es6.js 4.4 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747407484074940750407514075240753407544075540756407574075840759407604076140762407634076440765407664076740768407694077040771407724077340774407754077640777407784077940780407814078240783407844078540786407874078840789407904079140792407934079440795407964079740798407994080040801408024080340804408054080640807408084080940810408114081240813408144081540816408174081840819408204082140822408234082440825408264082740828408294083040831408324083340834408354083640837408384083940840408414084240843408444084540846408474084840849408504085140852408534085440855408564085740858408594086040861408624086340864408654086640867408684086940870408714087240873408744087540876408774087840879408804088140882408834088440885408864088740888408894089040891408924089340894408954089640897408984089940900409014090240903409044090540906409074090840909409104091140912409134091440915409164091740918409194092040921409224092340924409254092640927409284092940930409314093240933409344093540936409374093840939409404094140942409434094440945409464094740948409494095040951409524095340954409554095640957409584095940960409614096240963409644096540966409674096840969409704097140972409734097440975409764097740978409794098040981409824098340984409854098640987409884098940990409914099240993409944099540996409974099840999410004100141002410034100441005410064100741008410094101041011410124101341014410154101641017410184101941020410214102241023410244102541026410274102841029410304103141032410334103441035410364103741038410394104041041410424104341044410454104641047410484104941050410514105241053410544105541056410574105841059410604106141062410634106441065410664106741068410694107041071410724107341074410754107641077410784107941080410814108241083410844108541086410874108841089410904109141092410934109441095410964109741098410994110041101411024110341104411054110641107411084110941110411114111241113411144111541116411174111841119411204112141122411234112441125411264112741128411294113041131411324113341134411354113641137411384113941140411414114241143411444114541146411474114841149411504115141152411534115441155411564115741158411594116041161411624116341164411654116641167411684116941170411714117241173411744117541176411774117841179411804118141182411834118441185411864118741188411894119041191411924119341194411954119641197411984119941200412014120241203412044120541206412074120841209412104121141212412134121441215412164121741218412194122041221412224122341224412254122641227412284122941230412314123241233412344123541236412374123841239412404124141242412434124441245412464124741248412494125041251412524125341254412554125641257412584125941260412614126241263412644126541266412674126841269412704127141272412734127441275412764127741278412794128041281412824128341284412854128641287412884128941290412914129241293412944129541296412974129841299413004130141302413034130441305413064130741308413094131041311413124131341314413154131641317413184131941320413214132241323413244132541326413274132841329413304133141332413334133441335413364133741338413394134041341413424134341344413454134641347413484134941350413514135241353413544135541356413574135841359413604136141362413634136441365413664136741368413694137041371413724137341374413754137641377413784137941380413814138241383413844138541386413874138841389413904139141392413934139441395413964139741398413994140041401414024140341404414054140641407414084140941410414114141241413414144141541416414174141841419414204142141422414234142441425414264142741428414294143041431414324143341434414354143641437414384143941440414414144241443414444144541446414474144841449414504145141452414534145441455414564145741458414594146041461414624146341464414654146641467414684146941470414714147241473414744147541476414774147841479414804148141482414834148441485414864148741488414894149041491414924149341494414954149641497414984149941500415014150241503415044150541506415074150841509415104151141512415134151441515415164151741518415194152041521415224152341524415254152641527415284152941530415314153241533415344153541536415374153841539415404154141542415434154441545415464154741548415494155041551415524155341554415554155641557415584155941560415614156241563415644156541566415674156841569415704157141572415734157441575415764157741578415794158041581415824158341584415854158641587415884158941590415914159241593415944159541596415974159841599416004160141602416034160441605416064160741608416094161041611416124161341614416154161641617416184161941620416214162241623416244162541626416274162841629416304163141632416334163441635416364163741638416394164041641416424164341644416454164641647416484164941650416514165241653416544165541656416574165841659416604166141662416634166441665416664166741668416694167041671416724167341674416754167641677416784167941680416814168241683416844168541686416874168841689416904169141692416934169441695416964169741698416994170041701417024170341704417054170641707417084170941710417114171241713417144171541716417174171841719417204172141722417234172441725417264172741728417294173041731417324173341734417354173641737417384173941740417414174241743417444174541746417474174841749417504175141752417534175441755417564175741758417594176041761417624176341764417654176641767417684176941770417714177241773417744177541776417774177841779417804178141782417834178441785417864178741788417894179041791417924179341794417954179641797417984179941800418014180241803418044180541806418074180841809418104181141812418134181441815418164181741818418194182041821418224182341824418254182641827418284182941830418314183241833418344183541836418374183841839418404184141842418434184441845418464184741848418494185041851418524185341854418554185641857418584185941860418614186241863418644186541866418674186841869418704187141872418734187441875418764187741878418794188041881418824188341884418854188641887418884188941890418914189241893418944189541896418974189841899419004190141902419034190441905419064190741908419094191041911419124191341914419154191641917419184191941920419214192241923419244192541926419274192841929419304193141932419334193441935419364193741938419394194041941419424194341944419454194641947419484194941950419514195241953419544195541956419574195841959419604196141962419634196441965419664196741968419694197041971419724197341974419754197641977419784197941980419814198241983419844198541986419874198841989419904199141992419934199441995419964199741998419994200042001420024200342004420054200642007420084200942010420114201242013420144201542016420174201842019420204202142022420234202442025420264202742028420294203042031420324203342034420354203642037420384203942040420414204242043420444204542046420474204842049420504205142052420534205442055420564205742058420594206042061420624206342064420654206642067420684206942070420714207242073420744207542076420774207842079420804208142082420834208442085420864208742088420894209042091420924209342094420954209642097420984209942100421014210242103421044210542106421074210842109421104211142112421134211442115421164211742118421194212042121421224212342124421254212642127421284212942130421314213242133421344213542136421374213842139421404214142142421434214442145421464214742148421494215042151421524215342154421554215642157421584215942160421614216242163421644216542166421674216842169421704217142172421734217442175421764217742178421794218042181421824218342184421854218642187421884218942190421914219242193421944219542196421974219842199422004220142202422034220442205422064220742208422094221042211422124221342214422154221642217422184221942220422214222242223422244222542226422274222842229422304223142232422334223442235422364223742238422394224042241422424224342244422454224642247422484224942250422514225242253422544225542256422574225842259422604226142262422634226442265422664226742268422694227042271422724227342274422754227642277422784227942280422814228242283422844228542286422874228842289422904229142292422934229442295422964229742298422994230042301423024230342304423054230642307423084230942310423114231242313423144231542316423174231842319423204232142322423234232442325423264232742328423294233042331423324233342334423354233642337423384233942340423414234242343423444234542346423474234842349423504235142352423534235442355423564235742358423594236042361423624236342364423654236642367423684236942370423714237242373423744237542376423774237842379423804238142382423834238442385423864238742388423894239042391423924239342394423954239642397423984239942400424014240242403424044240542406424074240842409424104241142412424134241442415424164241742418424194242042421424224242342424424254242642427424284242942430424314243242433424344243542436424374243842439424404244142442424434244442445424464244742448424494245042451424524245342454424554245642457424584245942460424614246242463424644246542466424674246842469424704247142472424734247442475424764247742478424794248042481424824248342484424854248642487424884248942490424914249242493424944249542496424974249842499425004250142502425034250442505425064250742508425094251042511425124251342514425154251642517425184251942520425214252242523425244252542526425274252842529425304253142532425334253442535425364253742538425394254042541425424254342544425454254642547425484254942550425514255242553425544255542556425574255842559425604256142562425634256442565425664256742568425694257042571425724257342574425754257642577425784257942580425814258242583425844258542586425874258842589425904259142592425934259442595425964259742598425994260042601426024260342604426054260642607426084260942610426114261242613426144261542616426174261842619426204262142622426234262442625426264262742628426294263042631426324263342634426354263642637426384263942640426414264242643426444264542646426474264842649426504265142652426534265442655426564265742658426594266042661426624266342664426654266642667426684266942670426714267242673426744267542676426774267842679426804268142682426834268442685426864268742688426894269042691426924269342694426954269642697426984269942700427014270242703427044270542706427074270842709427104271142712427134271442715427164271742718427194272042721427224272342724427254272642727427284272942730427314273242733427344273542736427374273842739427404274142742427434274442745427464274742748427494275042751427524275342754427554275642757427584275942760427614276242763427644276542766427674276842769427704277142772427734277442775427764277742778427794278042781427824278342784427854278642787427884278942790427914279242793427944279542796427974279842799428004280142802428034280442805428064280742808428094281042811428124281342814428154281642817428184281942820428214282242823428244282542826428274282842829428304283142832428334283442835428364283742838428394284042841428424284342844428454284642847428484284942850428514285242853428544285542856428574285842859428604286142862428634286442865428664286742868428694287042871428724287342874428754287642877428784287942880428814288242883428844288542886428874288842889428904289142892428934289442895428964289742898428994290042901429024290342904429054290642907429084290942910429114291242913429144291542916429174291842919429204292142922429234292442925429264292742928429294293042931429324293342934429354293642937429384293942940429414294242943429444294542946429474294842949429504295142952429534295442955429564295742958429594296042961429624296342964429654296642967429684296942970429714297242973429744297542976429774297842979429804298142982429834298442985429864298742988429894299042991429924299342994429954299642997429984299943000430014300243003430044300543006430074300843009430104301143012430134301443015430164301743018430194302043021430224302343024430254302643027430284302943030430314303243033430344303543036430374303843039430404304143042430434304443045430464304743048430494305043051430524305343054430554305643057430584305943060430614306243063430644306543066430674306843069430704307143072430734307443075430764307743078430794308043081430824308343084430854308643087430884308943090430914309243093430944309543096430974309843099431004310143102431034310443105431064310743108431094311043111431124311343114431154311643117431184311943120431214312243123431244312543126431274312843129431304313143132431334313443135431364313743138431394314043141431424314343144431454314643147431484314943150431514315243153431544315543156431574315843159431604316143162431634316443165431664316743168431694317043171431724317343174431754317643177431784317943180431814318243183431844318543186431874318843189431904319143192431934319443195431964319743198431994320043201432024320343204432054320643207432084320943210432114321243213432144321543216432174321843219432204322143222432234322443225432264322743228432294323043231432324323343234432354323643237432384323943240432414324243243432444324543246432474324843249432504325143252432534325443255432564325743258432594326043261432624326343264432654326643267432684326943270432714327243273432744327543276432774327843279432804328143282432834328443285432864328743288432894329043291432924329343294432954329643297432984329943300433014330243303433044330543306433074330843309433104331143312433134331443315433164331743318433194332043321433224332343324433254332643327433284332943330433314333243333433344333543336433374333843339433404334143342433434334443345433464334743348433494335043351433524335343354433554335643357433584335943360433614336243363433644336543366433674336843369433704337143372433734337443375433764337743378433794338043381433824338343384433854338643387433884338943390433914339243393433944339543396433974339843399434004340143402434034340443405434064340743408434094341043411434124341343414434154341643417434184341943420434214342243423434244342543426434274342843429434304343143432434334343443435434364343743438434394344043441434424344343444434454344643447434484344943450434514345243453434544345543456434574345843459434604346143462434634346443465434664346743468434694347043471434724347343474434754347643477434784347943480434814348243483434844348543486434874348843489434904349143492434934349443495434964349743498434994350043501435024350343504435054350643507435084350943510435114351243513435144351543516435174351843519435204352143522435234352443525435264352743528435294353043531435324353343534435354353643537435384353943540435414354243543435444354543546435474354843549435504355143552435534355443555435564355743558435594356043561435624356343564435654356643567435684356943570435714357243573435744357543576435774357843579435804358143582435834358443585435864358743588435894359043591435924359343594435954359643597435984359943600436014360243603436044360543606436074360843609436104361143612436134361443615436164361743618436194362043621436224362343624436254362643627436284362943630436314363243633436344363543636436374363843639436404364143642436434364443645436464364743648436494365043651436524365343654436554365643657436584365943660436614366243663436644366543666436674366843669436704367143672436734367443675436764367743678436794368043681436824368343684436854368643687436884368943690436914369243693436944369543696436974369843699437004370143702437034370443705437064370743708437094371043711437124371343714437154371643717437184371943720437214372243723437244372543726437274372843729437304373143732437334373443735437364373743738437394374043741437424374343744437454374643747437484374943750437514375243753437544375543756437574375843759437604376143762437634376443765437664376743768437694377043771437724377343774437754377643777437784377943780437814378243783437844378543786437874378843789437904379143792437934379443795437964379743798437994380043801438024380343804438054380643807438084380943810438114381243813438144381543816438174381843819438204382143822438234382443825438264382743828438294383043831438324383343834438354383643837438384383943840438414384243843438444384543846438474384843849438504385143852438534385443855438564385743858438594386043861438624386343864438654386643867438684386943870438714387243873438744387543876438774387843879438804388143882438834388443885438864388743888438894389043891438924389343894438954389643897438984389943900439014390243903439044390543906439074390843909439104391143912439134391443915439164391743918439194392043921439224392343924439254392643927439284392943930439314393243933439344393543936439374393843939439404394143942439434394443945439464394743948439494395043951439524395343954439554395643957439584395943960439614396243963439644396543966439674396843969439704397143972439734397443975439764397743978439794398043981439824398343984439854398643987439884398943990439914399243993439944399543996439974399843999440004400144002440034400444005440064400744008440094401044011440124401344014440154401644017440184401944020440214402244023440244402544026440274402844029440304403144032440334403444035440364403744038440394404044041440424404344044440454404644047440484404944050440514405244053440544405544056440574405844059440604406144062440634406444065440664406744068440694407044071440724407344074440754407644077440784407944080440814408244083440844408544086440874408844089440904409144092440934409444095440964409744098440994410044101441024410344104441054410644107441084410944110441114411244113441144411544116441174411844119441204412144122441234412444125441264412744128441294413044131441324413344134441354413644137441384413944140441414414244143441444414544146441474414844149441504415144152441534415444155441564415744158441594416044161441624416344164441654416644167441684416944170441714417244173441744417544176441774417844179441804418144182441834418444185441864418744188441894419044191441924419344194441954419644197441984419944200442014420244203442044420544206442074420844209442104421144212442134421444215442164421744218442194422044221442224422344224442254422644227442284422944230442314423244233442344423544236442374423844239442404424144242442434424444245442464424744248442494425044251442524425344254442554425644257442584425944260442614426244263442644426544266442674426844269442704427144272442734427444275442764427744278442794428044281442824428344284442854428644287442884428944290442914429244293442944429544296442974429844299443004430144302443034430444305443064430744308443094431044311443124431344314443154431644317443184431944320443214432244323443244432544326443274432844329443304433144332443334433444335443364433744338443394434044341443424434344344443454434644347443484434944350443514435244353443544435544356443574435844359443604436144362443634436444365443664436744368443694437044371443724437344374443754437644377443784437944380443814438244383443844438544386443874438844389443904439144392443934439444395443964439744398443994440044401444024440344404444054440644407444084440944410444114441244413444144441544416444174441844419444204442144422444234442444425444264442744428444294443044431444324443344434444354443644437444384443944440444414444244443444444444544446444474444844449444504445144452444534445444455444564445744458444594446044461444624446344464444654446644467444684446944470444714447244473444744447544476444774447844479444804448144482444834448444485444864448744488444894449044491444924449344494444954449644497444984449944500445014450244503445044450544506445074450844509445104451144512445134451444515445164451744518445194452044521445224452344524445254452644527445284452944530445314453244533445344453544536445374453844539445404454144542445434454444545445464454744548445494455044551445524455344554445554455644557445584455944560445614456244563445644456544566445674456844569445704457144572445734457444575445764457744578445794458044581445824458344584445854458644587445884458944590445914459244593445944459544596445974459844599446004460144602446034460444605446064460744608446094461044611446124461344614446154461644617446184461944620446214462244623446244462544626446274462844629446304463144632446334463444635446364463744638446394464044641446424464344644446454464644647446484464944650446514465244653446544465544656446574465844659446604466144662446634466444665446664466744668446694467044671446724467344674446754467644677446784467944680446814468244683446844468544686446874468844689446904469144692446934469444695446964469744698446994470044701447024470344704447054470644707447084470944710447114471244713447144471544716447174471844719447204472144722447234472444725447264472744728447294473044731447324473344734447354473644737447384473944740447414474244743447444474544746447474474844749447504475144752447534475444755447564475744758447594476044761447624476344764447654476644767447684476944770447714477244773447744477544776447774477844779447804478144782447834478444785447864478744788447894479044791447924479344794447954479644797447984479944800448014480244803448044480544806448074480844809448104481144812448134481444815448164481744818448194482044821448224482344824448254482644827448284482944830448314483244833448344483544836448374483844839448404484144842448434484444845448464484744848448494485044851448524485344854448554485644857448584485944860448614486244863448644486544866448674486844869448704487144872448734487444875448764487744878448794488044881448824488344884448854488644887448884488944890448914489244893448944489544896448974489844899449004490144902449034490444905449064490744908449094491044911449124491344914449154491644917449184491944920449214492244923449244492544926449274492844929449304493144932449334493444935449364493744938449394494044941449424494344944449454494644947449484494944950449514495244953449544495544956449574495844959449604496144962449634496444965449664496744968449694497044971449724497344974449754497644977449784497944980449814498244983449844498544986449874498844989449904499144992449934499444995449964499744998449994500045001450024500345004450054500645007450084500945010450114501245013450144501545016450174501845019450204502145022450234502445025450264502745028450294503045031450324503345034450354503645037450384503945040450414504245043450444504545046450474504845049450504505145052450534505445055450564505745058450594506045061450624506345064450654506645067450684506945070450714507245073450744507545076450774507845079450804508145082450834508445085450864508745088450894509045091450924509345094450954509645097450984509945100451014510245103451044510545106451074510845109451104511145112451134511445115451164511745118451194512045121451224512345124451254512645127451284512945130451314513245133451344513545136451374513845139451404514145142451434514445145451464514745148451494515045151451524515345154451554515645157451584515945160451614516245163451644516545166451674516845169451704517145172451734517445175451764517745178451794518045181451824518345184451854518645187451884518945190451914519245193451944519545196451974519845199452004520145202452034520445205452064520745208452094521045211452124521345214452154521645217452184521945220452214522245223452244522545226452274522845229452304523145232452334523445235452364523745238452394524045241452424524345244452454524645247452484524945250452514525245253452544525545256452574525845259452604526145262452634526445265452664526745268452694527045271452724527345274452754527645277452784527945280452814528245283452844528545286452874528845289452904529145292452934529445295452964529745298452994530045301453024530345304453054530645307453084530945310453114531245313453144531545316453174531845319453204532145322453234532445325453264532745328453294533045331453324533345334453354533645337453384533945340453414534245343453444534545346453474534845349453504535145352453534535445355453564535745358453594536045361453624536345364453654536645367453684536945370453714537245373453744537545376453774537845379453804538145382453834538445385453864538745388453894539045391453924539345394453954539645397453984539945400454014540245403454044540545406454074540845409454104541145412454134541445415454164541745418454194542045421454224542345424454254542645427454284542945430454314543245433454344543545436454374543845439454404544145442454434544445445454464544745448454494545045451454524545345454454554545645457454584545945460454614546245463454644546545466454674546845469454704547145472454734547445475454764547745478454794548045481454824548345484454854548645487454884548945490454914549245493454944549545496454974549845499455004550145502455034550445505455064550745508455094551045511455124551345514455154551645517455184551945520455214552245523455244552545526455274552845529455304553145532455334553445535455364553745538455394554045541455424554345544455454554645547455484554945550455514555245553455544555545556455574555845559455604556145562455634556445565455664556745568455694557045571455724557345574455754557645577455784557945580455814558245583455844558545586455874558845589455904559145592455934559445595455964559745598455994560045601456024560345604456054560645607456084560945610456114561245613456144561545616456174561845619456204562145622456234562445625456264562745628456294563045631456324563345634456354563645637456384563945640456414564245643456444564545646456474564845649456504565145652456534565445655456564565745658456594566045661456624566345664456654566645667456684566945670456714567245673456744567545676456774567845679456804568145682456834568445685456864568745688456894569045691456924569345694456954569645697456984569945700457014570245703457044570545706457074570845709457104571145712457134571445715457164571745718457194572045721457224572345724457254572645727457284572945730457314573245733457344573545736457374573845739457404574145742457434574445745457464574745748457494575045751457524575345754457554575645757457584575945760457614576245763457644576545766457674576845769457704577145772457734577445775457764577745778457794578045781457824578345784457854578645787457884578945790457914579245793457944579545796457974579845799458004580145802458034580445805458064580745808458094581045811458124581345814458154581645817458184581945820458214582245823458244582545826458274582845829458304583145832458334583445835458364583745838458394584045841458424584345844458454584645847458484584945850458514585245853458544585545856458574585845859458604586145862458634586445865458664586745868458694587045871458724587345874458754587645877458784587945880458814588245883458844588545886458874588845889458904589145892458934589445895458964589745898458994590045901459024590345904459054590645907459084590945910459114591245913459144591545916459174591845919459204592145922459234592445925459264592745928459294593045931459324593345934459354593645937459384593945940459414594245943459444594545946459474594845949459504595145952459534595445955459564595745958459594596045961459624596345964459654596645967459684596945970459714597245973459744597545976459774597845979459804598145982459834598445985459864598745988459894599045991459924599345994459954599645997459984599946000460014600246003460044600546006460074600846009460104601146012460134601446015460164601746018460194602046021460224602346024460254602646027460284602946030460314603246033460344603546036460374603846039460404604146042460434604446045460464604746048460494605046051460524605346054460554605646057460584605946060460614606246063460644606546066460674606846069460704607146072460734607446075460764607746078460794608046081460824608346084460854608646087460884608946090460914609246093460944609546096460974609846099461004610146102461034610446105461064610746108461094611046111461124611346114461154611646117461184611946120461214612246123461244612546126461274612846129461304613146132461334613446135461364613746138461394614046141461424614346144461454614646147461484614946150461514615246153461544615546156461574615846159461604616146162461634616446165461664616746168461694617046171461724617346174461754617646177461784617946180461814618246183461844618546186461874618846189461904619146192461934619446195461964619746198461994620046201462024620346204462054620646207462084620946210462114621246213462144621546216462174621846219462204622146222462234622446225462264622746228462294623046231462324623346234462354623646237462384623946240462414624246243462444624546246462474624846249462504625146252462534625446255462564625746258462594626046261462624626346264462654626646267462684626946270462714627246273462744627546276462774627846279462804628146282462834628446285462864628746288462894629046291462924629346294462954629646297462984629946300463014630246303463044630546306463074630846309463104631146312463134631446315463164631746318463194632046321463224632346324463254632646327463284632946330463314633246333463344633546336463374633846339463404634146342463434634446345463464634746348463494635046351463524635346354463554635646357463584635946360463614636246363463644636546366463674636846369463704637146372463734637446375463764637746378463794638046381463824638346384463854638646387463884638946390463914639246393463944639546396463974639846399464004640146402464034640446405464064640746408464094641046411464124641346414464154641646417464184641946420464214642246423464244642546426464274642846429464304643146432464334643446435464364643746438464394644046441464424644346444464454644646447464484644946450464514645246453464544645546456464574645846459464604646146462464634646446465464664646746468464694647046471464724647346474464754647646477464784647946480464814648246483464844648546486464874648846489464904649146492464934649446495464964649746498464994650046501465024650346504465054650646507465084650946510465114651246513465144651546516465174651846519465204652146522465234652446525465264652746528465294653046531465324653346534465354653646537465384653946540465414654246543465444654546546465474654846549465504655146552465534655446555465564655746558465594656046561465624656346564465654656646567465684656946570465714657246573465744657546576465774657846579465804658146582465834658446585465864658746588465894659046591465924659346594465954659646597465984659946600466014660246603466044660546606466074660846609466104661146612466134661446615466164661746618466194662046621466224662346624466254662646627466284662946630466314663246633466344663546636466374663846639466404664146642466434664446645466464664746648466494665046651466524665346654466554665646657466584665946660466614666246663466644666546666466674666846669466704667146672466734667446675466764667746678466794668046681466824668346684466854668646687466884668946690466914669246693466944669546696466974669846699467004670146702467034670446705467064670746708467094671046711467124671346714467154671646717467184671946720467214672246723467244672546726467274672846729467304673146732467334673446735467364673746738467394674046741467424674346744467454674646747467484674946750467514675246753467544675546756467574675846759467604676146762467634676446765467664676746768467694677046771467724677346774467754677646777467784677946780467814678246783467844678546786467874678846789467904679146792467934679446795467964679746798467994680046801468024680346804468054680646807468084680946810468114681246813468144681546816468174681846819468204682146822468234682446825468264682746828468294683046831468324683346834468354683646837468384683946840468414684246843468444684546846468474684846849468504685146852468534685446855468564685746858468594686046861468624686346864468654686646867468684686946870468714687246873468744687546876468774687846879468804688146882468834688446885468864688746888468894689046891468924689346894468954689646897468984689946900469014690246903469044690546906469074690846909469104691146912469134691446915469164691746918469194692046921469224692346924469254692646927469284692946930469314693246933469344693546936469374693846939469404694146942469434694446945469464694746948469494695046951469524695346954469554695646957469584695946960469614696246963469644696546966469674696846969469704697146972469734697446975469764697746978469794698046981469824698346984469854698646987469884698946990469914699246993469944699546996469974699846999470004700147002470034700447005470064700747008470094701047011470124701347014470154701647017470184701947020470214702247023470244702547026470274702847029470304703147032470334703447035470364703747038470394704047041470424704347044470454704647047470484704947050470514705247053470544705547056470574705847059470604706147062470634706447065470664706747068470694707047071470724707347074470754707647077470784707947080470814708247083470844708547086470874708847089470904709147092470934709447095470964709747098470994710047101471024710347104471054710647107471084710947110471114711247113471144711547116471174711847119471204712147122471234712447125471264712747128471294713047131471324713347134471354713647137471384713947140471414714247143471444714547146471474714847149471504715147152471534715447155471564715747158471594716047161471624716347164471654716647167471684716947170471714717247173471744717547176471774717847179471804718147182471834718447185471864718747188471894719047191471924719347194471954719647197471984719947200472014720247203472044720547206472074720847209472104721147212472134721447215472164721747218472194722047221472224722347224472254722647227472284722947230472314723247233472344723547236472374723847239472404724147242472434724447245472464724747248472494725047251472524725347254472554725647257472584725947260472614726247263472644726547266472674726847269472704727147272472734727447275472764727747278472794728047281472824728347284472854728647287472884728947290472914729247293472944729547296472974729847299473004730147302473034730447305473064730747308473094731047311473124731347314473154731647317473184731947320473214732247323473244732547326473274732847329473304733147332473334733447335473364733747338473394734047341473424734347344473454734647347473484734947350473514735247353473544735547356473574735847359473604736147362473634736447365473664736747368473694737047371473724737347374473754737647377473784737947380473814738247383473844738547386473874738847389473904739147392473934739447395473964739747398473994740047401474024740347404474054740647407474084740947410474114741247413474144741547416474174741847419474204742147422474234742447425474264742747428474294743047431474324743347434474354743647437474384743947440474414744247443474444744547446474474744847449474504745147452474534745447455474564745747458474594746047461474624746347464474654746647467474684746947470474714747247473474744747547476474774747847479474804748147482474834748447485474864748747488474894749047491474924749347494474954749647497474984749947500475014750247503475044750547506475074750847509475104751147512475134751447515475164751747518475194752047521475224752347524475254752647527475284752947530475314753247533475344753547536475374753847539475404754147542475434754447545475464754747548475494755047551475524755347554475554755647557475584755947560475614756247563475644756547566475674756847569475704757147572475734757447575475764757747578475794758047581475824758347584475854758647587475884758947590475914759247593475944759547596475974759847599476004760147602476034760447605476064760747608476094761047611476124761347614476154761647617476184761947620476214762247623476244762547626476274762847629476304763147632476334763447635476364763747638476394764047641476424764347644476454764647647476484764947650476514765247653476544765547656476574765847659476604766147662476634766447665476664766747668476694767047671476724767347674476754767647677476784767947680476814768247683476844768547686476874768847689476904769147692476934769447695476964769747698476994770047701477024770347704477054770647707477084770947710477114771247713477144771547716477174771847719477204772147722477234772447725477264772747728477294773047731477324773347734477354773647737477384773947740477414774247743477444774547746477474774847749477504775147752477534775447755477564775747758477594776047761477624776347764477654776647767477684776947770477714777247773477744777547776477774777847779477804778147782477834778447785477864778747788477894779047791477924779347794477954779647797477984779947800478014780247803478044780547806478074780847809478104781147812478134781447815478164781747818478194782047821478224782347824478254782647827478284782947830478314783247833478344783547836478374783847839478404784147842478434784447845478464784747848478494785047851478524785347854478554785647857478584785947860478614786247863478644786547866478674786847869478704787147872478734787447875478764787747878478794788047881478824788347884478854788647887478884788947890478914789247893478944789547896478974789847899479004790147902479034790447905479064790747908479094791047911479124791347914479154791647917479184791947920479214792247923479244792547926479274792847929479304793147932479334793447935479364793747938479394794047941479424794347944479454794647947479484794947950479514795247953479544795547956479574795847959479604796147962479634796447965479664796747968479694797047971479724797347974479754797647977479784797947980479814798247983479844798547986479874798847989479904799147992479934799447995479964799747998479994800048001480024800348004480054800648007480084800948010480114801248013480144801548016480174801848019480204802148022480234802448025480264802748028480294803048031480324803348034480354803648037480384803948040480414804248043480444804548046480474804848049480504805148052480534805448055480564805748058480594806048061480624806348064480654806648067480684806948070480714807248073480744807548076480774807848079480804808148082480834808448085480864808748088480894809048091480924809348094480954809648097480984809948100481014810248103481044810548106481074810848109481104811148112481134811448115481164811748118481194812048121481224812348124481254812648127481284812948130481314813248133481344813548136481374813848139481404814148142481434814448145481464814748148481494815048151481524815348154481554815648157481584815948160481614816248163481644816548166481674816848169481704817148172481734817448175481764817748178481794818048181481824818348184481854818648187481884818948190481914819248193481944819548196481974819848199482004820148202482034820448205482064820748208482094821048211482124821348214482154821648217482184821948220482214822248223482244822548226482274822848229482304823148232482334823448235482364823748238482394824048241482424824348244482454824648247482484824948250482514825248253482544825548256482574825848259482604826148262482634826448265482664826748268482694827048271482724827348274482754827648277482784827948280482814828248283482844828548286482874828848289482904829148292482934829448295482964829748298482994830048301483024830348304483054830648307483084830948310483114831248313483144831548316483174831848319483204832148322483234832448325483264832748328483294833048331483324833348334483354833648337483384833948340483414834248343483444834548346483474834848349483504835148352483534835448355483564835748358483594836048361483624836348364483654836648367483684836948370483714837248373483744837548376483774837848379483804838148382483834838448385483864838748388483894839048391483924839348394483954839648397483984839948400484014840248403484044840548406484074840848409484104841148412484134841448415484164841748418484194842048421484224842348424484254842648427484284842948430484314843248433484344843548436484374843848439484404844148442484434844448445484464844748448484494845048451484524845348454484554845648457484584845948460484614846248463484644846548466484674846848469484704847148472484734847448475484764847748478484794848048481484824848348484484854848648487484884848948490484914849248493484944849548496484974849848499485004850148502485034850448505485064850748508485094851048511485124851348514485154851648517485184851948520485214852248523485244852548526485274852848529485304853148532485334853448535485364853748538485394854048541485424854348544485454854648547485484854948550485514855248553485544855548556485574855848559485604856148562485634856448565485664856748568485694857048571485724857348574485754857648577485784857948580485814858248583485844858548586485874858848589485904859148592485934859448595485964859748598485994860048601486024860348604486054860648607486084860948610486114861248613486144861548616486174861848619486204862148622486234862448625486264862748628486294863048631486324863348634486354863648637486384863948640486414864248643486444864548646486474864848649486504865148652486534865448655486564865748658486594866048661486624866348664486654866648667486684866948670486714867248673486744867548676486774867848679486804868148682486834868448685486864868748688486894869048691486924869348694486954869648697486984869948700487014870248703487044870548706487074870848709487104871148712487134871448715487164871748718487194872048721487224872348724487254872648727487284872948730487314873248733487344873548736487374873848739487404874148742487434874448745487464874748748487494875048751487524875348754487554875648757487584875948760487614876248763487644876548766487674876848769487704877148772487734877448775487764877748778487794878048781487824878348784487854878648787487884878948790487914879248793487944879548796487974879848799488004880148802488034880448805488064880748808488094881048811488124881348814488154881648817488184881948820488214882248823488244882548826488274882848829488304883148832488334883448835488364883748838488394884048841488424884348844488454884648847488484884948850488514885248853488544885548856488574885848859488604886148862488634886448865488664886748868488694887048871488724887348874488754887648877488784887948880488814888248883488844888548886488874888848889488904889148892488934889448895488964889748898488994890048901489024890348904489054890648907489084890948910489114891248913489144891548916489174891848919489204892148922489234892448925489264892748928489294893048931489324893348934489354893648937489384893948940489414894248943489444894548946489474894848949489504895148952489534895448955489564895748958489594896048961489624896348964489654896648967489684896948970489714897248973489744897548976489774897848979489804898148982489834898448985489864898748988489894899048991489924899348994489954899648997489984899949000490014900249003490044900549006490074900849009490104901149012490134901449015490164901749018490194902049021490224902349024490254902649027490284902949030490314903249033490344903549036490374903849039490404904149042490434904449045490464904749048490494905049051490524905349054490554905649057490584905949060490614906249063490644906549066490674906849069490704907149072490734907449075490764907749078490794908049081490824908349084490854908649087490884908949090490914909249093490944909549096490974909849099491004910149102491034910449105491064910749108491094911049111491124911349114491154911649117491184911949120491214912249123491244912549126491274912849129491304913149132491334913449135491364913749138491394914049141491424914349144491454914649147491484914949150491514915249153491544915549156491574915849159491604916149162491634916449165491664916749168491694917049171491724917349174491754917649177491784917949180491814918249183491844918549186491874918849189491904919149192491934919449195491964919749198491994920049201492024920349204492054920649207492084920949210492114921249213492144921549216492174921849219492204922149222492234922449225492264922749228492294923049231492324923349234492354923649237492384923949240492414924249243492444924549246492474924849249492504925149252492534925449255492564925749258492594926049261492624926349264492654926649267492684926949270492714927249273492744927549276492774927849279492804928149282492834928449285492864928749288492894929049291492924929349294492954929649297492984929949300493014930249303493044930549306493074930849309493104931149312493134931449315493164931749318493194932049321493224932349324493254932649327493284932949330493314933249333493344933549336493374933849339493404934149342493434934449345493464934749348493494935049351493524935349354493554935649357493584935949360493614936249363493644936549366493674936849369493704937149372493734937449375493764937749378493794938049381493824938349384493854938649387493884938949390493914939249393493944939549396493974939849399494004940149402494034940449405494064940749408494094941049411494124941349414494154941649417494184941949420494214942249423494244942549426494274942849429494304943149432494334943449435494364943749438494394944049441494424944349444494454944649447494484944949450494514945249453494544945549456494574945849459494604946149462494634946449465494664946749468494694947049471494724947349474494754947649477494784947949480494814948249483494844948549486494874948849489494904949149492494934949449495494964949749498494994950049501495024950349504495054950649507495084950949510495114951249513495144951549516495174951849519495204952149522495234952449525495264952749528495294953049531495324953349534495354953649537495384953949540495414954249543495444954549546495474954849549495504955149552495534955449555495564955749558495594956049561495624956349564495654956649567495684956949570495714957249573495744957549576495774957849579495804958149582495834958449585495864958749588495894959049591495924959349594495954959649597495984959949600496014960249603496044960549606496074960849609496104961149612496134961449615496164961749618496194962049621496224962349624496254962649627496284962949630496314963249633496344963549636496374963849639496404964149642496434964449645496464964749648496494965049651496524965349654496554965649657496584965949660496614966249663496644966549666496674966849669496704967149672496734967449675496764967749678496794968049681496824968349684496854968649687496884968949690496914969249693496944969549696496974969849699497004970149702497034970449705497064970749708497094971049711497124971349714497154971649717497184971949720497214972249723497244972549726497274972849729497304973149732497334973449735497364973749738497394974049741497424974349744497454974649747497484974949750497514975249753497544975549756497574975849759497604976149762497634976449765497664976749768497694977049771497724977349774497754977649777497784977949780497814978249783497844978549786497874978849789497904979149792497934979449795497964979749798497994980049801498024980349804498054980649807498084980949810498114981249813498144981549816498174981849819498204982149822498234982449825498264982749828498294983049831498324983349834498354983649837498384983949840498414984249843498444984549846498474984849849498504985149852498534985449855498564985749858498594986049861498624986349864498654986649867498684986949870498714987249873498744987549876498774987849879498804988149882498834988449885498864988749888498894989049891498924989349894498954989649897498984989949900499014990249903499044990549906499074990849909499104991149912499134991449915499164991749918499194992049921499224992349924499254992649927499284992949930499314993249933499344993549936499374993849939499404994149942499434994449945499464994749948499494995049951499524995349954499554995649957499584995949960499614996249963499644996549966499674996849969499704997149972499734997449975499764997749978499794998049981499824998349984499854998649987499884998949990499914999249993499944999549996499974999849999500005000150002500035000450005500065000750008500095001050011500125001350014500155001650017500185001950020500215002250023500245002550026500275002850029500305003150032500335003450035500365003750038500395004050041500425004350044500455004650047500485004950050500515005250053500545005550056500575005850059500605006150062500635006450065500665006750068500695007050071500725007350074500755007650077500785007950080500815008250083500845008550086500875008850089500905009150092500935009450095500965009750098500995010050101501025010350104501055010650107501085010950110501115011250113501145011550116501175011850119501205012150122501235012450125501265012750128501295013050131501325013350134501355013650137501385013950140501415014250143501445014550146501475014850149501505015150152501535015450155501565015750158501595016050161501625016350164501655016650167501685016950170501715017250173501745017550176501775017850179501805018150182501835018450185501865018750188501895019050191501925019350194501955019650197501985019950200502015020250203502045020550206502075020850209502105021150212502135021450215502165021750218502195022050221502225022350224502255022650227502285022950230502315023250233502345023550236502375023850239502405024150242502435024450245502465024750248502495025050251502525025350254502555025650257502585025950260502615026250263502645026550266502675026850269502705027150272502735027450275502765027750278502795028050281502825028350284502855028650287502885028950290502915029250293502945029550296502975029850299503005030150302503035030450305503065030750308503095031050311503125031350314503155031650317503185031950320503215032250323503245032550326503275032850329503305033150332503335033450335503365033750338503395034050341503425034350344503455034650347503485034950350503515035250353503545035550356503575035850359503605036150362503635036450365503665036750368503695037050371503725037350374503755037650377503785037950380503815038250383503845038550386503875038850389503905039150392503935039450395503965039750398503995040050401504025040350404504055040650407504085040950410504115041250413504145041550416504175041850419504205042150422504235042450425504265042750428504295043050431504325043350434504355043650437504385043950440504415044250443504445044550446504475044850449504505045150452504535045450455504565045750458504595046050461504625046350464504655046650467504685046950470504715047250473504745047550476504775047850479504805048150482504835048450485504865048750488504895049050491504925049350494504955049650497504985049950500505015050250503505045050550506505075050850509505105051150512505135051450515505165051750518505195052050521505225052350524505255052650527505285052950530505315053250533505345053550536505375053850539505405054150542505435054450545505465054750548505495055050551505525055350554505555055650557505585055950560505615056250563505645056550566505675056850569505705057150572505735057450575505765057750578505795058050581505825058350584505855058650587505885058950590505915059250593505945059550596505975059850599506005060150602506035060450605506065060750608506095061050611506125061350614506155061650617506185061950620506215062250623506245062550626506275062850629506305063150632506335063450635506365063750638506395064050641506425064350644506455064650647506485064950650506515065250653506545065550656506575065850659506605066150662506635066450665506665066750668506695067050671506725067350674506755067650677506785067950680506815068250683506845068550686506875068850689506905069150692506935069450695506965069750698506995070050701507025070350704507055070650707507085070950710507115071250713507145071550716507175071850719507205072150722507235072450725507265072750728507295073050731507325073350734507355073650737507385073950740507415074250743507445074550746507475074850749507505075150752507535075450755507565075750758507595076050761507625076350764507655076650767507685076950770507715077250773507745077550776507775077850779507805078150782507835078450785507865078750788507895079050791507925079350794507955079650797507985079950800508015080250803508045080550806508075080850809508105081150812508135081450815508165081750818508195082050821508225082350824508255082650827508285082950830508315083250833508345083550836508375083850839508405084150842508435084450845508465084750848508495085050851508525085350854508555085650857508585085950860508615086250863508645086550866508675086850869508705087150872508735087450875508765087750878508795088050881508825088350884508855088650887508885088950890508915089250893508945089550896508975089850899509005090150902509035090450905509065090750908509095091050911509125091350914509155091650917509185091950920509215092250923509245092550926509275092850929509305093150932509335093450935509365093750938509395094050941509425094350944509455094650947509485094950950509515095250953509545095550956509575095850959509605096150962509635096450965509665096750968509695097050971509725097350974509755097650977509785097950980509815098250983509845098550986509875098850989509905099150992509935099450995509965099750998509995100051001510025100351004510055100651007510085100951010510115101251013510145101551016510175101851019510205102151022510235102451025510265102751028510295103051031510325103351034510355103651037510385103951040510415104251043510445104551046510475104851049510505105151052510535105451055510565105751058510595106051061510625106351064510655106651067510685106951070510715107251073510745107551076510775107851079510805108151082510835108451085510865108751088510895109051091510925109351094510955109651097510985109951100511015110251103511045110551106511075110851109511105111151112511135111451115511165111751118511195112051121511225112351124511255112651127511285112951130511315113251133511345113551136511375113851139511405114151142511435114451145511465114751148511495115051151511525115351154511555115651157511585115951160511615116251163511645116551166511675116851169511705117151172511735117451175511765117751178511795118051181511825118351184511855118651187511885118951190511915119251193511945119551196511975119851199512005120151202512035120451205512065120751208512095121051211512125121351214512155121651217512185121951220512215122251223512245122551226512275122851229512305123151232512335123451235512365123751238512395124051241512425124351244512455124651247512485124951250512515125251253512545125551256512575125851259512605126151262512635126451265512665126751268512695127051271512725127351274512755127651277512785127951280512815128251283512845128551286512875128851289512905129151292512935129451295512965129751298512995130051301513025130351304513055130651307513085130951310513115131251313513145131551316513175131851319513205132151322513235132451325513265132751328513295133051331513325133351334513355133651337513385133951340513415134251343513445134551346513475134851349513505135151352513535135451355513565135751358513595136051361513625136351364513655136651367513685136951370513715137251373513745137551376513775137851379513805138151382513835138451385513865138751388513895139051391513925139351394513955139651397513985139951400514015140251403514045140551406514075140851409514105141151412514135141451415514165141751418514195142051421514225142351424514255142651427514285142951430514315143251433514345143551436514375143851439514405144151442514435144451445514465144751448514495145051451514525145351454514555145651457514585145951460514615146251463514645146551466514675146851469514705147151472514735147451475514765147751478514795148051481514825148351484514855148651487514885148951490514915149251493514945149551496514975149851499515005150151502515035150451505515065150751508515095151051511515125151351514515155151651517515185151951520515215152251523515245152551526515275152851529515305153151532515335153451535515365153751538515395154051541515425154351544515455154651547515485154951550515515155251553515545155551556515575155851559515605156151562515635156451565515665156751568515695157051571515725157351574515755157651577515785157951580515815158251583515845158551586515875158851589515905159151592515935159451595515965159751598515995160051601516025160351604516055160651607516085160951610516115161251613516145161551616516175161851619516205162151622516235162451625516265162751628516295163051631516325163351634516355163651637516385163951640516415164251643516445164551646516475164851649516505165151652516535165451655516565165751658516595166051661516625166351664516655166651667516685166951670516715167251673516745167551676516775167851679516805168151682516835168451685516865168751688516895169051691516925169351694516955169651697516985169951700517015170251703517045170551706517075170851709517105171151712517135171451715517165171751718517195172051721517225172351724517255172651727517285172951730517315173251733517345173551736517375173851739517405174151742517435174451745517465174751748517495175051751517525175351754517555175651757517585175951760517615176251763517645176551766517675176851769517705177151772517735177451775517765177751778517795178051781517825178351784517855178651787517885178951790517915179251793517945179551796517975179851799518005180151802518035180451805518065180751808518095181051811518125181351814518155181651817518185181951820518215182251823518245182551826518275182851829518305183151832518335183451835518365183751838518395184051841518425184351844518455184651847518485184951850518515185251853518545185551856518575185851859518605186151862518635186451865518665186751868518695187051871518725187351874518755187651877518785187951880518815188251883518845188551886518875188851889518905189151892518935189451895518965189751898518995190051901519025190351904519055190651907519085190951910519115191251913519145191551916519175191851919519205192151922519235192451925519265192751928519295193051931519325193351934519355193651937519385193951940519415194251943519445194551946519475194851949519505195151952519535195451955519565195751958519595196051961519625196351964519655196651967519685196951970519715197251973519745197551976519775197851979519805198151982519835198451985519865198751988519895199051991519925199351994519955199651997519985199952000520015200252003520045200552006520075200852009520105201152012520135201452015520165201752018520195202052021520225202352024520255202652027520285202952030520315203252033520345203552036520375203852039520405204152042520435204452045520465204752048520495205052051520525205352054520555205652057520585205952060520615206252063520645206552066520675206852069520705207152072520735207452075520765207752078520795208052081520825208352084520855208652087520885208952090520915209252093520945209552096520975209852099521005210152102521035210452105521065210752108521095211052111521125211352114521155211652117521185211952120521215212252123521245212552126521275212852129521305213152132521335213452135521365213752138521395214052141521425214352144521455214652147521485214952150521515215252153521545215552156521575215852159521605216152162521635216452165521665216752168521695217052171521725217352174521755217652177521785217952180521815218252183521845218552186521875218852189521905219152192521935219452195521965219752198521995220052201522025220352204522055220652207522085220952210522115221252213522145221552216522175221852219522205222152222522235222452225522265222752228522295223052231522325223352234522355223652237522385223952240522415224252243522445224552246522475224852249522505225152252522535225452255522565225752258522595226052261522625226352264522655226652267522685226952270522715227252273522745227552276522775227852279522805228152282522835228452285522865228752288522895229052291522925229352294522955229652297522985229952300523015230252303523045230552306523075230852309523105231152312523135231452315523165231752318523195232052321523225232352324523255232652327523285232952330523315233252333523345233552336523375233852339523405234152342523435234452345523465234752348523495235052351523525235352354523555235652357523585235952360523615236252363523645236552366523675236852369523705237152372523735237452375523765237752378523795238052381523825238352384523855238652387523885238952390523915239252393523945239552396523975239852399524005240152402524035240452405524065240752408524095241052411524125241352414524155241652417524185241952420524215242252423524245242552426524275242852429524305243152432524335243452435524365243752438524395244052441524425244352444524455244652447524485244952450524515245252453524545245552456524575245852459524605246152462524635246452465524665246752468524695247052471524725247352474524755247652477524785247952480524815248252483524845248552486524875248852489524905249152492524935249452495524965249752498524995250052501525025250352504525055250652507525085250952510525115251252513525145251552516525175251852519525205252152522525235252452525525265252752528525295253052531525325253352534525355253652537525385253952540525415254252543525445254552546525475254852549525505255152552525535255452555525565255752558525595256052561525625256352564525655256652567525685256952570525715257252573525745257552576525775257852579525805258152582525835258452585525865258752588525895259052591525925259352594525955259652597525985259952600526015260252603526045260552606526075260852609526105261152612526135261452615526165261752618526195262052621526225262352624526255262652627526285262952630526315263252633526345263552636526375263852639526405264152642526435264452645526465264752648526495265052651526525265352654526555265652657526585265952660526615266252663526645266552666526675266852669526705267152672526735267452675526765267752678526795268052681526825268352684526855268652687526885268952690526915269252693526945269552696526975269852699527005270152702527035270452705527065270752708527095271052711527125271352714527155271652717527185271952720527215272252723527245272552726527275272852729527305273152732527335273452735527365273752738527395274052741527425274352744527455274652747527485274952750527515275252753527545275552756527575275852759527605276152762527635276452765527665276752768527695277052771527725277352774527755277652777527785277952780527815278252783527845278552786527875278852789527905279152792527935279452795527965279752798527995280052801528025280352804528055280652807528085280952810528115281252813528145281552816528175281852819528205282152822528235282452825528265282752828528295283052831528325283352834528355283652837528385283952840528415284252843528445284552846528475284852849528505285152852528535285452855528565285752858528595286052861528625286352864528655286652867528685286952870528715287252873528745287552876528775287852879528805288152882528835288452885528865288752888528895289052891528925289352894528955289652897528985289952900529015290252903529045290552906529075290852909529105291152912529135291452915529165291752918529195292052921529225292352924529255292652927529285292952930529315293252933529345293552936529375293852939529405294152942529435294452945529465294752948529495295052951529525295352954529555295652957529585295952960529615296252963529645296552966529675296852969529705297152972529735297452975529765297752978529795298052981529825298352984529855298652987529885298952990529915299252993529945299552996529975299852999530005300153002530035300453005530065300753008530095301053011530125301353014530155301653017530185301953020530215302253023530245302553026530275302853029530305303153032530335303453035530365303753038530395304053041530425304353044530455304653047530485304953050530515305253053530545305553056530575305853059530605306153062530635306453065530665306753068530695307053071530725307353074530755307653077530785307953080530815308253083530845308553086530875308853089530905309153092530935309453095530965309753098530995310053101531025310353104531055310653107531085310953110531115311253113531145311553116531175311853119531205312153122531235312453125531265312753128531295313053131531325313353134531355313653137531385313953140531415314253143531445314553146531475314853149531505315153152531535315453155531565315753158531595316053161531625316353164531655316653167531685316953170531715317253173531745317553176531775317853179531805318153182531835318453185531865318753188531895319053191531925319353194531955319653197531985319953200532015320253203532045320553206532075320853209532105321153212532135321453215532165321753218532195322053221532225322353224532255322653227532285322953230532315323253233532345323553236532375323853239532405324153242532435324453245532465324753248532495325053251532525325353254532555325653257532585325953260532615326253263532645326553266532675326853269532705327153272532735327453275532765327753278532795328053281532825328353284532855328653287532885328953290532915329253293532945329553296532975329853299533005330153302533035330453305533065330753308533095331053311533125331353314533155331653317533185331953320533215332253323533245332553326533275332853329533305333153332533335333453335533365333753338533395334053341533425334353344533455334653347533485334953350533515335253353533545335553356533575335853359533605336153362533635336453365533665336753368533695337053371533725337353374533755337653377533785337953380533815338253383533845338553386533875338853389533905339153392533935339453395533965339753398533995340053401534025340353404534055340653407534085340953410534115341253413534145341553416534175341853419534205342153422534235342453425534265342753428534295343053431534325343353434534355343653437534385343953440534415344253443534445344553446534475344853449534505345153452534535345453455534565345753458534595346053461534625346353464534655346653467534685346953470534715347253473534745347553476534775347853479534805348153482534835348453485534865348753488534895349053491534925349353494534955349653497534985349953500535015350253503535045350553506535075350853509535105351153512535135351453515535165351753518535195352053521535225352353524535255352653527535285352953530535315353253533535345353553536535375353853539535405354153542535435354453545535465354753548535495355053551535525355353554535555355653557535585355953560535615356253563535645356553566535675356853569535705357153572535735357453575535765357753578535795358053581535825358353584535855358653587535885358953590535915359253593535945359553596535975359853599536005360153602536035360453605536065360753608536095361053611536125361353614536155361653617536185361953620536215362253623536245362553626536275362853629536305363153632536335363453635536365363753638536395364053641536425364353644536455364653647536485364953650536515365253653536545365553656536575365853659536605366153662536635366453665536665366753668536695367053671536725367353674536755367653677536785367953680536815368253683536845368553686536875368853689536905369153692536935369453695536965369753698536995370053701537025370353704537055370653707537085370953710537115371253713537145371553716537175371853719537205372153722537235372453725537265372753728537295373053731537325373353734537355373653737537385373953740537415374253743537445374553746537475374853749537505375153752537535375453755537565375753758537595376053761537625376353764537655376653767537685376953770537715377253773537745377553776537775377853779537805378153782537835378453785537865378753788537895379053791537925379353794537955379653797537985379953800538015380253803538045380553806538075380853809538105381153812538135381453815538165381753818538195382053821538225382353824538255382653827538285382953830538315383253833538345383553836538375383853839538405384153842538435384453845538465384753848538495385053851538525385353854538555385653857538585385953860538615386253863538645386553866538675386853869538705387153872538735387453875538765387753878538795388053881538825388353884538855388653887538885388953890538915389253893538945389553896538975389853899539005390153902539035390453905539065390753908539095391053911539125391353914539155391653917539185391953920539215392253923539245392553926539275392853929539305393153932539335393453935539365393753938539395394053941539425394353944539455394653947539485394953950539515395253953539545395553956539575395853959539605396153962539635396453965539665396753968539695397053971539725397353974539755397653977539785397953980539815398253983539845398553986539875398853989539905399153992539935399453995539965399753998539995400054001540025400354004540055400654007540085400954010540115401254013540145401554016540175401854019540205402154022540235402454025540265402754028540295403054031540325403354034540355403654037540385403954040540415404254043540445404554046540475404854049540505405154052540535405454055540565405754058540595406054061540625406354064540655406654067540685406954070540715407254073540745407554076540775407854079540805408154082540835408454085540865408754088540895409054091540925409354094540955409654097540985409954100541015410254103541045410554106541075410854109541105411154112541135411454115541165411754118541195412054121541225412354124541255412654127541285412954130541315413254133541345413554136541375413854139541405414154142541435414454145541465414754148541495415054151541525415354154541555415654157541585415954160541615416254163541645416554166541675416854169541705417154172541735417454175541765417754178541795418054181541825418354184541855418654187541885418954190541915419254193541945419554196541975419854199542005420154202542035420454205542065420754208542095421054211542125421354214542155421654217542185421954220542215422254223542245422554226542275422854229542305423154232542335423454235542365423754238542395424054241542425424354244542455424654247542485424954250542515425254253542545425554256542575425854259542605426154262542635426454265542665426754268542695427054271542725427354274542755427654277542785427954280542815428254283542845428554286542875428854289542905429154292542935429454295542965429754298542995430054301543025430354304543055430654307543085430954310543115431254313543145431554316543175431854319543205432154322543235432454325543265432754328543295433054331543325433354334543355433654337543385433954340543415434254343543445434554346543475434854349543505435154352543535435454355543565435754358543595436054361543625436354364543655436654367543685436954370543715437254373543745437554376543775437854379543805438154382543835438454385543865438754388543895439054391543925439354394543955439654397543985439954400544015440254403544045440554406544075440854409544105441154412544135441454415544165441754418544195442054421544225442354424544255442654427544285442954430544315443254433544345443554436544375443854439544405444154442544435444454445544465444754448544495445054451544525445354454544555445654457544585445954460544615446254463544645446554466544675446854469544705447154472544735447454475544765447754478544795448054481544825448354484544855448654487544885448954490544915449254493544945449554496544975449854499545005450154502545035450454505545065450754508545095451054511545125451354514545155451654517545185451954520545215452254523545245452554526545275452854529545305453154532545335453454535545365453754538545395454054541545425454354544545455454654547545485454954550545515455254553545545455554556545575455854559545605456154562545635456454565545665456754568545695457054571545725457354574545755457654577545785457954580545815458254583545845458554586545875458854589545905459154592545935459454595545965459754598545995460054601546025460354604546055460654607546085460954610546115461254613546145461554616546175461854619546205462154622546235462454625546265462754628546295463054631546325463354634546355463654637546385463954640546415464254643546445464554646546475464854649546505465154652546535465454655546565465754658546595466054661546625466354664546655466654667546685466954670546715467254673546745467554676546775467854679546805468154682546835468454685546865468754688546895469054691546925469354694546955469654697546985469954700547015470254703547045470554706547075470854709547105471154712547135471454715547165471754718547195472054721547225472354724547255472654727547285472954730547315473254733547345473554736547375473854739547405474154742547435474454745547465474754748547495475054751547525475354754547555475654757547585475954760547615476254763547645476554766547675476854769547705477154772547735477454775547765477754778547795478054781547825478354784547855478654787547885478954790547915479254793547945479554796547975479854799548005480154802548035480454805548065480754808548095481054811548125481354814548155481654817548185481954820548215482254823548245482554826548275482854829548305483154832548335483454835548365483754838548395484054841548425484354844548455484654847548485484954850548515485254853548545485554856548575485854859548605486154862548635486454865548665486754868548695487054871548725487354874548755487654877548785487954880548815488254883548845488554886548875488854889548905489154892548935489454895548965489754898548995490054901549025490354904549055490654907549085490954910549115491254913549145491554916549175491854919549205492154922549235492454925549265492754928549295493054931549325493354934549355493654937549385493954940549415494254943549445494554946549475494854949549505495154952549535495454955549565495754958549595496054961549625496354964549655496654967549685496954970549715497254973549745497554976549775497854979549805498154982549835498454985549865498754988549895499054991549925499354994549955499654997549985499955000550015500255003550045500555006550075500855009550105501155012550135501455015550165501755018550195502055021550225502355024550255502655027550285502955030550315503255033550345503555036550375503855039550405504155042550435504455045550465504755048550495505055051550525505355054550555505655057550585505955060550615506255063550645506555066550675506855069550705507155072550735507455075550765507755078550795508055081550825508355084550855508655087550885508955090550915509255093550945509555096550975509855099551005510155102551035510455105551065510755108551095511055111551125511355114551155511655117551185511955120551215512255123551245512555126551275512855129551305513155132551335513455135551365513755138551395514055141551425514355144551455514655147551485514955150551515515255153551545515555156551575515855159551605516155162551635516455165551665516755168551695517055171551725517355174551755517655177551785517955180551815518255183551845518555186551875518855189551905519155192551935519455195551965519755198551995520055201552025520355204552055520655207552085520955210552115521255213552145521555216552175521855219552205522155222552235522455225552265522755228552295523055231552325523355234552355523655237552385523955240552415524255243552445524555246552475524855249552505525155252552535525455255552565525755258552595526055261552625526355264552655526655267552685526955270552715527255273552745527555276552775527855279552805528155282552835528455285552865528755288552895529055291552925529355294552955529655297552985529955300553015530255303553045530555306553075530855309553105531155312553135531455315553165531755318553195532055321553225532355324553255532655327553285532955330553315533255333553345533555336553375533855339553405534155342553435534455345553465534755348553495535055351553525535355354553555535655357553585535955360553615536255363553645536555366553675536855369553705537155372553735537455375553765537755378553795538055381553825538355384553855538655387553885538955390553915539255393553945539555396553975539855399554005540155402554035540455405554065540755408554095541055411554125541355414554155541655417554185541955420554215542255423554245542555426554275542855429554305543155432554335543455435554365543755438554395544055441554425544355444554455544655447554485544955450554515545255453554545545555456554575545855459554605546155462554635546455465554665546755468554695547055471554725547355474554755547655477554785547955480554815548255483554845548555486554875548855489554905549155492554935549455495554965549755498554995550055501555025550355504555055550655507555085550955510555115551255513555145551555516555175551855519555205552155522555235552455525555265552755528555295553055531555325553355534555355553655537555385553955540555415554255543555445554555546555475554855549555505555155552555535555455555555565555755558555595556055561555625556355564555655556655567555685556955570555715557255573555745557555576555775557855579555805558155582555835558455585555865558755588555895559055591555925559355594555955559655597555985559955600556015560255603556045560555606556075560855609556105561155612556135561455615556165561755618556195562055621556225562355624556255562655627556285562955630556315563255633556345563555636556375563855639556405564155642556435564455645556465564755648556495565055651556525565355654556555565655657556585565955660556615566255663556645566555666556675566855669556705567155672556735567455675556765567755678556795568055681556825568355684556855568655687556885568955690556915569255693556945569555696556975569855699557005570155702557035570455705557065570755708557095571055711557125571355714557155571655717557185571955720557215572255723557245572555726557275572855729557305573155732557335573455735557365573755738557395574055741557425574355744557455574655747557485574955750557515575255753557545575555756557575575855759557605576155762557635576455765557665576755768557695577055771557725577355774557755577655777557785577955780557815578255783557845578555786557875578855789557905579155792557935579455795557965579755798557995580055801558025580355804558055580655807558085580955810558115581255813558145581555816558175581855819558205582155822558235582455825558265582755828558295583055831558325583355834558355583655837558385583955840558415584255843558445584555846558475584855849558505585155852558535585455855558565585755858558595586055861558625586355864558655586655867558685586955870558715587255873558745587555876558775587855879558805588155882558835588455885558865588755888558895589055891558925589355894558955589655897558985589955900559015590255903559045590555906559075590855909559105591155912559135591455915559165591755918559195592055921559225592355924559255592655927559285592955930559315593255933559345593555936559375593855939559405594155942559435594455945559465594755948559495595055951559525595355954559555595655957559585595955960559615596255963559645596555966559675596855969559705597155972559735597455975559765597755978559795598055981559825598355984559855598655987559885598955990559915599255993559945599555996559975599855999560005600156002560035600456005560065600756008560095601056011560125601356014560155601656017560185601956020560215602256023560245602556026560275602856029560305603156032560335603456035560365603756038560395604056041560425604356044560455604656047560485604956050560515605256053560545605556056560575605856059560605606156062560635606456065560665606756068560695607056071560725607356074560755607656077560785607956080560815608256083560845608556086560875608856089560905609156092560935609456095560965609756098560995610056101561025610356104561055610656107561085610956110561115611256113561145611556116561175611856119561205612156122561235612456125561265612756128561295613056131561325613356134561355613656137561385613956140561415614256143561445614556146561475614856149561505615156152561535615456155561565615756158561595616056161561625616356164561655616656167561685616956170561715617256173561745617556176561775617856179561805618156182561835618456185561865618756188561895619056191561925619356194561955619656197561985619956200562015620256203562045620556206562075620856209562105621156212562135621456215562165621756218562195622056221562225622356224562255622656227562285622956230562315623256233562345623556236562375623856239562405624156242562435624456245562465624756248562495625056251562525625356254562555625656257562585625956260562615626256263562645626556266562675626856269562705627156272562735627456275562765627756278562795628056281562825628356284562855628656287562885628956290562915629256293562945629556296562975629856299563005630156302563035630456305563065630756308563095631056311563125631356314563155631656317563185631956320563215632256323563245632556326563275632856329563305633156332563335633456335563365633756338563395634056341563425634356344563455634656347563485634956350563515635256353563545635556356563575635856359563605636156362563635636456365563665636756368563695637056371563725637356374563755637656377563785637956380563815638256383563845638556386563875638856389563905639156392563935639456395563965639756398563995640056401564025640356404564055640656407564085640956410564115641256413564145641556416564175641856419564205642156422564235642456425564265642756428564295643056431564325643356434564355643656437564385643956440564415644256443564445644556446564475644856449564505645156452564535645456455564565645756458564595646056461564625646356464564655646656467564685646956470564715647256473564745647556476564775647856479564805648156482564835648456485564865648756488564895649056491564925649356494564955649656497564985649956500565015650256503565045650556506565075650856509565105651156512565135651456515565165651756518565195652056521565225652356524565255652656527565285652956530565315653256533565345653556536565375653856539565405654156542565435654456545565465654756548565495655056551565525655356554565555655656557565585655956560565615656256563565645656556566565675656856569565705657156572565735657456575565765657756578565795658056581565825658356584565855658656587565885658956590565915659256593565945659556596565975659856599566005660156602566035660456605566065660756608566095661056611566125661356614566155661656617566185661956620566215662256623566245662556626566275662856629566305663156632566335663456635566365663756638566395664056641566425664356644566455664656647566485664956650566515665256653566545665556656566575665856659566605666156662566635666456665566665666756668566695667056671566725667356674566755667656677566785667956680566815668256683566845668556686566875668856689566905669156692566935669456695566965669756698566995670056701567025670356704567055670656707567085670956710567115671256713567145671556716567175671856719567205672156722567235672456725567265672756728567295673056731567325673356734567355673656737567385673956740567415674256743567445674556746567475674856749567505675156752567535675456755567565675756758567595676056761567625676356764567655676656767567685676956770567715677256773567745677556776567775677856779567805678156782567835678456785567865678756788567895679056791567925679356794567955679656797567985679956800568015680256803568045680556806568075680856809568105681156812568135681456815568165681756818568195682056821568225682356824568255682656827568285682956830568315683256833568345683556836568375683856839568405684156842568435684456845568465684756848568495685056851568525685356854568555685656857568585685956860568615686256863568645686556866568675686856869568705687156872568735687456875568765687756878568795688056881568825688356884568855688656887568885688956890568915689256893568945689556896568975689856899569005690156902569035690456905569065690756908569095691056911569125691356914569155691656917569185691956920569215692256923569245692556926569275692856929569305693156932569335693456935569365693756938569395694056941569425694356944569455694656947569485694956950569515695256953569545695556956569575695856959569605696156962569635696456965569665696756968569695697056971569725697356974569755697656977569785697956980569815698256983569845698556986569875698856989569905699156992569935699456995569965699756998569995700057001570025700357004570055700657007570085700957010570115701257013570145701557016570175701857019570205702157022570235702457025570265702757028570295703057031570325703357034570355703657037570385703957040570415704257043570445704557046570475704857049570505705157052570535705457055570565705757058570595706057061570625706357064570655706657067570685706957070570715707257073570745707557076570775707857079570805708157082570835708457085570865708757088570895709057091570925709357094570955709657097570985709957100571015710257103571045710557106571075710857109571105711157112571135711457115571165711757118571195712057121571225712357124571255712657127571285712957130571315713257133571345713557136571375713857139571405714157142571435714457145571465714757148571495715057151571525715357154571555715657157571585715957160571615716257163571645716557166571675716857169571705717157172571735717457175571765717757178571795718057181571825718357184571855718657187571885718957190571915719257193571945719557196571975719857199572005720157202572035720457205572065720757208572095721057211572125721357214572155721657217572185721957220572215722257223572245722557226572275722857229572305723157232572335723457235572365723757238572395724057241572425724357244572455724657247572485724957250572515725257253572545725557256572575725857259572605726157262572635726457265572665726757268572695727057271572725727357274572755727657277572785727957280572815728257283572845728557286572875728857289572905729157292572935729457295572965729757298572995730057301573025730357304573055730657307573085730957310573115731257313573145731557316573175731857319573205732157322573235732457325573265732757328573295733057331573325733357334573355733657337573385733957340573415734257343573445734557346573475734857349573505735157352573535735457355573565735757358573595736057361573625736357364573655736657367573685736957370573715737257373573745737557376573775737857379573805738157382573835738457385573865738757388573895739057391573925739357394573955739657397573985739957400574015740257403574045740557406574075740857409574105741157412574135741457415574165741757418574195742057421574225742357424574255742657427574285742957430574315743257433574345743557436574375743857439574405744157442574435744457445574465744757448574495745057451574525745357454574555745657457574585745957460574615746257463574645746557466574675746857469574705747157472574735747457475574765747757478574795748057481574825748357484574855748657487574885748957490574915749257493574945749557496574975749857499575005750157502575035750457505575065750757508575095751057511575125751357514575155751657517575185751957520575215752257523575245752557526575275752857529575305753157532575335753457535575365753757538575395754057541575425754357544575455754657547575485754957550575515755257553575545755557556575575755857559575605756157562575635756457565575665756757568575695757057571575725757357574575755757657577575785757957580575815758257583575845758557586575875758857589575905759157592575935759457595575965759757598575995760057601576025760357604576055760657607576085760957610576115761257613576145761557616576175761857619576205762157622576235762457625576265762757628576295763057631576325763357634576355763657637576385763957640576415764257643576445764557646576475764857649576505765157652576535765457655576565765757658576595766057661576625766357664576655766657667576685766957670576715767257673576745767557676576775767857679576805768157682576835768457685576865768757688576895769057691576925769357694576955769657697576985769957700577015770257703577045770557706577075770857709577105771157712577135771457715577165771757718577195772057721577225772357724577255772657727577285772957730577315773257733577345773557736577375773857739577405774157742577435774457745577465774757748577495775057751577525775357754577555775657757577585775957760577615776257763577645776557766577675776857769577705777157772577735777457775577765777757778577795778057781577825778357784577855778657787577885778957790577915779257793577945779557796577975779857799578005780157802578035780457805578065780757808578095781057811578125781357814578155781657817578185781957820578215782257823578245782557826578275782857829578305783157832578335783457835578365783757838578395784057841578425784357844578455784657847578485784957850578515785257853578545785557856578575785857859578605786157862578635786457865578665786757868578695787057871578725787357874578755787657877578785787957880578815788257883578845788557886578875788857889578905789157892578935789457895578965789757898578995790057901579025790357904579055790657907579085790957910579115791257913579145791557916579175791857919579205792157922579235792457925579265792757928579295793057931579325793357934579355793657937579385793957940579415794257943579445794557946579475794857949579505795157952579535795457955579565795757958579595796057961579625796357964579655796657967579685796957970579715797257973579745797557976579775797857979579805798157982579835798457985579865798757988579895799057991579925799357994579955799657997579985799958000580015800258003580045800558006580075800858009580105801158012580135801458015580165801758018580195802058021580225802358024580255802658027580285802958030580315803258033580345803558036580375803858039580405804158042580435804458045580465804758048580495805058051580525805358054580555805658057580585805958060580615806258063580645806558066580675806858069580705807158072580735807458075580765807758078580795808058081580825808358084580855808658087580885808958090580915809258093580945809558096580975809858099581005810158102581035810458105581065810758108581095811058111581125811358114581155811658117581185811958120581215812258123581245812558126581275812858129581305813158132581335813458135581365813758138581395814058141581425814358144581455814658147581485814958150581515815258153581545815558156581575815858159581605816158162581635816458165581665816758168581695817058171581725817358174581755817658177581785817958180581815818258183581845818558186581875818858189581905819158192581935819458195581965819758198581995820058201582025820358204582055820658207582085820958210582115821258213582145821558216582175821858219582205822158222582235822458225582265822758228582295823058231582325823358234582355823658237582385823958240582415824258243582445824558246582475824858249582505825158252582535825458255582565825758258582595826058261582625826358264582655826658267582685826958270582715827258273582745827558276582775827858279582805828158282582835828458285582865828758288582895829058291582925829358294582955829658297582985829958300583015830258303583045830558306583075830858309583105831158312583135831458315583165831758318583195832058321583225832358324583255832658327583285832958330583315833258333583345833558336583375833858339583405834158342583435834458345583465834758348583495835058351583525835358354583555835658357583585835958360583615836258363583645836558366583675836858369583705837158372583735837458375583765837758378583795838058381583825838358384583855838658387583885838958390583915839258393583945839558396583975839858399584005840158402584035840458405584065840758408584095841058411584125841358414584155841658417584185841958420584215842258423584245842558426584275842858429584305843158432584335843458435584365843758438584395844058441584425844358444584455844658447584485844958450584515845258453584545845558456584575845858459584605846158462584635846458465584665846758468584695847058471584725847358474584755847658477584785847958480584815848258483584845848558486584875848858489584905849158492584935849458495584965849758498584995850058501585025850358504585055850658507585085850958510585115851258513585145851558516585175851858519585205852158522585235852458525585265852758528585295853058531585325853358534585355853658537585385853958540585415854258543585445854558546585475854858549585505855158552585535855458555585565855758558585595856058561585625856358564585655856658567585685856958570585715857258573585745857558576585775857858579585805858158582585835858458585585865858758588585895859058591585925859358594585955859658597585985859958600586015860258603586045860558606586075860858609586105861158612586135861458615586165861758618586195862058621586225862358624586255862658627586285862958630586315863258633586345863558636586375863858639586405864158642586435864458645586465864758648586495865058651586525865358654586555865658657586585865958660586615866258663586645866558666586675866858669586705867158672586735867458675586765867758678586795868058681586825868358684586855868658687586885868958690586915869258693586945869558696586975869858699587005870158702587035870458705587065870758708587095871058711587125871358714587155871658717587185871958720587215872258723587245872558726587275872858729587305873158732587335873458735587365873758738587395874058741587425874358744587455874658747587485874958750587515875258753587545875558756587575875858759587605876158762587635876458765587665876758768587695877058771587725877358774587755877658777587785877958780587815878258783587845878558786587875878858789587905879158792587935879458795587965879758798587995880058801588025880358804588055880658807588085880958810588115881258813588145881558816588175881858819588205882158822588235882458825588265882758828588295883058831588325883358834588355883658837588385883958840588415884258843588445884558846588475884858849588505885158852588535885458855588565885758858588595886058861588625886358864588655886658867588685886958870588715887258873588745887558876588775887858879588805888158882588835888458885588865888758888588895889058891588925889358894588955889658897588985889958900589015890258903589045890558906589075890858909589105891158912589135891458915589165891758918589195892058921589225892358924589255892658927589285892958930589315893258933589345893558936589375893858939589405894158942589435894458945589465894758948589495895058951589525895358954589555895658957589585895958960589615896258963589645896558966589675896858969589705897158972589735897458975589765897758978589795898058981589825898358984589855898658987589885898958990589915899258993589945899558996589975899858999590005900159002590035900459005590065900759008590095901059011590125901359014590155901659017590185901959020590215902259023590245902559026590275902859029590305903159032590335903459035590365903759038590395904059041590425904359044590455904659047590485904959050590515905259053590545905559056590575905859059590605906159062590635906459065590665906759068590695907059071590725907359074590755907659077590785907959080590815908259083590845908559086590875908859089590905909159092590935909459095590965909759098590995910059101591025910359104591055910659107591085910959110591115911259113591145911559116591175911859119591205912159122591235912459125591265912759128591295913059131591325913359134591355913659137591385913959140591415914259143591445914559146591475914859149591505915159152591535915459155591565915759158591595916059161591625916359164591655916659167591685916959170591715917259173591745917559176591775917859179591805918159182591835918459185591865918759188591895919059191591925919359194591955919659197591985919959200592015920259203592045920559206592075920859209592105921159212592135921459215592165921759218592195922059221592225922359224592255922659227592285922959230592315923259233592345923559236592375923859239592405924159242592435924459245592465924759248592495925059251592525925359254592555925659257592585925959260592615926259263592645926559266592675926859269592705927159272592735927459275592765927759278592795928059281592825928359284592855928659287592885928959290592915929259293592945929559296592975929859299593005930159302593035930459305593065930759308593095931059311593125931359314593155931659317593185931959320593215932259323593245932559326593275932859329593305933159332593335933459335593365933759338593395934059341593425934359344593455934659347593485934959350593515935259353593545935559356593575935859359593605936159362593635936459365593665936759368593695937059371593725937359374593755937659377593785937959380593815938259383593845938559386593875938859389593905939159392593935939459395593965939759398593995940059401594025940359404594055940659407594085940959410594115941259413594145941559416594175941859419594205942159422594235942459425594265942759428594295943059431594325943359434594355943659437594385943959440594415944259443594445944559446594475944859449594505945159452594535945459455594565945759458594595946059461594625946359464594655946659467594685946959470594715947259473594745947559476594775947859479594805948159482594835948459485594865948759488594895949059491594925949359494594955949659497594985949959500595015950259503595045950559506595075950859509595105951159512595135951459515595165951759518595195952059521595225952359524595255952659527595285952959530595315953259533595345953559536595375953859539595405954159542595435954459545595465954759548595495955059551595525955359554595555955659557595585955959560595615956259563595645956559566595675956859569595705957159572595735957459575595765957759578595795958059581595825958359584595855958659587595885958959590595915959259593595945959559596595975959859599596005960159602596035960459605596065960759608596095961059611596125961359614596155961659617596185961959620596215962259623596245962559626596275962859629596305963159632596335963459635596365963759638596395964059641596425964359644596455964659647596485964959650596515965259653596545965559656596575965859659596605966159662596635966459665596665966759668596695967059671596725967359674596755967659677596785967959680596815968259683596845968559686596875968859689596905969159692596935969459695596965969759698596995970059701597025970359704597055970659707597085970959710597115971259713597145971559716597175971859719597205972159722597235972459725597265972759728597295973059731597325973359734597355973659737597385973959740597415974259743597445974559746597475974859749597505975159752597535975459755597565975759758597595976059761597625976359764597655976659767597685976959770597715977259773597745977559776597775977859779597805978159782597835978459785597865978759788597895979059791597925979359794597955979659797597985979959800598015980259803598045980559806598075980859809598105981159812598135981459815598165981759818598195982059821598225982359824598255982659827598285982959830598315983259833598345983559836598375983859839598405984159842598435984459845598465984759848598495985059851598525985359854598555985659857598585985959860598615986259863598645986559866598675986859869598705987159872598735987459875598765987759878598795988059881598825988359884598855988659887598885988959890598915989259893598945989559896598975989859899599005990159902599035990459905599065990759908599095991059911599125991359914599155991659917599185991959920599215992259923599245992559926599275992859929599305993159932599335993459935599365993759938599395994059941599425994359944599455994659947599485994959950599515995259953599545995559956599575995859959599605996159962599635996459965599665996759968599695997059971599725997359974599755997659977599785997959980599815998259983599845998559986599875998859989599905999159992599935999459995599965999759998599996000060001600026000360004600056000660007600086000960010600116001260013600146001560016600176001860019600206002160022600236002460025600266002760028600296003060031600326003360034600356003660037600386003960040600416004260043600446004560046600476004860049600506005160052600536005460055600566005760058600596006060061600626006360064600656006660067600686006960070600716007260073600746007560076600776007860079600806008160082600836008460085600866008760088600896009060091600926009360094600956009660097600986009960100601016010260103601046010560106601076010860109601106011160112601136011460115601166011760118601196012060121601226012360124601256012660127601286012960130601316013260133601346013560136601376013860139601406014160142601436014460145601466014760148601496015060151601526015360154601556015660157601586015960160601616016260163601646016560166601676016860169601706017160172601736017460175601766017760178601796018060181601826018360184601856018660187601886018960190601916019260193601946019560196601976019860199602006020160202602036020460205602066020760208602096021060211602126021360214602156021660217602186021960220602216022260223602246022560226602276022860229602306023160232602336023460235602366023760238602396024060241602426024360244602456024660247602486024960250602516025260253602546025560256602576025860259602606026160262602636026460265602666026760268602696027060271602726027360274602756027660277602786027960280602816028260283602846028560286602876028860289602906029160292602936029460295602966029760298602996030060301603026030360304603056030660307603086030960310603116031260313603146031560316603176031860319603206032160322603236032460325603266032760328603296033060331603326033360334603356033660337603386033960340603416034260343603446034560346603476034860349603506035160352603536035460355603566035760358603596036060361603626036360364603656036660367603686036960370603716037260373603746037560376603776037860379603806038160382603836038460385603866038760388603896039060391603926039360394603956039660397603986039960400604016040260403604046040560406604076040860409604106041160412604136041460415604166041760418604196042060421604226042360424604256042660427604286042960430604316043260433604346043560436604376043860439604406044160442604436044460445604466044760448604496045060451604526045360454604556045660457604586045960460604616046260463604646046560466604676046860469604706047160472604736047460475604766047760478604796048060481604826048360484604856048660487604886048960490604916049260493604946049560496604976049860499605006050160502605036050460505605066050760508605096051060511605126051360514605156051660517605186051960520605216052260523605246052560526605276052860529605306053160532605336053460535605366053760538605396054060541605426054360544605456054660547605486054960550605516055260553605546055560556605576055860559605606056160562605636056460565605666056760568605696057060571605726057360574605756057660577605786057960580605816058260583605846058560586605876058860589605906059160592605936059460595605966059760598605996060060601606026060360604606056060660607606086060960610606116061260613606146061560616606176061860619606206062160622606236062460625606266062760628606296063060631606326063360634606356063660637606386063960640606416064260643606446064560646606476064860649606506065160652606536065460655606566065760658606596066060661606626066360664606656066660667606686066960670606716067260673606746067560676606776067860679606806068160682606836068460685606866068760688606896069060691606926069360694606956069660697606986069960700607016070260703607046070560706607076070860709607106071160712607136071460715607166071760718607196072060721607226072360724607256072660727607286072960730607316073260733607346073560736607376073860739607406074160742607436074460745607466074760748607496075060751607526075360754607556075660757607586075960760607616076260763607646076560766607676076860769607706077160772607736077460775607766077760778607796078060781607826078360784607856078660787607886078960790607916079260793607946079560796607976079860799608006080160802608036080460805608066080760808608096081060811608126081360814608156081660817608186081960820608216082260823608246082560826608276082860829608306083160832608336083460835608366083760838608396084060841608426084360844608456084660847608486084960850608516085260853608546085560856608576085860859608606086160862608636086460865608666086760868608696087060871608726087360874608756087660877608786087960880608816088260883608846088560886608876088860889608906089160892608936089460895608966089760898608996090060901609026090360904609056090660907609086090960910609116091260913609146091560916609176091860919609206092160922609236092460925609266092760928609296093060931609326093360934609356093660937609386093960940609416094260943609446094560946609476094860949609506095160952609536095460955609566095760958609596096060961609626096360964609656096660967609686096960970609716097260973609746097560976609776097860979609806098160982609836098460985609866098760988609896099060991609926099360994609956099660997609986099961000610016100261003610046100561006610076100861009610106101161012610136101461015610166101761018610196102061021610226102361024610256102661027610286102961030610316103261033610346103561036610376103861039610406104161042610436104461045610466104761048610496105061051610526105361054610556105661057610586105961060610616106261063610646106561066610676106861069610706107161072610736107461075610766107761078610796108061081610826108361084610856108661087610886108961090610916109261093610946109561096610976109861099611006110161102611036110461105611066110761108611096111061111611126111361114611156111661117611186111961120611216112261123611246112561126611276112861129611306113161132611336113461135611366113761138611396114061141611426114361144611456114661147611486114961150611516115261153611546115561156611576115861159611606116161162611636116461165611666116761168611696117061171611726117361174611756117661177611786117961180611816118261183611846118561186611876118861189611906119161192611936119461195611966119761198611996120061201612026120361204612056120661207612086120961210612116121261213612146121561216612176121861219612206122161222612236122461225612266122761228612296123061231612326123361234612356123661237612386123961240612416124261243612446124561246612476124861249612506125161252612536125461255612566125761258612596126061261612626126361264612656126661267612686126961270612716127261273612746127561276612776127861279612806128161282612836128461285612866128761288612896129061291612926129361294612956129661297612986129961300613016130261303613046130561306613076130861309613106131161312613136131461315613166131761318613196132061321613226132361324613256132661327613286132961330613316133261333613346133561336613376133861339613406134161342613436134461345613466134761348613496135061351613526135361354613556135661357613586135961360613616136261363613646136561366613676136861369613706137161372613736137461375613766137761378613796138061381613826138361384613856138661387613886138961390613916139261393613946139561396613976139861399614006140161402614036140461405614066140761408614096141061411614126141361414614156141661417614186141961420614216142261423614246142561426614276142861429614306143161432614336143461435614366143761438614396144061441614426144361444614456144661447614486144961450614516145261453614546145561456614576145861459614606146161462614636146461465614666146761468614696147061471614726147361474614756147661477614786147961480614816148261483614846148561486614876148861489614906149161492614936149461495614966149761498614996150061501615026150361504615056150661507615086150961510615116151261513615146151561516615176151861519615206152161522615236152461525615266152761528615296153061531615326153361534615356153661537615386153961540615416154261543615446154561546615476154861549615506155161552615536155461555615566155761558615596156061561615626156361564615656156661567615686156961570615716157261573615746157561576615776157861579615806158161582615836158461585615866158761588615896159061591615926159361594615956159661597615986159961600616016160261603616046160561606616076160861609616106161161612616136161461615616166161761618616196162061621616226162361624616256162661627616286162961630616316163261633616346163561636616376163861639616406164161642616436164461645616466164761648616496165061651616526165361654616556165661657616586165961660616616166261663616646166561666616676166861669616706167161672616736167461675616766167761678616796168061681616826168361684616856168661687616886168961690616916169261693616946169561696616976169861699617006170161702617036170461705617066170761708617096171061711617126171361714617156171661717617186171961720617216172261723617246172561726617276172861729617306173161732617336173461735617366173761738617396174061741617426174361744617456174661747617486174961750617516175261753617546175561756617576175861759617606176161762617636176461765617666176761768617696177061771617726177361774617756177661777617786177961780617816178261783617846178561786617876178861789617906179161792617936179461795617966179761798617996180061801618026180361804618056180661807618086180961810618116181261813618146181561816618176181861819618206182161822618236182461825618266182761828618296183061831618326183361834618356183661837618386183961840618416184261843618446184561846618476184861849618506185161852618536185461855618566185761858618596186061861618626186361864618656186661867618686186961870618716187261873618746187561876618776187861879618806188161882618836188461885618866188761888618896189061891618926189361894618956189661897618986189961900619016190261903619046190561906619076190861909619106191161912619136191461915619166191761918619196192061921619226192361924619256192661927619286192961930619316193261933619346193561936619376193861939619406194161942619436194461945619466194761948619496195061951619526195361954619556195661957619586195961960619616196261963619646196561966619676196861969619706197161972619736197461975619766197761978619796198061981619826198361984619856198661987619886198961990619916199261993619946199561996619976199861999620006200162002620036200462005620066200762008620096201062011620126201362014620156201662017620186201962020620216202262023620246202562026620276202862029620306203162032620336203462035620366203762038620396204062041620426204362044620456204662047620486204962050620516205262053620546205562056620576205862059620606206162062620636206462065620666206762068620696207062071620726207362074620756207662077620786207962080620816208262083620846208562086620876208862089620906209162092620936209462095620966209762098620996210062101621026210362104621056210662107621086210962110621116211262113621146211562116621176211862119621206212162122621236212462125621266212762128621296213062131621326213362134621356213662137621386213962140621416214262143621446214562146621476214862149621506215162152621536215462155621566215762158621596216062161621626216362164621656216662167621686216962170621716217262173621746217562176621776217862179621806218162182621836218462185621866218762188621896219062191621926219362194621956219662197621986219962200622016220262203622046220562206622076220862209622106221162212622136221462215622166221762218622196222062221622226222362224622256222662227622286222962230622316223262233622346223562236622376223862239622406224162242622436224462245622466224762248622496225062251622526225362254622556225662257622586225962260622616226262263622646226562266622676226862269622706227162272622736227462275622766227762278622796228062281622826228362284622856228662287622886228962290622916229262293622946229562296622976229862299623006230162302623036230462305623066230762308623096231062311623126231362314623156231662317623186231962320623216232262323623246232562326623276232862329623306233162332623336233462335623366233762338623396234062341623426234362344623456234662347623486234962350623516235262353623546235562356623576235862359623606236162362623636236462365623666236762368623696237062371623726237362374623756237662377623786237962380623816238262383623846238562386623876238862389623906239162392623936239462395623966239762398623996240062401624026240362404624056240662407624086240962410624116241262413624146241562416624176241862419624206242162422624236242462425624266242762428624296243062431624326243362434624356243662437624386243962440624416244262443624446244562446624476244862449624506245162452624536245462455624566245762458624596246062461624626246362464624656246662467624686246962470624716247262473624746247562476624776247862479624806248162482624836248462485624866248762488624896249062491624926249362494624956249662497624986249962500625016250262503625046250562506625076250862509625106251162512625136251462515625166251762518625196252062521625226252362524625256252662527625286252962530625316253262533625346253562536625376253862539625406254162542625436254462545625466254762548625496255062551625526255362554625556255662557625586255962560625616256262563625646256562566625676256862569625706257162572625736257462575625766257762578625796258062581625826258362584625856258662587625886258962590625916259262593625946259562596625976259862599626006260162602626036260462605626066260762608626096261062611626126261362614626156261662617626186261962620626216262262623626246262562626626276262862629626306263162632626336263462635626366263762638626396264062641626426264362644626456264662647626486264962650626516265262653626546265562656626576265862659626606266162662626636266462665626666266762668626696267062671626726267362674626756267662677626786267962680626816268262683626846268562686626876268862689626906269162692626936269462695626966269762698626996270062701627026270362704627056270662707627086270962710627116271262713627146271562716627176271862719627206272162722627236272462725627266272762728627296273062731627326273362734627356273662737627386273962740627416274262743627446274562746627476274862749627506275162752627536275462755627566275762758627596276062761627626276362764627656276662767627686276962770627716277262773627746277562776627776277862779627806278162782627836278462785627866278762788627896279062791627926279362794627956279662797627986279962800628016280262803628046280562806628076280862809628106281162812628136281462815628166281762818628196282062821628226282362824628256282662827628286282962830628316283262833628346283562836628376283862839628406284162842628436284462845628466284762848628496285062851628526285362854628556285662857628586285962860628616286262863628646286562866628676286862869628706287162872628736287462875628766287762878628796288062881628826288362884628856288662887628886288962890628916289262893628946289562896628976289862899629006290162902629036290462905629066290762908629096291062911629126291362914629156291662917629186291962920629216292262923629246292562926629276292862929629306293162932629336293462935629366293762938629396294062941629426294362944629456294662947629486294962950629516295262953629546295562956629576295862959629606296162962629636296462965629666296762968629696297062971629726297362974629756297662977629786297962980629816298262983629846298562986629876298862989629906299162992629936299462995629966299762998629996300063001630026300363004630056300663007630086300963010630116301263013630146301563016630176301863019630206302163022630236302463025630266302763028630296303063031630326303363034630356303663037630386303963040630416304263043630446304563046630476304863049630506305163052630536305463055630566305763058630596306063061630626306363064630656306663067630686306963070630716307263073630746307563076630776307863079630806308163082630836308463085630866308763088630896309063091630926309363094630956309663097630986309963100631016310263103631046310563106631076310863109631106311163112631136311463115631166311763118631196312063121631226312363124631256312663127631286312963130631316313263133631346313563136631376313863139631406314163142631436314463145631466314763148631496315063151631526315363154631556315663157631586315963160631616316263163631646316563166631676316863169631706317163172631736317463175631766317763178631796318063181631826318363184631856318663187631886318963190631916319263193631946319563196631976319863199632006320163202632036320463205632066320763208632096321063211632126321363214632156321663217632186321963220632216322263223632246322563226632276322863229632306323163232632336323463235632366323763238632396324063241632426324363244632456324663247632486324963250632516325263253632546325563256632576325863259632606326163262632636326463265632666326763268632696327063271632726327363274632756327663277632786327963280632816328263283632846328563286632876328863289632906329163292632936329463295632966329763298632996330063301633026330363304633056330663307633086330963310633116331263313633146331563316633176331863319633206332163322633236332463325633266332763328633296333063331633326333363334633356333663337633386333963340633416334263343633446334563346633476334863349633506335163352633536335463355633566335763358633596336063361633626336363364633656336663367633686336963370633716337263373633746337563376633776337863379633806338163382633836338463385633866338763388633896339063391633926339363394633956339663397633986339963400634016340263403634046340563406634076340863409634106341163412634136341463415634166341763418634196342063421634226342363424634256342663427634286342963430634316343263433634346343563436634376343863439634406344163442634436344463445634466344763448634496345063451634526345363454634556345663457634586345963460634616346263463634646346563466634676346863469634706347163472634736347463475634766347763478634796348063481634826348363484634856348663487634886348963490634916349263493634946349563496634976349863499635006350163502635036350463505635066350763508635096351063511635126351363514635156351663517635186351963520635216352263523635246352563526635276352863529635306353163532635336353463535635366353763538635396354063541635426354363544635456354663547635486354963550635516355263553635546355563556635576355863559635606356163562635636356463565635666356763568635696357063571635726357363574635756357663577635786357963580635816358263583635846358563586635876358863589635906359163592635936359463595635966359763598635996360063601636026360363604636056360663607636086360963610636116361263613636146361563616636176361863619636206362163622636236362463625636266362763628636296363063631636326363363634636356363663637636386363963640636416364263643636446364563646636476364863649636506365163652636536365463655636566365763658636596366063661636626366363664636656366663667636686366963670636716367263673636746367563676636776367863679636806368163682636836368463685636866368763688636896369063691636926369363694636956369663697636986369963700637016370263703637046370563706637076370863709637106371163712637136371463715637166371763718637196372063721637226372363724637256372663727637286372963730637316373263733637346373563736637376373863739637406374163742637436374463745637466374763748637496375063751637526375363754637556375663757637586375963760637616376263763637646376563766637676376863769637706377163772637736377463775637766377763778637796378063781637826378363784637856378663787637886378963790637916379263793637946379563796637976379863799638006380163802638036380463805638066380763808638096381063811638126381363814638156381663817638186381963820638216382263823638246382563826638276382863829638306383163832638336383463835638366383763838638396384063841638426384363844638456384663847638486384963850638516385263853638546385563856638576385863859638606386163862638636386463865638666386763868638696387063871638726387363874638756387663877638786387963880638816388263883638846388563886638876388863889638906389163892638936389463895638966389763898638996390063901639026390363904639056390663907639086390963910639116391263913639146391563916639176391863919639206392163922639236392463925639266392763928639296393063931639326393363934639356393663937639386393963940639416394263943639446394563946639476394863949639506395163952639536395463955639566395763958639596396063961639626396363964639656396663967639686396963970639716397263973639746397563976639776397863979639806398163982639836398463985639866398763988639896399063991639926399363994639956399663997639986399964000640016400264003640046400564006640076400864009640106401164012640136401464015640166401764018640196402064021640226402364024640256402664027640286402964030640316403264033640346403564036640376403864039640406404164042640436404464045640466404764048640496405064051640526405364054640556405664057640586405964060640616406264063640646406564066640676406864069640706407164072640736407464075640766407764078640796408064081640826408364084640856408664087640886408964090640916409264093640946409564096640976409864099641006410164102641036410464105641066410764108641096411064111641126411364114641156411664117641186411964120641216412264123641246412564126641276412864129641306413164132641336413464135641366413764138641396414064141641426414364144641456414664147641486414964150641516415264153641546415564156641576415864159641606416164162641636416464165641666416764168641696417064171641726417364174641756417664177641786417964180641816418264183641846418564186641876418864189641906419164192641936419464195641966419764198641996420064201642026420364204642056420664207642086420964210642116421264213642146421564216642176421864219642206422164222642236422464225642266422764228642296423064231642326423364234642356423664237642386423964240642416424264243642446424564246642476424864249642506425164252642536425464255642566425764258642596426064261642626426364264642656426664267642686426964270642716427264273642746427564276642776427864279642806428164282642836428464285642866428764288642896429064291642926429364294642956429664297642986429964300643016430264303643046430564306643076430864309643106431164312643136431464315643166431764318643196432064321643226432364324643256432664327643286432964330643316433264333643346433564336643376433864339643406434164342643436434464345643466434764348643496435064351643526435364354643556435664357643586435964360643616436264363643646436564366643676436864369643706437164372643736437464375643766437764378643796438064381643826438364384643856438664387643886438964390643916439264393643946439564396643976439864399644006440164402644036440464405644066440764408644096441064411644126441364414644156441664417644186441964420644216442264423644246442564426644276442864429644306443164432644336443464435644366443764438644396444064441644426444364444644456444664447644486444964450644516445264453644546445564456644576445864459644606446164462644636446464465644666446764468644696447064471644726447364474644756447664477644786447964480644816448264483644846448564486644876448864489644906449164492644936449464495644966449764498644996450064501645026450364504645056450664507645086450964510645116451264513645146451564516645176451864519645206452164522645236452464525645266452764528645296453064531645326453364534645356453664537645386453964540645416454264543645446454564546645476454864549645506455164552645536455464555645566455764558645596456064561645626456364564645656456664567645686456964570645716457264573645746457564576645776457864579645806458164582645836458464585645866458764588645896459064591645926459364594645956459664597645986459964600646016460264603646046460564606646076460864609646106461164612646136461464615646166461764618646196462064621646226462364624646256462664627646286462964630646316463264633646346463564636646376463864639646406464164642646436464464645646466464764648646496465064651646526465364654646556465664657646586465964660646616466264663646646466564666646676466864669646706467164672646736467464675646766467764678646796468064681646826468364684646856468664687646886468964690646916469264693646946469564696646976469864699647006470164702647036470464705647066470764708647096471064711647126471364714647156471664717647186471964720647216472264723647246472564726647276472864729647306473164732647336473464735647366473764738647396474064741647426474364744647456474664747647486474964750647516475264753647546475564756647576475864759647606476164762647636476464765647666476764768647696477064771647726477364774647756477664777647786477964780647816478264783647846478564786647876478864789647906479164792647936479464795647966479764798647996480064801648026480364804648056480664807648086480964810648116481264813648146481564816648176481864819648206482164822648236482464825648266482764828648296483064831648326483364834648356483664837648386483964840648416484264843648446484564846648476484864849648506485164852648536485464855648566485764858648596486064861648626486364864648656486664867648686486964870648716487264873648746487564876648776487864879648806488164882648836488464885648866488764888648896489064891648926489364894648956489664897648986489964900649016490264903649046490564906649076490864909649106491164912649136491464915649166491764918649196492064921649226492364924649256492664927649286492964930649316493264933649346493564936649376493864939649406494164942649436494464945649466494764948649496495064951649526495364954649556495664957649586495964960649616496264963649646496564966649676496864969649706497164972649736497464975649766497764978649796498064981649826498364984649856498664987649886498964990649916499264993649946499564996649976499864999650006500165002650036500465005650066500765008650096501065011650126501365014650156501665017650186501965020650216502265023650246502565026650276502865029650306503165032650336503465035650366503765038650396504065041650426504365044650456504665047650486504965050650516505265053650546505565056650576505865059650606506165062650636506465065650666506765068650696507065071650726507365074650756507665077650786507965080650816508265083650846508565086650876508865089650906509165092650936509465095650966509765098650996510065101651026510365104651056510665107651086510965110651116511265113651146511565116651176511865119651206512165122651236512465125651266512765128651296513065131651326513365134651356513665137651386513965140651416514265143651446514565146651476514865149651506515165152651536515465155651566515765158651596516065161651626516365164651656516665167651686516965170651716517265173651746517565176651776517865179651806518165182651836518465185651866518765188651896519065191651926519365194651956519665197651986519965200652016520265203652046520565206652076520865209652106521165212652136521465215652166521765218652196522065221652226522365224652256522665227652286522965230652316523265233652346523565236652376523865239652406524165242652436524465245652466524765248652496525065251652526525365254652556525665257652586525965260652616526265263652646526565266652676526865269652706527165272652736527465275652766527765278652796528065281652826528365284652856528665287652886528965290652916529265293652946529565296652976529865299653006530165302653036530465305653066530765308653096531065311653126531365314653156531665317653186531965320653216532265323653246532565326653276532865329653306533165332653336533465335653366533765338653396534065341653426534365344653456534665347653486534965350653516535265353653546535565356653576535865359653606536165362653636536465365653666536765368653696537065371653726537365374653756537665377653786537965380653816538265383653846538565386653876538865389653906539165392653936539465395653966539765398653996540065401654026540365404654056540665407654086540965410654116541265413654146541565416654176541865419654206542165422654236542465425654266542765428654296543065431654326543365434654356543665437654386543965440654416544265443654446544565446654476544865449654506545165452654536545465455654566545765458654596546065461654626546365464654656546665467654686546965470654716547265473654746547565476654776547865479654806548165482654836548465485654866548765488654896549065491654926549365494654956549665497654986549965500655016550265503655046550565506655076550865509655106551165512655136551465515655166551765518655196552065521655226552365524655256552665527655286552965530655316553265533655346553565536655376553865539655406554165542655436554465545655466554765548655496555065551655526555365554655556555665557655586555965560655616556265563655646556565566655676556865569655706557165572655736557465575655766557765578655796558065581655826558365584655856558665587655886558965590655916559265593655946559565596655976559865599656006560165602656036560465605656066560765608656096561065611656126561365614656156561665617656186561965620656216562265623656246562565626656276562865629656306563165632656336563465635656366563765638656396564065641656426564365644656456564665647656486564965650656516565265653656546565565656656576565865659656606566165662656636566465665656666566765668656696567065671656726567365674656756567665677656786567965680656816568265683656846568565686656876568865689656906569165692656936569465695656966569765698656996570065701657026570365704657056570665707657086570965710657116571265713657146571565716657176571865719657206572165722657236572465725657266572765728657296573065731657326573365734657356573665737657386573965740657416574265743657446574565746657476574865749657506575165752657536575465755657566575765758657596576065761657626576365764657656576665767657686576965770657716577265773657746577565776657776577865779657806578165782657836578465785657866578765788657896579065791657926579365794657956579665797657986579965800658016580265803658046580565806658076580865809658106581165812658136581465815658166581765818658196582065821658226582365824658256582665827658286582965830658316583265833658346583565836658376583865839658406584165842658436584465845658466584765848658496585065851658526585365854658556585665857658586585965860658616586265863658646586565866658676586865869658706587165872658736587465875658766587765878658796588065881658826588365884658856588665887658886588965890658916589265893658946589565896658976589865899659006590165902659036590465905659066590765908659096591065911659126591365914659156591665917659186591965920659216592265923659246592565926659276592865929659306593165932659336593465935659366593765938659396594065941659426594365944659456594665947659486594965950659516595265953659546595565956659576595865959659606596165962659636596465965659666596765968659696597065971659726597365974659756597665977659786597965980659816598265983659846598565986659876598865989659906599165992659936599465995659966599765998659996600066001660026600366004660056600666007660086600966010660116601266013660146601566016660176601866019660206602166022660236602466025660266602766028660296603066031660326603366034660356603666037660386603966040660416604266043660446604566046660476604866049660506605166052660536605466055660566605766058660596606066061660626606366064660656606666067660686606966070660716607266073660746607566076660776607866079660806608166082660836608466085660866608766088660896609066091660926609366094660956609666097660986609966100661016610266103661046610566106661076610866109661106611166112661136611466115661166611766118661196612066121661226612366124661256612666127661286612966130661316613266133661346613566136661376613866139661406614166142661436614466145661466614766148661496615066151661526615366154661556615666157661586615966160661616616266163661646616566166661676616866169661706617166172661736617466175661766617766178661796618066181661826618366184661856618666187661886618966190661916619266193661946619566196661976619866199662006620166202662036620466205662066620766208662096621066211662126621366214662156621666217662186621966220662216622266223662246622566226662276622866229662306623166232662336623466235662366623766238662396624066241662426624366244662456624666247662486624966250662516625266253662546625566256662576625866259662606626166262662636626466265662666626766268662696627066271662726627366274662756627666277662786627966280662816628266283662846628566286662876628866289662906629166292662936629466295662966629766298662996630066301663026630366304663056630666307663086630966310663116631266313663146631566316663176631866319663206632166322663236632466325663266632766328663296633066331663326633366334663356633666337663386633966340663416634266343663446634566346663476634866349663506635166352663536635466355663566635766358663596636066361663626636366364663656636666367663686636966370663716637266373663746637566376663776637866379663806638166382663836638466385663866638766388663896639066391663926639366394663956639666397663986639966400664016640266403664046640566406664076640866409664106641166412664136641466415664166641766418664196642066421664226642366424664256642666427664286642966430664316643266433664346643566436664376643866439664406644166442664436644466445664466644766448664496645066451664526645366454664556645666457664586645966460664616646266463664646646566466664676646866469664706647166472664736647466475664766647766478664796648066481664826648366484664856648666487664886648966490664916649266493664946649566496664976649866499665006650166502665036650466505665066650766508665096651066511665126651366514665156651666517665186651966520665216652266523665246652566526665276652866529665306653166532665336653466535665366653766538665396654066541665426654366544665456654666547665486654966550665516655266553665546655566556665576655866559665606656166562665636656466565665666656766568665696657066571665726657366574665756657666577665786657966580665816658266583665846658566586665876658866589665906659166592665936659466595665966659766598665996660066601666026660366604666056660666607666086660966610666116661266613666146661566616666176661866619666206662166622666236662466625666266662766628666296663066631666326663366634666356663666637666386663966640666416664266643666446664566646666476664866649666506665166652666536665466655666566665766658666596666066661666626666366664666656666666667666686666966670666716667266673666746667566676666776667866679666806668166682666836668466685666866668766688666896669066691666926669366694666956669666697666986669966700667016670266703667046670566706667076670866709667106671166712667136671466715667166671766718667196672066721667226672366724667256672666727667286672966730667316673266733667346673566736667376673866739667406674166742667436674466745667466674766748667496675066751667526675366754667556675666757667586675966760667616676266763667646676566766667676676866769667706677166772667736677466775667766677766778667796678066781667826678366784667856678666787667886678966790667916679266793667946679566796667976679866799668006680166802668036680466805668066680766808668096681066811668126681366814668156681666817668186681966820668216682266823668246682566826668276682866829668306683166832668336683466835668366683766838668396684066841668426684366844668456684666847668486684966850668516685266853668546685566856668576685866859668606686166862668636686466865668666686766868668696687066871668726687366874668756687666877668786687966880668816688266883668846688566886668876688866889668906689166892668936689466895668966689766898668996690066901669026690366904669056690666907669086690966910669116691266913669146691566916669176691866919669206692166922669236692466925669266692766928669296693066931669326693366934669356693666937669386693966940669416694266943669446694566946669476694866949669506695166952669536695466955669566695766958669596696066961669626696366964669656696666967669686696966970669716697266973669746697566976669776697866979669806698166982669836698466985669866698766988669896699066991669926699366994669956699666997669986699967000670016700267003670046700567006670076700867009670106701167012670136701467015670166701767018670196702067021670226702367024670256702667027670286702967030670316703267033670346703567036670376703867039670406704167042670436704467045670466704767048670496705067051670526705367054670556705667057670586705967060670616706267063670646706567066670676706867069670706707167072670736707467075670766707767078670796708067081670826708367084670856708667087670886708967090670916709267093670946709567096670976709867099671006710167102671036710467105671066710767108671096711067111671126711367114671156711667117671186711967120671216712267123671246712567126671276712867129671306713167132671336713467135671366713767138671396714067141671426714367144671456714667147671486714967150671516715267153671546715567156671576715867159671606716167162671636716467165671666716767168671696717067171671726717367174671756717667177671786717967180671816718267183671846718567186671876718867189671906719167192671936719467195671966719767198671996720067201672026720367204672056720667207672086720967210672116721267213672146721567216672176721867219672206722167222672236722467225672266722767228672296723067231672326723367234672356723667237672386723967240672416724267243672446724567246672476724867249672506725167252672536725467255672566725767258672596726067261672626726367264672656726667267672686726967270672716727267273672746727567276672776727867279672806728167282672836728467285672866728767288672896729067291672926729367294672956729667297672986729967300673016730267303673046730567306673076730867309673106731167312673136731467315673166731767318673196732067321673226732367324673256732667327673286732967330673316733267333673346733567336673376733867339673406734167342673436734467345673466734767348673496735067351673526735367354673556735667357673586735967360673616736267363673646736567366673676736867369673706737167372673736737467375673766737767378673796738067381673826738367384673856738667387673886738967390673916739267393673946739567396673976739867399674006740167402674036740467405674066740767408674096741067411674126741367414674156741667417674186741967420674216742267423674246742567426674276742867429674306743167432674336743467435674366743767438674396744067441674426744367444674456744667447674486744967450674516745267453674546745567456674576745867459674606746167462674636746467465674666746767468674696747067471674726747367474674756747667477674786747967480674816748267483674846748567486674876748867489674906749167492674936749467495674966749767498674996750067501675026750367504675056750667507675086750967510675116751267513675146751567516675176751867519675206752167522675236752467525675266752767528675296753067531675326753367534675356753667537675386753967540675416754267543675446754567546675476754867549675506755167552675536755467555675566755767558675596756067561675626756367564675656756667567675686756967570675716757267573675746757567576675776757867579675806758167582675836758467585675866758767588675896759067591675926759367594675956759667597675986759967600676016760267603676046760567606676076760867609676106761167612676136761467615676166761767618676196762067621676226762367624676256762667627676286762967630676316763267633676346763567636676376763867639676406764167642676436764467645676466764767648676496765067651676526765367654676556765667657676586765967660676616766267663676646766567666676676766867669676706767167672676736767467675676766767767678676796768067681676826768367684676856768667687676886768967690676916769267693676946769567696676976769867699677006770167702677036770467705677066770767708677096771067711677126771367714677156771667717677186771967720677216772267723677246772567726677276772867729677306773167732677336773467735677366773767738677396774067741677426774367744677456774667747677486774967750677516775267753677546775567756677576775867759677606776167762677636776467765677666776767768677696777067771677726777367774677756777667777677786777967780677816778267783677846778567786677876778867789677906779167792677936779467795677966779767798677996780067801678026780367804678056780667807678086780967810678116781267813678146781567816678176781867819678206782167822678236782467825678266782767828678296783067831678326783367834678356783667837678386783967840678416784267843678446784567846678476784867849678506785167852678536785467855678566785767858678596786067861678626786367864678656786667867678686786967870678716787267873678746787567876678776787867879678806788167882678836788467885678866788767888678896789067891678926789367894678956789667897678986789967900679016790267903679046790567906679076790867909679106791167912679136791467915679166791767918679196792067921679226792367924679256792667927679286792967930679316793267933679346793567936679376793867939679406794167942679436794467945679466794767948679496795067951679526795367954679556795667957679586795967960679616796267963679646796567966679676796867969679706797167972679736797467975679766797767978679796798067981679826798367984679856798667987679886798967990679916799267993679946799567996679976799867999680006800168002680036800468005680066800768008680096801068011680126801368014680156801668017680186801968020680216802268023680246802568026680276802868029680306803168032680336803468035680366803768038680396804068041680426804368044680456804668047680486804968050680516805268053680546805568056680576805868059680606806168062680636806468065680666806768068680696807068071680726807368074680756807668077680786807968080680816808268083680846808568086680876808868089680906809168092680936809468095680966809768098680996810068101681026810368104681056810668107681086810968110681116811268113681146811568116681176811868119681206812168122681236812468125681266812768128681296813068131681326813368134681356813668137681386813968140681416814268143681446814568146681476814868149681506815168152681536815468155681566815768158681596816068161681626816368164681656816668167681686816968170681716817268173681746817568176681776817868179681806818168182681836818468185681866818768188681896819068191681926819368194681956819668197681986819968200682016820268203682046820568206682076820868209682106821168212682136821468215682166821768218682196822068221682226822368224682256822668227682286822968230682316823268233682346823568236682376823868239682406824168242682436824468245682466824768248682496825068251682526825368254682556825668257682586825968260682616826268263682646826568266682676826868269682706827168272682736827468275682766827768278682796828068281682826828368284682856828668287682886828968290682916829268293682946829568296682976829868299683006830168302683036830468305683066830768308683096831068311683126831368314683156831668317683186831968320683216832268323683246832568326683276832868329683306833168332683336833468335683366833768338683396834068341683426834368344683456834668347683486834968350683516835268353683546835568356683576835868359683606836168362683636836468365683666836768368683696837068371683726837368374683756837668377683786837968380683816838268383683846838568386683876838868389683906839168392683936839468395683966839768398683996840068401684026840368404684056840668407684086840968410684116841268413684146841568416684176841868419684206842168422684236842468425684266842768428684296843068431684326843368434684356843668437684386843968440684416844268443684446844568446684476844868449684506845168452684536845468455684566845768458684596846068461684626846368464684656846668467684686846968470684716847268473684746847568476684776847868479684806848168482684836848468485684866848768488684896849068491684926849368494684956849668497684986849968500685016850268503685046850568506685076850868509685106851168512685136851468515685166851768518685196852068521685226852368524685256852668527685286852968530685316853268533685346853568536685376853868539685406854168542685436854468545685466854768548685496855068551685526855368554685556855668557685586855968560685616856268563685646856568566685676856868569685706857168572685736857468575685766857768578685796858068581685826858368584685856858668587685886858968590685916859268593685946859568596685976859868599686006860168602686036860468605686066860768608686096861068611686126861368614686156861668617686186861968620686216862268623686246862568626686276862868629686306863168632686336863468635686366863768638686396864068641686426864368644686456864668647686486864968650686516865268653686546865568656686576865868659686606866168662686636866468665686666866768668686696867068671686726867368674686756867668677686786867968680686816868268683686846868568686686876868868689686906869168692686936869468695686966869768698686996870068701687026870368704687056870668707687086870968710687116871268713687146871568716687176871868719687206872168722687236872468725687266872768728687296873068731687326873368734687356873668737687386873968740687416874268743687446874568746687476874868749687506875168752687536875468755687566875768758687596876068761687626876368764687656876668767687686876968770687716877268773687746877568776687776877868779687806878168782687836878468785687866878768788687896879068791687926879368794687956879668797687986879968800688016880268803688046880568806688076880868809688106881168812688136881468815688166881768818688196882068821688226882368824688256882668827688286882968830688316883268833688346883568836688376883868839688406884168842688436884468845688466884768848688496885068851688526885368854688556885668857688586885968860688616886268863688646886568866688676886868869688706887168872688736887468875688766887768878688796888068881688826888368884688856888668887688886888968890688916889268893688946889568896688976889868899689006890168902689036890468905689066890768908689096891068911689126891368914689156891668917689186891968920689216892268923689246892568926689276892868929689306893168932689336893468935689366893768938689396894068941689426894368944689456894668947689486894968950689516895268953689546895568956689576895868959689606896168962689636896468965689666896768968689696897068971689726897368974689756897668977689786897968980689816898268983689846898568986689876898868989689906899168992689936899468995689966899768998689996900069001690026900369004690056900669007690086900969010690116901269013690146901569016690176901869019690206902169022690236902469025690266902769028690296903069031690326903369034690356903669037690386903969040690416904269043690446904569046690476904869049690506905169052690536905469055690566905769058690596906069061690626906369064690656906669067690686906969070690716907269073690746907569076690776907869079690806908169082690836908469085690866908769088690896909069091690926909369094690956909669097690986909969100691016910269103691046910569106691076910869109691106911169112691136911469115691166911769118691196912069121691226912369124691256912669127691286912969130691316913269133691346913569136691376913869139691406914169142691436914469145691466914769148691496915069151691526915369154691556915669157691586915969160691616916269163691646916569166691676916869169691706917169172691736917469175691766917769178691796918069181691826918369184691856918669187691886918969190691916919269193691946919569196691976919869199692006920169202692036920469205692066920769208692096921069211692126921369214692156921669217692186921969220692216922269223692246922569226692276922869229692306923169232692336923469235692366923769238692396924069241692426924369244692456924669247692486924969250692516925269253692546925569256692576925869259692606926169262692636926469265692666926769268692696927069271692726927369274692756927669277692786927969280692816928269283692846928569286692876928869289692906929169292692936929469295692966929769298692996930069301693026930369304693056930669307693086930969310693116931269313693146931569316693176931869319693206932169322693236932469325693266932769328693296933069331693326933369334693356933669337693386933969340693416934269343693446934569346693476934869349693506935169352693536935469355693566935769358693596936069361693626936369364693656936669367693686936969370693716937269373693746937569376693776937869379693806938169382693836938469385693866938769388693896939069391693926939369394693956939669397693986939969400694016940269403694046940569406694076940869409694106941169412694136941469415694166941769418694196942069421694226942369424694256942669427694286942969430694316943269433694346943569436694376943869439694406944169442694436944469445694466944769448694496945069451694526945369454694556945669457694586945969460694616946269463694646946569466694676946869469694706947169472694736947469475694766947769478694796948069481694826948369484694856948669487694886948969490694916949269493694946949569496694976949869499695006950169502695036950469505695066950769508695096951069511695126951369514695156951669517695186951969520695216952269523695246952569526695276952869529695306953169532695336953469535695366953769538695396954069541695426954369544695456954669547695486954969550695516955269553695546955569556695576955869559695606956169562695636956469565695666956769568695696957069571695726957369574695756957669577695786957969580695816958269583695846958569586695876958869589695906959169592695936959469595695966959769598695996960069601696026960369604696056960669607696086960969610696116961269613696146961569616696176961869619696206962169622696236962469625696266962769628696296963069631696326963369634696356963669637696386963969640696416964269643696446964569646696476964869649696506965169652696536965469655696566965769658696596966069661696626966369664696656966669667696686966969670696716967269673696746967569676696776967869679696806968169682696836968469685696866968769688696896969069691696926969369694696956969669697696986969969700697016970269703697046970569706697076970869709697106971169712697136971469715697166971769718697196972069721697226972369724697256972669727697286972969730697316973269733697346973569736697376973869739697406974169742697436974469745697466974769748697496975069751697526975369754697556975669757697586975969760697616976269763697646976569766697676976869769697706977169772697736977469775697766977769778697796978069781697826978369784697856978669787697886978969790697916979269793697946979569796697976979869799698006980169802698036980469805698066980769808698096981069811698126981369814698156981669817698186981969820698216982269823698246982569826698276982869829698306983169832698336983469835698366983769838698396984069841698426984369844698456984669847698486984969850698516985269853698546985569856698576985869859698606986169862698636986469865698666986769868698696987069871698726987369874698756987669877698786987969880698816988269883698846988569886698876988869889698906989169892698936989469895698966989769898698996990069901699026990369904699056990669907699086990969910699116991269913699146991569916699176991869919699206992169922699236992469925699266992769928699296993069931699326993369934699356993669937699386993969940699416994269943699446994569946699476994869949699506995169952699536995469955699566995769958699596996069961699626996369964699656996669967699686996969970699716997269973699746997569976699776997869979699806998169982699836998469985699866998769988699896999069991699926999369994699956999669997699986999970000700017000270003700047000570006700077000870009700107001170012700137001470015700167001770018700197002070021700227002370024700257002670027700287002970030700317003270033700347003570036700377003870039700407004170042700437004470045700467004770048700497005070051700527005370054700557005670057700587005970060700617006270063700647006570066700677006870069700707007170072700737007470075700767007770078700797008070081700827008370084700857008670087700887008970090700917009270093700947009570096700977009870099701007010170102701037010470105701067010770108701097011070111701127011370114701157011670117701187011970120701217012270123701247012570126701277012870129701307013170132701337013470135701367013770138701397014070141701427014370144701457014670147701487014970150701517015270153701547015570156701577015870159701607016170162701637016470165701667016770168701697017070171701727017370174701757017670177701787017970180701817018270183701847018570186701877018870189701907019170192701937019470195701967019770198701997020070201702027020370204702057020670207702087020970210702117021270213702147021570216702177021870219702207022170222702237022470225702267022770228702297023070231702327023370234702357023670237702387023970240702417024270243702447024570246702477024870249702507025170252702537025470255702567025770258702597026070261702627026370264702657026670267702687026970270702717027270273702747027570276702777027870279702807028170282702837028470285702867028770288702897029070291702927029370294702957029670297702987029970300703017030270303703047030570306703077030870309703107031170312703137031470315703167031770318703197032070321703227032370324703257032670327703287032970330703317033270333703347033570336703377033870339703407034170342703437034470345703467034770348703497035070351703527035370354703557035670357703587035970360703617036270363703647036570366703677036870369703707037170372703737037470375703767037770378703797038070381703827038370384703857038670387703887038970390703917039270393703947039570396703977039870399704007040170402704037040470405704067040770408704097041070411704127041370414704157041670417704187041970420704217042270423704247042570426704277042870429704307043170432704337043470435704367043770438704397044070441704427044370444704457044670447704487044970450704517045270453704547045570456704577045870459704607046170462704637046470465704667046770468704697047070471704727047370474704757047670477704787047970480704817048270483704847048570486704877048870489704907049170492704937049470495704967049770498704997050070501705027050370504705057050670507705087050970510705117051270513705147051570516705177051870519705207052170522705237052470525705267052770528705297053070531705327053370534705357053670537705387053970540705417054270543705447054570546705477054870549705507055170552705537055470555705567055770558705597056070561705627056370564705657056670567705687056970570705717057270573705747057570576705777057870579705807058170582705837058470585705867058770588705897059070591705927059370594705957059670597705987059970600706017060270603706047060570606706077060870609706107061170612706137061470615706167061770618706197062070621706227062370624706257062670627706287062970630706317063270633706347063570636706377063870639706407064170642706437064470645706467064770648706497065070651706527065370654706557065670657706587065970660706617066270663706647066570666706677066870669706707067170672706737067470675706767067770678706797068070681706827068370684706857068670687706887068970690706917069270693706947069570696706977069870699707007070170702707037070470705707067070770708707097071070711707127071370714707157071670717707187071970720707217072270723707247072570726707277072870729707307073170732707337073470735707367073770738707397074070741707427074370744707457074670747707487074970750707517075270753707547075570756707577075870759707607076170762707637076470765707667076770768707697077070771707727077370774707757077670777707787077970780707817078270783707847078570786707877078870789707907079170792707937079470795707967079770798707997080070801708027080370804708057080670807708087080970810708117081270813708147081570816708177081870819708207082170822708237082470825708267082770828708297083070831708327083370834708357083670837708387083970840708417084270843708447084570846708477084870849708507085170852708537085470855708567085770858708597086070861708627086370864708657086670867708687086970870708717087270873708747087570876708777087870879708807088170882708837088470885708867088770888708897089070891708927089370894708957089670897708987089970900709017090270903709047090570906709077090870909709107091170912709137091470915709167091770918709197092070921709227092370924709257092670927709287092970930709317093270933709347093570936709377093870939709407094170942709437094470945709467094770948709497095070951709527095370954709557095670957709587095970960709617096270963709647096570966709677096870969709707097170972709737097470975709767097770978709797098070981709827098370984709857098670987709887098970990709917099270993709947099570996709977099870999710007100171002710037100471005710067100771008710097101071011710127101371014710157101671017710187101971020710217102271023710247102571026710277102871029710307103171032710337103471035710367103771038710397104071041710427104371044710457104671047710487104971050710517105271053710547105571056710577105871059710607106171062710637106471065710667106771068710697107071071710727107371074710757107671077710787107971080710817108271083710847108571086710877108871089710907109171092710937109471095710967109771098710997110071101711027110371104711057110671107711087110971110711117111271113711147111571116711177111871119711207112171122711237112471125711267112771128711297113071131711327113371134711357113671137711387113971140711417114271143711447114571146711477114871149711507115171152711537115471155711567115771158711597116071161711627116371164711657116671167711687116971170711717117271173711747117571176711777117871179711807118171182711837118471185711867118771188711897119071191711927119371194711957119671197711987119971200712017120271203712047120571206712077120871209712107121171212712137121471215712167121771218712197122071221712227122371224712257122671227712287122971230712317123271233712347123571236712377123871239712407124171242712437124471245712467124771248712497125071251712527125371254712557125671257712587125971260712617126271263712647126571266712677126871269712707127171272712737127471275712767127771278712797128071281712827128371284712857128671287712887128971290712917129271293712947129571296712977129871299713007130171302713037130471305713067130771308713097131071311713127131371314713157131671317713187131971320713217132271323713247132571326713277132871329713307133171332713337133471335713367133771338713397134071341713427134371344713457134671347713487134971350713517135271353713547135571356713577135871359713607136171362713637136471365713667136771368713697137071371713727137371374713757137671377713787137971380713817138271383713847138571386713877138871389713907139171392713937139471395713967139771398713997140071401714027140371404714057140671407714087140971410714117141271413714147141571416714177141871419714207142171422714237142471425714267142771428714297143071431714327143371434714357143671437714387143971440714417144271443714447144571446714477144871449714507145171452714537145471455714567145771458714597146071461714627146371464714657146671467714687146971470714717147271473714747147571476714777147871479714807148171482714837148471485714867148771488714897149071491714927149371494714957149671497714987149971500715017150271503715047150571506715077150871509715107151171512715137151471515715167151771518715197152071521715227152371524715257152671527715287152971530715317153271533715347153571536715377153871539715407154171542715437154471545715467154771548715497155071551715527155371554715557155671557715587155971560715617156271563715647156571566715677156871569715707157171572715737157471575715767157771578715797158071581715827158371584715857158671587715887158971590715917159271593715947159571596715977159871599716007160171602716037160471605716067160771608716097161071611716127161371614716157161671617716187161971620716217162271623716247162571626716277162871629716307163171632716337163471635716367163771638716397164071641716427164371644716457164671647716487164971650716517165271653716547165571656716577165871659716607166171662716637166471665716667166771668716697167071671716727167371674716757167671677716787167971680716817168271683716847168571686716877168871689716907169171692716937169471695716967169771698716997170071701717027170371704717057170671707717087170971710717117171271713717147171571716717177171871719717207172171722717237172471725717267172771728717297173071731717327173371734717357173671737717387173971740717417174271743717447174571746717477174871749717507175171752717537175471755717567175771758717597176071761717627176371764717657176671767717687176971770717717177271773717747177571776717777177871779717807178171782717837178471785717867178771788717897179071791717927179371794717957179671797717987179971800718017180271803718047180571806718077180871809718107181171812718137181471815718167181771818718197182071821718227182371824718257182671827718287182971830718317183271833718347183571836718377183871839718407184171842718437184471845718467184771848718497185071851718527185371854718557185671857718587185971860718617186271863718647186571866718677186871869718707187171872718737187471875718767187771878718797188071881718827188371884718857188671887718887188971890718917189271893718947189571896718977189871899719007190171902719037190471905719067190771908719097191071911719127191371914719157191671917719187191971920719217192271923719247192571926719277192871929719307193171932719337193471935719367193771938719397194071941719427194371944719457194671947719487194971950719517195271953719547195571956719577195871959719607196171962719637196471965719667196771968719697197071971719727197371974719757197671977719787197971980719817198271983719847198571986719877198871989719907199171992719937199471995719967199771998719997200072001720027200372004720057200672007720087200972010720117201272013720147201572016720177201872019720207202172022720237202472025720267202772028720297203072031720327203372034720357203672037720387203972040720417204272043720447204572046720477204872049720507205172052720537205472055720567205772058720597206072061720627206372064720657206672067720687206972070720717207272073720747207572076720777207872079720807208172082720837208472085720867208772088720897209072091720927209372094720957209672097720987209972100721017210272103721047210572106721077210872109721107211172112721137211472115721167211772118721197212072121721227212372124721257212672127721287212972130721317213272133721347213572136721377213872139721407214172142721437214472145721467214772148721497215072151721527215372154721557215672157721587215972160721617216272163721647216572166721677216872169721707217172172721737217472175721767217772178721797218072181721827218372184721857218672187721887218972190721917219272193721947219572196721977219872199722007220172202722037220472205722067220772208722097221072211722127221372214722157221672217722187221972220722217222272223722247222572226722277222872229722307223172232722337223472235722367223772238722397224072241722427224372244722457224672247722487224972250722517225272253722547225572256722577225872259722607226172262722637226472265722667226772268722697227072271722727227372274722757227672277722787227972280722817228272283722847228572286722877228872289722907229172292722937229472295722967229772298722997230072301723027230372304723057230672307723087230972310723117231272313723147231572316723177231872319723207232172322723237232472325723267232772328723297233072331723327233372334723357233672337723387233972340723417234272343723447234572346723477234872349723507235172352723537235472355723567235772358723597236072361723627236372364723657236672367723687236972370723717237272373723747237572376723777237872379723807238172382723837238472385723867238772388723897239072391723927239372394723957239672397723987239972400724017240272403724047240572406724077240872409724107241172412724137241472415724167241772418724197242072421724227242372424724257242672427724287242972430724317243272433724347243572436724377243872439724407244172442724437244472445724467244772448724497245072451724527245372454724557245672457724587245972460724617246272463724647246572466724677246872469724707247172472724737247472475724767247772478724797248072481724827248372484724857248672487724887248972490724917249272493724947249572496724977249872499725007250172502725037250472505725067250772508725097251072511725127251372514725157251672517725187251972520725217252272523725247252572526725277252872529725307253172532725337253472535725367253772538725397254072541725427254372544725457254672547725487254972550725517255272553725547255572556725577255872559725607256172562725637256472565725667256772568725697257072571725727257372574725757257672577725787257972580725817258272583725847258572586725877258872589725907259172592725937259472595725967259772598725997260072601726027260372604726057260672607726087260972610726117261272613726147261572616726177261872619726207262172622726237262472625726267262772628726297263072631726327263372634726357263672637726387263972640726417264272643726447264572646726477264872649726507265172652726537265472655726567265772658726597266072661726627266372664726657266672667726687266972670726717267272673726747267572676726777267872679726807268172682726837268472685726867268772688726897269072691726927269372694726957269672697726987269972700727017270272703727047270572706727077270872709727107271172712727137271472715727167271772718727197272072721727227272372724727257272672727727287272972730727317273272733727347273572736727377273872739727407274172742727437274472745727467274772748727497275072751727527275372754727557275672757727587275972760727617276272763727647276572766727677276872769727707277172772727737277472775727767277772778727797278072781727827278372784727857278672787727887278972790727917279272793727947279572796727977279872799728007280172802728037280472805728067280772808728097281072811728127281372814728157281672817728187281972820728217282272823728247282572826728277282872829728307283172832728337283472835728367283772838728397284072841728427284372844728457284672847728487284972850728517285272853728547285572856728577285872859728607286172862728637286472865728667286772868728697287072871728727287372874728757287672877728787287972880728817288272883728847288572886728877288872889728907289172892728937289472895728967289772898728997290072901729027290372904729057290672907729087290972910729117291272913729147291572916729177291872919729207292172922729237292472925729267292772928729297293072931729327293372934729357293672937729387293972940729417294272943729447294572946729477294872949729507295172952729537295472955729567295772958729597296072961729627296372964729657296672967729687296972970729717297272973729747297572976729777297872979729807298172982729837298472985729867298772988729897299072991729927299372994729957299672997729987299973000730017300273003730047300573006730077300873009730107301173012730137301473015730167301773018730197302073021730227302373024730257302673027730287302973030730317303273033730347303573036730377303873039730407304173042730437304473045730467304773048730497305073051730527305373054730557305673057730587305973060730617306273063730647306573066730677306873069730707307173072730737307473075730767307773078730797308073081730827308373084730857308673087730887308973090730917309273093730947309573096730977309873099731007310173102731037310473105731067310773108731097311073111731127311373114731157311673117731187311973120731217312273123731247312573126731277312873129731307313173132731337313473135731367313773138731397314073141731427314373144731457314673147731487314973150731517315273153731547315573156731577315873159731607316173162731637316473165731667316773168731697317073171731727317373174731757317673177731787317973180731817318273183731847318573186731877318873189731907319173192731937319473195731967319773198731997320073201732027320373204732057320673207732087320973210732117321273213732147321573216732177321873219732207322173222732237322473225732267322773228732297323073231732327323373234732357323673237732387323973240732417324273243732447324573246732477324873249732507325173252732537325473255732567325773258732597326073261732627326373264732657326673267732687326973270732717327273273732747327573276732777327873279732807328173282732837328473285732867328773288732897329073291732927329373294732957329673297732987329973300733017330273303733047330573306733077330873309733107331173312733137331473315733167331773318733197332073321733227332373324733257332673327733287332973330733317333273333733347333573336733377333873339733407334173342733437334473345733467334773348733497335073351733527335373354733557335673357733587335973360733617336273363733647336573366733677336873369733707337173372733737337473375733767337773378733797338073381733827338373384733857338673387733887338973390733917339273393733947339573396733977339873399734007340173402734037340473405734067340773408734097341073411734127341373414734157341673417734187341973420734217342273423734247342573426734277342873429734307343173432734337343473435734367343773438734397344073441734427344373444734457344673447734487344973450734517345273453734547345573456734577345873459734607346173462734637346473465734667346773468734697347073471734727347373474734757347673477734787347973480734817348273483734847348573486734877348873489734907349173492734937349473495734967349773498734997350073501735027350373504735057350673507735087350973510735117351273513735147351573516735177351873519735207352173522735237352473525735267352773528735297353073531735327353373534735357353673537735387353973540735417354273543735447354573546735477354873549735507355173552735537355473555735567355773558735597356073561735627356373564735657356673567735687356973570735717357273573735747357573576735777357873579735807358173582735837358473585735867358773588735897359073591735927359373594735957359673597735987359973600736017360273603736047360573606736077360873609736107361173612736137361473615736167361773618736197362073621736227362373624736257362673627736287362973630736317363273633736347363573636736377363873639736407364173642736437364473645736467364773648736497365073651736527365373654736557365673657736587365973660736617366273663736647366573666736677366873669736707367173672736737367473675736767367773678736797368073681736827368373684736857368673687736887368973690736917369273693736947369573696736977369873699737007370173702737037370473705737067370773708737097371073711737127371373714737157371673717737187371973720737217372273723737247372573726737277372873729737307373173732737337373473735737367373773738737397374073741737427374373744737457374673747737487374973750737517375273753737547375573756737577375873759737607376173762737637376473765737667376773768737697377073771737727377373774737757377673777737787377973780737817378273783737847378573786737877378873789737907379173792737937379473795737967379773798737997380073801738027380373804738057380673807738087380973810738117381273813738147381573816738177381873819738207382173822738237382473825738267382773828738297383073831738327383373834738357383673837738387383973840738417384273843738447384573846738477384873849738507385173852738537385473855738567385773858738597386073861738627386373864738657386673867738687386973870738717387273873738747387573876738777387873879738807388173882738837388473885738867388773888738897389073891738927389373894738957389673897738987389973900739017390273903739047390573906739077390873909739107391173912739137391473915739167391773918739197392073921739227392373924739257392673927739287392973930739317393273933739347393573936739377393873939739407394173942739437394473945739467394773948739497395073951739527395373954739557395673957739587395973960739617396273963739647396573966739677396873969739707397173972739737397473975739767397773978739797398073981739827398373984739857398673987739887398973990739917399273993739947399573996739977399873999740007400174002740037400474005740067400774008740097401074011740127401374014740157401674017740187401974020740217402274023740247402574026740277402874029740307403174032740337403474035740367403774038740397404074041740427404374044740457404674047740487404974050740517405274053740547405574056740577405874059740607406174062740637406474065740667406774068740697407074071740727407374074740757407674077740787407974080740817408274083740847408574086740877408874089740907409174092740937409474095740967409774098740997410074101741027410374104741057410674107741087410974110741117411274113741147411574116741177411874119741207412174122741237412474125741267412774128741297413074131741327413374134741357413674137741387413974140741417414274143741447414574146741477414874149741507415174152741537415474155741567415774158741597416074161741627416374164741657416674167741687416974170741717417274173741747417574176741777417874179741807418174182741837418474185741867418774188741897419074191741927419374194741957419674197741987419974200742017420274203742047420574206742077420874209742107421174212742137421474215742167421774218742197422074221742227422374224742257422674227742287422974230742317423274233742347423574236742377423874239742407424174242742437424474245742467424774248742497425074251742527425374254742557425674257742587425974260742617426274263742647426574266742677426874269742707427174272742737427474275742767427774278742797428074281742827428374284742857428674287742887428974290742917429274293742947429574296742977429874299743007430174302743037430474305743067430774308743097431074311743127431374314743157431674317743187431974320743217432274323743247432574326743277432874329743307433174332743337433474335743367433774338743397434074341743427434374344743457434674347743487434974350743517435274353743547435574356743577435874359743607436174362743637436474365743667436774368743697437074371743727437374374743757437674377743787437974380743817438274383743847438574386743877438874389743907439174392743937439474395743967439774398743997440074401744027440374404744057440674407744087440974410744117441274413744147441574416744177441874419744207442174422744237442474425744267442774428744297443074431744327443374434744357443674437744387443974440744417444274443744447444574446744477444874449744507445174452744537445474455744567445774458744597446074461744627446374464744657446674467744687446974470744717447274473744747447574476744777447874479744807448174482744837448474485744867448774488744897449074491744927449374494744957449674497744987449974500745017450274503745047450574506745077450874509745107451174512745137451474515745167451774518745197452074521745227452374524745257452674527745287452974530745317453274533745347453574536745377453874539745407454174542745437454474545745467454774548745497455074551745527455374554745557455674557745587455974560745617456274563745647456574566745677456874569745707457174572745737457474575745767457774578745797458074581745827458374584745857458674587745887458974590745917459274593745947459574596745977459874599746007460174602746037460474605746067460774608746097461074611746127461374614746157461674617746187461974620746217462274623746247462574626746277462874629746307463174632746337463474635746367463774638746397464074641746427464374644746457464674647746487464974650746517465274653746547465574656746577465874659746607466174662746637466474665746667466774668746697467074671746727467374674746757467674677746787467974680746817468274683746847468574686746877468874689746907469174692746937469474695746967469774698746997470074701747027470374704747057470674707747087470974710747117471274713747147471574716747177471874719747207472174722747237472474725747267472774728747297473074731747327473374734747357473674737747387473974740747417474274743747447474574746747477474874749747507475174752747537475474755747567475774758747597476074761747627476374764747657476674767747687476974770747717477274773747747477574776747777477874779747807478174782747837478474785747867478774788747897479074791747927479374794747957479674797747987479974800748017480274803748047480574806748077480874809748107481174812748137481474815748167481774818748197482074821748227482374824748257482674827748287482974830748317483274833748347483574836748377483874839748407484174842748437484474845748467484774848748497485074851748527485374854748557485674857748587485974860748617486274863748647486574866748677486874869748707487174872748737487474875748767487774878748797488074881748827488374884748857488674887748887488974890748917489274893748947489574896748977489874899749007490174902749037490474905749067490774908749097491074911749127491374914749157491674917749187491974920749217492274923749247492574926749277492874929749307493174932749337493474935749367493774938749397494074941749427494374944749457494674947749487494974950749517495274953749547495574956749577495874959749607496174962749637496474965749667496774968749697497074971749727497374974749757497674977749787497974980749817498274983749847498574986749877498874989749907499174992749937499474995749967499774998749997500075001750027500375004750057500675007750087500975010750117501275013750147501575016750177501875019750207502175022750237502475025750267502775028750297503075031750327503375034750357503675037750387503975040750417504275043750447504575046750477504875049750507505175052750537505475055750567505775058750597506075061750627506375064750657506675067750687506975070750717507275073750747507575076750777507875079750807508175082750837508475085750867508775088750897509075091750927509375094750957509675097750987509975100751017510275103751047510575106751077510875109751107511175112751137511475115751167511775118751197512075121751227512375124751257512675127751287512975130751317513275133751347513575136751377513875139751407514175142751437514475145751467514775148751497515075151751527515375154751557515675157751587515975160751617516275163751647516575166751677516875169751707517175172751737517475175751767517775178751797518075181751827518375184751857518675187751887518975190751917519275193751947519575196751977519875199752007520175202752037520475205752067520775208752097521075211752127521375214752157521675217752187521975220752217522275223752247522575226752277522875229752307523175232752337523475235752367523775238752397524075241752427524375244752457524675247752487524975250752517525275253752547525575256752577525875259752607526175262752637526475265752667526775268752697527075271752727527375274752757527675277752787527975280752817528275283752847528575286752877528875289752907529175292752937529475295752967529775298752997530075301753027530375304753057530675307753087530975310753117531275313753147531575316753177531875319753207532175322753237532475325753267532775328753297533075331753327533375334753357533675337753387533975340753417534275343753447534575346753477534875349753507535175352753537535475355753567535775358753597536075361753627536375364753657536675367753687536975370753717537275373753747537575376753777537875379753807538175382753837538475385753867538775388753897539075391753927539375394753957539675397753987539975400754017540275403754047540575406754077540875409754107541175412754137541475415754167541775418754197542075421754227542375424754257542675427754287542975430754317543275433754347543575436754377543875439754407544175442754437544475445754467544775448754497545075451754527545375454754557545675457754587545975460754617546275463754647546575466754677546875469754707547175472754737547475475754767547775478754797548075481754827548375484754857548675487754887548975490754917549275493754947549575496754977549875499755007550175502755037550475505755067550775508755097551075511755127551375514755157551675517755187551975520755217552275523755247552575526755277552875529755307553175532755337553475535755367553775538755397554075541755427554375544755457554675547755487554975550755517555275553755547555575556755577555875559755607556175562755637556475565755667556775568755697557075571755727557375574755757557675577755787557975580755817558275583755847558575586755877558875589755907559175592755937559475595755967559775598755997560075601756027560375604756057560675607756087560975610756117561275613756147561575616756177561875619756207562175622756237562475625756267562775628756297563075631756327563375634756357563675637756387563975640756417564275643756447564575646756477564875649756507565175652756537565475655756567565775658756597566075661756627566375664756657566675667756687566975670756717567275673756747567575676756777567875679756807568175682756837568475685756867568775688756897569075691756927569375694756957569675697756987569975700757017570275703757047570575706757077570875709757107571175712757137571475715757167571775718757197572075721757227572375724757257572675727757287572975730757317573275733757347573575736757377573875739757407574175742757437574475745757467574775748757497575075751757527575375754757557575675757757587575975760757617576275763757647576575766757677576875769757707577175772757737577475775757767577775778757797578075781757827578375784757857578675787757887578975790757917579275793757947579575796757977579875799758007580175802758037580475805758067580775808758097581075811758127581375814758157581675817758187581975820758217582275823758247582575826758277582875829758307583175832758337583475835758367583775838758397584075841758427584375844758457584675847758487584975850758517585275853758547585575856758577585875859758607586175862758637586475865758667586775868758697587075871758727587375874758757587675877758787587975880758817588275883758847588575886758877588875889758907589175892758937589475895758967589775898758997590075901759027590375904759057590675907759087590975910759117591275913759147591575916759177591875919759207592175922759237592475925759267592775928759297593075931759327593375934759357593675937759387593975940759417594275943759447594575946759477594875949759507595175952759537595475955759567595775958759597596075961759627596375964759657596675967759687596975970759717597275973759747597575976759777597875979759807598175982759837598475985759867598775988759897599075991759927599375994759957599675997759987599976000760017600276003760047600576006760077600876009760107601176012760137601476015760167601776018760197602076021760227602376024760257602676027760287602976030760317603276033760347603576036760377603876039760407604176042760437604476045760467604776048760497605076051760527605376054760557605676057760587605976060760617606276063760647606576066760677606876069760707607176072760737607476075760767607776078760797608076081760827608376084760857608676087760887608976090760917609276093760947609576096760977609876099761007610176102761037610476105761067610776108761097611076111761127611376114761157611676117761187611976120761217612276123761247612576126761277612876129761307613176132761337613476135761367613776138761397614076141761427614376144761457614676147761487614976150761517615276153761547615576156761577615876159761607616176162761637616476165761667616776168761697617076171761727617376174761757617676177761787617976180761817618276183761847618576186761877618876189761907619176192761937619476195761967619776198761997620076201762027620376204762057620676207762087620976210762117621276213762147621576216762177621876219762207622176222762237622476225762267622776228762297623076231762327623376234762357623676237762387623976240762417624276243762447624576246762477624876249762507625176252762537625476255762567625776258762597626076261762627626376264762657626676267762687626976270762717627276273762747627576276762777627876279762807628176282762837628476285762867628776288762897629076291762927629376294762957629676297762987629976300763017630276303763047630576306763077630876309763107631176312763137631476315763167631776318763197632076321763227632376324763257632676327763287632976330763317633276333763347633576336763377633876339763407634176342763437634476345763467634776348763497635076351763527635376354763557635676357763587635976360763617636276363763647636576366763677636876369763707637176372763737637476375763767637776378763797638076381763827638376384763857638676387763887638976390763917639276393763947639576396763977639876399764007640176402764037640476405764067640776408764097641076411764127641376414764157641676417764187641976420764217642276423764247642576426764277642876429764307643176432764337643476435764367643776438764397644076441764427644376444764457644676447764487644976450764517645276453764547645576456764577645876459764607646176462764637646476465764667646776468764697647076471764727647376474764757647676477764787647976480764817648276483764847648576486764877648876489764907649176492764937649476495764967649776498764997650076501765027650376504765057650676507765087650976510765117651276513765147651576516765177651876519765207652176522765237652476525765267652776528765297653076531765327653376534765357653676537765387653976540765417654276543765447654576546765477654876549765507655176552765537655476555765567655776558765597656076561765627656376564765657656676567765687656976570765717657276573765747657576576765777657876579765807658176582765837658476585765867658776588765897659076591765927659376594765957659676597765987659976600766017660276603766047660576606766077660876609766107661176612766137661476615766167661776618766197662076621766227662376624766257662676627766287662976630766317663276633766347663576636766377663876639766407664176642766437664476645766467664776648766497665076651766527665376654766557665676657766587665976660766617666276663766647666576666766677666876669766707667176672766737667476675766767667776678766797668076681766827668376684766857668676687766887668976690766917669276693766947669576696766977669876699767007670176702767037670476705767067670776708767097671076711767127671376714767157671676717767187671976720767217672276723767247672576726767277672876729767307673176732767337673476735767367673776738767397674076741767427674376744767457674676747767487674976750767517675276753767547675576756767577675876759767607676176762767637676476765767667676776768767697677076771767727677376774767757677676777767787677976780767817678276783767847678576786767877678876789767907679176792767937679476795767967679776798767997680076801768027680376804768057680676807768087680976810768117681276813768147681576816768177681876819768207682176822768237682476825768267682776828768297683076831768327683376834768357683676837768387683976840768417684276843768447684576846768477684876849768507685176852768537685476855768567685776858768597686076861768627686376864768657686676867768687686976870768717687276873768747687576876768777687876879768807688176882768837688476885768867688776888768897689076891768927689376894768957689676897768987689976900769017690276903769047690576906769077690876909769107691176912769137691476915769167691776918769197692076921769227692376924769257692676927769287692976930769317693276933769347693576936769377693876939769407694176942769437694476945769467694776948769497695076951769527695376954769557695676957769587695976960769617696276963769647696576966769677696876969769707697176972769737697476975769767697776978769797698076981769827698376984769857698676987769887698976990769917699276993769947699576996769977699876999770007700177002770037700477005770067700777008770097701077011770127701377014770157701677017770187701977020770217702277023770247702577026770277702877029770307703177032770337703477035770367703777038770397704077041770427704377044770457704677047770487704977050770517705277053770547705577056770577705877059770607706177062770637706477065770667706777068770697707077071770727707377074770757707677077770787707977080770817708277083770847708577086770877708877089770907709177092770937709477095770967709777098770997710077101771027710377104771057710677107771087710977110771117711277113771147711577116771177711877119771207712177122771237712477125771267712777128771297713077131771327713377134771357713677137771387713977140771417714277143771447714577146771477714877149771507715177152771537715477155771567715777158771597716077161771627716377164771657716677167771687716977170771717717277173771747717577176771777717877179771807718177182771837718477185771867718777188771897719077191771927719377194771957719677197771987719977200772017720277203772047720577206772077720877209772107721177212772137721477215772167721777218772197722077221772227722377224772257722677227772287722977230772317723277233772347723577236772377723877239772407724177242772437724477245772467724777248772497725077251772527725377254772557725677257772587725977260772617726277263772647726577266772677726877269772707727177272772737727477275772767727777278772797728077281772827728377284772857728677287772887728977290772917729277293772947729577296772977729877299773007730177302773037730477305773067730777308773097731077311773127731377314773157731677317773187731977320773217732277323773247732577326773277732877329773307733177332773337733477335773367733777338773397734077341773427734377344773457734677347773487734977350773517735277353773547735577356773577735877359773607736177362773637736477365773667736777368773697737077371773727737377374773757737677377773787737977380773817738277383773847738577386773877738877389773907739177392773937739477395773967739777398773997740077401774027740377404774057740677407774087740977410774117741277413774147741577416774177741877419774207742177422774237742477425774267742777428774297743077431774327743377434774357743677437774387743977440774417744277443774447744577446774477744877449774507745177452774537745477455774567745777458774597746077461774627746377464774657746677467774687746977470774717747277473774747747577476774777747877479774807748177482774837748477485774867748777488774897749077491774927749377494774957749677497774987749977500775017750277503775047750577506775077750877509775107751177512775137751477515775167751777518775197752077521775227752377524775257752677527775287752977530775317753277533775347753577536775377753877539775407754177542775437754477545775467754777548775497755077551775527755377554775557755677557775587755977560775617756277563775647756577566775677756877569775707757177572775737757477575775767757777578775797758077581775827758377584775857758677587775887758977590775917759277593775947759577596775977759877599776007760177602776037760477605776067760777608776097761077611776127761377614776157761677617776187761977620776217762277623776247762577626776277762877629776307763177632776337763477635776367763777638776397764077641776427764377644776457764677647776487764977650776517765277653776547765577656776577765877659776607766177662776637766477665776667766777668776697767077671776727767377674776757767677677776787767977680776817768277683776847768577686776877768877689776907769177692776937769477695776967769777698776997770077701777027770377704777057770677707777087770977710777117771277713777147771577716777177771877719777207772177722777237772477725777267772777728777297773077731777327773377734777357773677737777387773977740777417774277743777447774577746777477774877749777507775177752777537775477755777567775777758777597776077761777627776377764777657776677767777687776977770777717777277773777747777577776777777777877779777807778177782777837778477785777867778777788777897779077791777927779377794777957779677797777987779977800778017780277803778047780577806778077780877809778107781177812778137781477815778167781777818778197782077821778227782377824778257782677827778287782977830778317783277833778347783577836778377783877839778407784177842778437784477845778467784777848778497785077851778527785377854778557785677857778587785977860778617786277863778647786577866778677786877869778707787177872778737787477875778767787777878778797788077881778827788377884778857788677887778887788977890778917789277893778947789577896778977789877899779007790177902779037790477905779067790777908779097791077911779127791377914779157791677917779187791977920779217792277923779247792577926779277792877929779307793177932779337793477935779367793777938779397794077941779427794377944779457794677947779487794977950779517795277953779547795577956779577795877959779607796177962779637796477965779667796777968779697797077971779727797377974779757797677977779787797977980779817798277983779847798577986779877798877989779907799177992779937799477995779967799777998779997800078001780027800378004780057800678007780087800978010780117801278013780147801578016780177801878019780207802178022780237802478025780267802778028780297803078031780327803378034780357803678037780387803978040780417804278043780447804578046780477804878049780507805178052780537805478055780567805778058780597806078061780627806378064780657806678067780687806978070780717807278073780747807578076780777807878079780807808178082780837808478085780867808778088780897809078091780927809378094780957809678097780987809978100781017810278103781047810578106781077810878109781107811178112781137811478115781167811778118781197812078121781227812378124781257812678127781287812978130781317813278133781347813578136781377813878139781407814178142781437814478145781467814778148781497815078151781527815378154781557815678157781587815978160781617816278163781647816578166781677816878169781707817178172781737817478175781767817778178781797818078181781827818378184781857818678187781887818978190781917819278193781947819578196781977819878199782007820178202782037820478205782067820778208782097821078211782127821378214782157821678217782187821978220782217822278223782247822578226782277822878229782307823178232782337823478235782367823778238782397824078241782427824378244782457824678247782487824978250782517825278253782547825578256782577825878259782607826178262782637826478265782667826778268782697827078271782727827378274782757827678277782787827978280782817828278283782847828578286782877828878289782907829178292782937829478295782967829778298782997830078301783027830378304783057830678307783087830978310783117831278313783147831578316783177831878319783207832178322783237832478325783267832778328783297833078331783327833378334783357833678337783387833978340783417834278343783447834578346783477834878349783507835178352783537835478355783567835778358783597836078361783627836378364783657836678367783687836978370783717837278373783747837578376783777837878379783807838178382783837838478385783867838778388783897839078391783927839378394783957839678397783987839978400784017840278403784047840578406784077840878409784107841178412784137841478415784167841778418784197842078421784227842378424784257842678427784287842978430784317843278433784347843578436784377843878439784407844178442784437844478445784467844778448784497845078451784527845378454784557845678457784587845978460784617846278463784647846578466784677846878469784707847178472784737847478475784767847778478784797848078481784827848378484784857848678487784887848978490784917849278493784947849578496784977849878499785007850178502785037850478505785067850778508785097851078511785127851378514785157851678517785187851978520785217852278523785247852578526785277852878529785307853178532785337853478535785367853778538785397854078541785427854378544785457854678547785487854978550785517855278553785547855578556785577855878559785607856178562785637856478565785667856778568785697857078571785727857378574785757857678577785787857978580785817858278583785847858578586785877858878589785907859178592785937859478595785967859778598785997860078601786027860378604786057860678607786087860978610786117861278613786147861578616786177861878619786207862178622786237862478625786267862778628786297863078631786327863378634786357863678637786387863978640786417864278643786447864578646786477864878649786507865178652786537865478655786567865778658786597866078661786627866378664786657866678667786687866978670786717867278673786747867578676786777867878679786807868178682786837868478685786867868778688786897869078691786927869378694786957869678697786987869978700787017870278703787047870578706787077870878709787107871178712787137871478715787167871778718787197872078721787227872378724787257872678727787287872978730787317873278733787347873578736787377873878739787407874178742787437874478745787467874778748787497875078751787527875378754787557875678757787587875978760787617876278763787647876578766787677876878769787707877178772787737877478775787767877778778787797878078781787827878378784787857878678787787887878978790787917879278793787947879578796787977879878799788007880178802788037880478805788067880778808788097881078811788127881378814788157881678817788187881978820788217882278823788247882578826788277882878829788307883178832788337883478835788367883778838788397884078841788427884378844788457884678847788487884978850788517885278853788547885578856788577885878859788607886178862788637886478865788667886778868788697887078871788727887378874788757887678877788787887978880788817888278883788847888578886788877888878889788907889178892788937889478895788967889778898788997890078901789027890378904789057890678907789087890978910789117891278913789147891578916789177891878919789207892178922789237892478925789267892778928789297893078931789327893378934789357893678937789387893978940789417894278943789447894578946789477894878949789507895178952789537895478955789567895778958789597896078961789627896378964789657896678967789687896978970789717897278973789747897578976789777897878979789807898178982789837898478985789867898778988789897899078991789927899378994789957899678997789987899979000790017900279003790047900579006790077900879009790107901179012790137901479015790167901779018790197902079021790227902379024790257902679027790287902979030790317903279033790347903579036790377903879039790407904179042790437904479045790467904779048790497905079051790527905379054790557905679057790587905979060790617906279063790647906579066790677906879069790707907179072790737907479075790767907779078790797908079081790827908379084790857908679087790887908979090790917909279093790947909579096790977909879099791007910179102791037910479105791067910779108791097911079111791127911379114791157911679117791187911979120791217912279123791247912579126791277912879129791307913179132791337913479135791367913779138791397914079141791427914379144791457914679147791487914979150791517915279153791547915579156791577915879159791607916179162791637916479165791667916779168791697917079171791727917379174791757917679177791787917979180791817918279183791847918579186791877918879189791907919179192791937919479195791967919779198791997920079201792027920379204792057920679207792087920979210792117921279213792147921579216792177921879219792207922179222792237922479225792267922779228792297923079231792327923379234792357923679237792387923979240792417924279243792447924579246792477924879249792507925179252792537925479255792567925779258792597926079261792627926379264792657926679267792687926979270792717927279273792747927579276792777927879279792807928179282792837928479285792867928779288792897929079291792927929379294792957929679297792987929979300793017930279303793047930579306793077930879309793107931179312793137931479315793167931779318793197932079321793227932379324793257932679327793287932979330793317933279333793347933579336793377933879339793407934179342793437934479345793467934779348793497935079351793527935379354793557935679357793587935979360793617936279363793647936579366793677936879369793707937179372793737937479375793767937779378793797938079381793827938379384793857938679387793887938979390793917939279393793947939579396793977939879399794007940179402794037940479405794067940779408794097941079411794127941379414794157941679417794187941979420794217942279423794247942579426794277942879429794307943179432794337943479435794367943779438794397944079441794427944379444794457944679447794487944979450794517945279453794547945579456794577945879459794607946179462794637946479465794667946779468794697947079471794727947379474794757947679477794787947979480794817948279483794847948579486794877948879489794907949179492794937949479495794967949779498794997950079501795027950379504795057950679507795087950979510795117951279513795147951579516795177951879519795207952179522795237952479525795267952779528795297953079531795327953379534795357953679537795387953979540795417954279543795447954579546795477954879549795507955179552795537955479555795567955779558795597956079561795627956379564795657956679567795687956979570795717957279573795747957579576795777957879579795807958179582795837958479585795867958779588795897959079591795927959379594795957959679597795987959979600796017960279603796047960579606796077960879609796107961179612796137961479615796167961779618796197962079621796227962379624796257962679627796287962979630796317963279633796347963579636796377963879639796407964179642796437964479645796467964779648796497965079651796527965379654796557965679657796587965979660796617966279663796647966579666796677966879669796707967179672796737967479675796767967779678796797968079681796827968379684796857968679687796887968979690796917969279693796947969579696796977969879699797007970179702797037970479705797067970779708797097971079711797127971379714797157971679717797187971979720797217972279723797247972579726797277972879729797307973179732797337973479735797367973779738797397974079741797427974379744797457974679747797487974979750797517975279753797547975579756797577975879759797607976179762797637976479765797667976779768797697977079771797727977379774797757977679777797787977979780797817978279783797847978579786797877978879789797907979179792797937979479795797967979779798797997980079801798027980379804798057980679807798087980979810798117981279813798147981579816798177981879819798207982179822798237982479825798267982779828798297983079831798327983379834798357983679837798387983979840798417984279843798447984579846798477984879849798507985179852798537985479855798567985779858798597986079861798627986379864798657986679867798687986979870798717987279873798747987579876798777987879879798807988179882798837988479885798867988779888798897989079891798927989379894798957989679897798987989979900799017990279903799047990579906799077990879909799107991179912799137991479915799167991779918799197992079921799227992379924799257992679927799287992979930799317993279933799347993579936799377993879939799407994179942799437994479945799467994779948799497995079951799527995379954799557995679957799587995979960799617996279963799647996579966799677996879969799707997179972799737997479975799767997779978799797998079981799827998379984799857998679987799887998979990799917999279993799947999579996799977999879999800008000180002800038000480005800068000780008800098001080011800128001380014800158001680017800188001980020800218002280023800248002580026800278002880029800308003180032800338003480035800368003780038800398004080041800428004380044800458004680047800488004980050800518005280053800548005580056800578005880059800608006180062800638006480065800668006780068800698007080071800728007380074800758007680077800788007980080800818008280083800848008580086800878008880089800908009180092800938009480095800968009780098800998010080101801028010380104801058010680107801088010980110801118011280113801148011580116801178011880119801208012180122801238012480125801268012780128801298013080131801328013380134801358013680137801388013980140801418014280143801448014580146801478014880149801508015180152801538015480155801568015780158801598016080161801628016380164801658016680167801688016980170801718017280173801748017580176801778017880179801808018180182801838018480185801868018780188801898019080191801928019380194801958019680197801988019980200802018020280203802048020580206802078020880209802108021180212802138021480215802168021780218802198022080221802228022380224802258022680227802288022980230802318023280233802348023580236802378023880239802408024180242802438024480245802468024780248802498025080251802528025380254802558025680257802588025980260802618026280263802648026580266802678026880269802708027180272802738027480275802768027780278802798028080281802828028380284802858028680287802888028980290802918029280293802948029580296802978029880299803008030180302803038030480305803068030780308803098031080311803128031380314803158031680317803188031980320803218032280323803248032580326803278032880329803308033180332803338033480335803368033780338803398034080341803428034380344803458034680347803488034980350803518035280353803548035580356803578035880359803608036180362803638036480365803668036780368803698037080371803728037380374803758037680377803788037980380803818038280383803848038580386803878038880389803908039180392803938039480395803968039780398803998040080401804028040380404804058040680407804088040980410804118041280413804148041580416804178041880419804208042180422804238042480425804268042780428804298043080431804328043380434804358043680437804388043980440804418044280443804448044580446804478044880449804508045180452804538045480455804568045780458804598046080461804628046380464804658046680467804688046980470804718047280473804748047580476804778047880479804808048180482804838048480485804868048780488804898049080491804928049380494804958049680497804988049980500805018050280503805048050580506805078050880509805108051180512805138051480515805168051780518805198052080521805228052380524805258052680527805288052980530805318053280533805348053580536805378053880539805408054180542805438054480545805468054780548805498055080551805528055380554805558055680557805588055980560805618056280563805648056580566805678056880569805708057180572805738057480575805768057780578805798058080581805828058380584805858058680587805888058980590805918059280593805948059580596805978059880599806008060180602806038060480605806068060780608806098061080611806128061380614806158061680617806188061980620806218062280623806248062580626806278062880629806308063180632806338063480635806368063780638806398064080641806428064380644806458064680647806488064980650806518065280653806548065580656806578065880659806608066180662806638066480665806668066780668806698067080671806728067380674806758067680677806788067980680806818068280683806848068580686806878068880689806908069180692806938069480695806968069780698806998070080701807028070380704807058070680707807088070980710807118071280713807148071580716807178071880719807208072180722807238072480725807268072780728807298073080731807328073380734807358073680737807388073980740807418074280743807448074580746807478074880749807508075180752807538075480755807568075780758807598076080761807628076380764807658076680767807688076980770807718077280773807748077580776807778077880779807808078180782807838078480785807868078780788807898079080791807928079380794807958079680797807988079980800808018080280803808048080580806808078080880809808108081180812808138081480815808168081780818808198082080821808228082380824808258082680827808288082980830808318083280833808348083580836808378083880839808408084180842808438084480845808468084780848808498085080851808528085380854808558085680857808588085980860808618086280863808648086580866808678086880869808708087180872808738087480875808768087780878808798088080881808828088380884808858088680887808888088980890808918089280893808948089580896808978089880899809008090180902809038090480905809068090780908809098091080911809128091380914809158091680917809188091980920809218092280923809248092580926809278092880929809308093180932809338093480935809368093780938809398094080941809428094380944809458094680947809488094980950809518095280953809548095580956809578095880959809608096180962809638096480965809668096780968809698097080971809728097380974809758097680977809788097980980809818098280983809848098580986809878098880989809908099180992809938099480995809968099780998809998100081001810028100381004810058100681007810088100981010810118101281013810148101581016810178101881019810208102181022810238102481025810268102781028810298103081031810328103381034810358103681037810388103981040810418104281043810448104581046810478104881049810508105181052810538105481055810568105781058810598106081061810628106381064810658106681067810688106981070810718107281073810748107581076810778107881079810808108181082810838108481085810868108781088810898109081091810928109381094810958109681097810988109981100811018110281103811048110581106811078110881109811108111181112811138111481115811168111781118811198112081121811228112381124811258112681127811288112981130811318113281133811348113581136811378113881139811408114181142811438114481145811468114781148811498115081151811528115381154811558115681157811588115981160811618116281163811648116581166811678116881169811708117181172811738117481175811768117781178811798118081181811828118381184811858118681187811888118981190811918119281193811948119581196811978119881199812008120181202812038120481205812068120781208812098121081211812128121381214812158121681217812188121981220812218122281223812248122581226812278122881229812308123181232812338123481235812368123781238812398124081241812428124381244812458124681247812488124981250812518125281253812548125581256812578125881259812608126181262812638126481265812668126781268812698127081271812728127381274812758127681277812788127981280812818128281283812848128581286812878128881289812908129181292812938129481295812968129781298812998130081301813028130381304813058130681307813088130981310813118131281313813148131581316813178131881319813208132181322813238132481325813268132781328813298133081331813328133381334813358133681337813388133981340813418134281343813448134581346813478134881349813508135181352813538135481355813568135781358813598136081361813628136381364813658136681367813688136981370813718137281373813748137581376813778137881379813808138181382813838138481385813868138781388813898139081391813928139381394813958139681397813988139981400814018140281403814048140581406814078140881409814108141181412814138141481415814168141781418814198142081421814228142381424814258142681427814288142981430814318143281433814348143581436814378143881439814408144181442814438144481445814468144781448814498145081451814528145381454814558145681457814588145981460814618146281463814648146581466814678146881469814708147181472814738147481475814768147781478814798148081481814828148381484814858148681487814888148981490814918149281493814948149581496814978149881499815008150181502815038150481505815068150781508815098151081511815128151381514815158151681517815188151981520815218152281523815248152581526815278152881529815308153181532815338153481535815368153781538815398154081541815428154381544815458154681547815488154981550815518155281553815548155581556815578155881559815608156181562815638156481565815668156781568815698157081571815728157381574815758157681577815788157981580815818158281583815848158581586815878158881589815908159181592815938159481595815968159781598815998160081601816028160381604816058160681607816088160981610816118161281613816148161581616816178161881619816208162181622816238162481625816268162781628816298163081631816328163381634816358163681637816388163981640816418164281643816448164581646816478164881649816508165181652816538165481655816568165781658816598166081661816628166381664816658166681667816688166981670816718167281673816748167581676816778167881679816808168181682816838168481685816868168781688816898169081691816928169381694816958169681697816988169981700817018170281703817048170581706817078170881709817108171181712817138171481715817168171781718817198172081721817228172381724817258172681727817288172981730817318173281733817348173581736817378173881739817408174181742817438174481745817468174781748817498175081751817528175381754817558175681757817588175981760817618176281763817648176581766817678176881769817708177181772817738177481775817768177781778817798178081781817828178381784817858178681787817888178981790817918179281793817948179581796817978179881799818008180181802818038180481805818068180781808818098181081811818128181381814818158181681817818188181981820818218182281823818248182581826818278182881829818308183181832818338183481835818368183781838818398184081841818428184381844818458184681847818488184981850818518185281853818548185581856818578185881859818608186181862818638186481865818668186781868818698187081871818728187381874818758187681877818788187981880818818188281883818848188581886818878188881889818908189181892818938189481895818968189781898818998190081901819028190381904819058190681907819088190981910819118191281913819148191581916819178191881919819208192181922819238192481925819268192781928819298193081931819328193381934819358193681937819388193981940819418194281943819448194581946819478194881949819508195181952819538195481955819568195781958819598196081961819628196381964819658196681967819688196981970819718197281973819748197581976819778197881979819808198181982819838198481985819868198781988819898199081991819928199381994819958199681997819988199982000820018200282003820048200582006820078200882009820108201182012820138201482015820168201782018820198202082021820228202382024820258202682027820288202982030820318203282033820348203582036820378203882039820408204182042820438204482045820468204782048820498205082051820528205382054820558205682057820588205982060820618206282063820648206582066820678206882069820708207182072820738207482075820768207782078820798208082081820828208382084820858208682087820888208982090820918209282093820948209582096820978209882099821008210182102821038210482105821068210782108821098211082111821128211382114821158211682117821188211982120821218212282123821248212582126821278212882129821308213182132821338213482135821368213782138821398214082141821428214382144821458214682147821488214982150821518215282153821548215582156821578215882159821608216182162821638216482165821668216782168821698217082171821728217382174821758217682177821788217982180821818218282183821848218582186821878218882189821908219182192821938219482195821968219782198821998220082201822028220382204822058220682207822088220982210822118221282213822148221582216822178221882219822208222182222822238222482225822268222782228822298223082231822328223382234822358223682237822388223982240822418224282243822448224582246822478224882249822508225182252822538225482255822568225782258822598226082261822628226382264822658226682267822688226982270822718227282273822748227582276822778227882279822808228182282822838228482285822868228782288822898229082291822928229382294822958229682297822988229982300823018230282303823048230582306823078230882309823108231182312823138231482315823168231782318823198232082321823228232382324823258232682327823288232982330823318233282333823348233582336823378233882339823408234182342823438234482345823468234782348823498235082351823528235382354823558235682357823588235982360823618236282363823648236582366823678236882369823708237182372823738237482375823768237782378823798238082381823828238382384823858238682387823888238982390823918239282393823948239582396823978239882399824008240182402824038240482405824068240782408824098241082411824128241382414824158241682417824188241982420824218242282423824248242582426824278242882429824308243182432824338243482435824368243782438824398244082441824428244382444824458244682447824488244982450824518245282453824548245582456824578245882459824608246182462824638246482465824668246782468824698247082471824728247382474824758247682477824788247982480824818248282483824848248582486824878248882489824908249182492824938249482495824968249782498824998250082501825028250382504825058250682507825088250982510825118251282513825148251582516825178251882519825208252182522825238252482525825268252782528825298253082531825328253382534825358253682537825388253982540825418254282543825448254582546825478254882549825508255182552825538255482555825568255782558825598256082561825628256382564825658256682567825688256982570825718257282573825748257582576825778257882579825808258182582825838258482585825868258782588825898259082591825928259382594825958259682597825988259982600826018260282603826048260582606826078260882609826108261182612826138261482615826168261782618826198262082621826228262382624826258262682627826288262982630826318263282633826348263582636826378263882639826408264182642826438264482645826468264782648826498265082651826528265382654826558265682657826588265982660826618266282663826648266582666826678266882669826708267182672826738267482675826768267782678826798268082681826828268382684826858268682687826888268982690826918269282693826948269582696826978269882699827008270182702827038270482705827068270782708827098271082711827128271382714827158271682717827188271982720827218272282723827248272582726827278272882729827308273182732827338273482735827368273782738827398274082741827428274382744827458274682747827488274982750827518275282753827548275582756827578275882759827608276182762827638276482765827668276782768827698277082771827728277382774827758277682777827788277982780827818278282783827848278582786827878278882789827908279182792827938279482795827968279782798827998280082801828028280382804828058280682807828088280982810828118281282813828148281582816828178281882819828208282182822828238282482825828268282782828828298283082831828328283382834828358283682837828388283982840828418284282843828448284582846828478284882849828508285182852828538285482855828568285782858828598286082861828628286382864828658286682867828688286982870828718287282873828748287582876828778287882879828808288182882828838288482885828868288782888828898289082891828928289382894828958289682897828988289982900829018290282903829048290582906829078290882909829108291182912829138291482915829168291782918829198292082921829228292382924829258292682927829288292982930829318293282933829348293582936829378293882939829408294182942829438294482945829468294782948829498295082951829528295382954829558295682957829588295982960829618296282963829648296582966829678296882969829708297182972829738297482975829768297782978829798298082981829828298382984829858298682987829888298982990829918299282993829948299582996829978299882999830008300183002830038300483005830068300783008830098301083011830128301383014830158301683017830188301983020830218302283023830248302583026830278302883029830308303183032830338303483035830368303783038830398304083041830428304383044830458304683047830488304983050830518305283053830548305583056830578305883059830608306183062830638306483065830668306783068830698307083071830728307383074830758307683077830788307983080830818308283083830848308583086830878308883089830908309183092830938309483095830968309783098830998310083101831028310383104831058310683107831088310983110831118311283113831148311583116831178311883119831208312183122831238312483125831268312783128831298313083131831328313383134831358313683137831388313983140831418314283143831448314583146831478314883149831508315183152831538315483155831568315783158831598316083161831628316383164831658316683167831688316983170831718317283173831748317583176831778317883179831808318183182831838318483185831868318783188831898319083191831928319383194831958319683197831988319983200832018320283203832048320583206832078320883209832108321183212832138321483215832168321783218832198322083221832228322383224832258322683227832288322983230832318323283233832348323583236832378323883239832408324183242832438324483245832468324783248832498325083251832528325383254832558325683257832588325983260832618326283263832648326583266832678326883269832708327183272832738327483275832768327783278832798328083281832828328383284832858328683287832888328983290832918329283293832948329583296832978329883299833008330183302833038330483305833068330783308833098331083311833128331383314833158331683317833188331983320833218332283323833248332583326833278332883329833308333183332833338333483335833368333783338833398334083341833428334383344833458334683347833488334983350833518335283353833548335583356833578335883359833608336183362833638336483365833668336783368833698337083371833728337383374833758337683377833788337983380833818338283383833848338583386833878338883389833908339183392833938339483395833968339783398833998340083401834028340383404834058340683407834088340983410834118341283413834148341583416834178341883419834208342183422834238342483425834268342783428834298343083431834328343383434834358343683437834388343983440834418344283443834448344583446834478344883449834508345183452834538345483455834568345783458834598346083461834628346383464834658346683467834688346983470834718347283473834748347583476834778347883479834808348183482834838348483485834868348783488834898349083491834928349383494834958349683497834988349983500835018350283503835048350583506835078350883509835108351183512835138351483515835168351783518835198352083521835228352383524835258352683527835288352983530835318353283533835348353583536835378353883539835408354183542835438354483545835468354783548835498355083551835528355383554835558355683557835588355983560835618356283563835648356583566835678356883569835708357183572835738357483575835768357783578835798358083581835828358383584835858358683587835888358983590835918359283593835948359583596835978359883599836008360183602836038360483605836068360783608836098361083611836128361383614836158361683617836188361983620836218362283623836248362583626836278362883629836308363183632836338363483635836368363783638836398364083641836428364383644836458364683647836488364983650836518365283653836548365583656836578365883659836608366183662836638366483665836668366783668836698367083671836728367383674836758367683677836788367983680836818368283683836848368583686836878368883689836908369183692836938369483695836968369783698836998370083701837028370383704837058370683707837088370983710837118371283713837148371583716837178371883719837208372183722837238372483725837268372783728837298373083731837328373383734837358373683737837388373983740837418374283743837448374583746837478374883749837508375183752837538375483755837568375783758837598376083761837628376383764837658376683767837688376983770837718377283773837748377583776837778377883779837808378183782837838378483785837868378783788837898379083791837928379383794837958379683797837988379983800838018380283803838048380583806838078380883809838108381183812838138381483815838168381783818838198382083821838228382383824838258382683827838288382983830838318383283833838348383583836838378383883839838408384183842838438384483845838468384783848838498385083851838528385383854838558385683857838588385983860838618386283863838648386583866838678386883869838708387183872838738387483875838768387783878838798388083881838828388383884838858388683887838888388983890838918389283893838948389583896838978389883899839008390183902839038390483905839068390783908839098391083911839128391383914839158391683917839188391983920839218392283923839248392583926839278392883929839308393183932839338393483935839368393783938839398394083941839428394383944839458394683947839488394983950839518395283953839548395583956839578395883959839608396183962839638396483965839668396783968839698397083971839728397383974839758397683977839788397983980839818398283983839848398583986839878398883989839908399183992839938399483995839968399783998839998400084001840028400384004840058400684007840088400984010840118401284013840148401584016840178401884019840208402184022840238402484025840268402784028840298403084031840328403384034840358403684037840388403984040840418404284043840448404584046840478404884049840508405184052840538405484055840568405784058840598406084061840628406384064840658406684067840688406984070840718407284073840748407584076840778407884079840808408184082840838408484085840868408784088840898409084091840928409384094840958409684097840988409984100841018410284103841048410584106841078410884109841108411184112841138411484115841168411784118841198412084121841228412384124841258412684127841288412984130841318413284133841348413584136841378413884139841408414184142841438414484145841468414784148841498415084151841528415384154841558415684157841588415984160841618416284163841648416584166841678416884169841708417184172841738417484175841768417784178841798418084181841828418384184841858418684187841888418984190841918419284193841948419584196841978419884199842008420184202842038420484205842068420784208842098421084211842128421384214842158421684217842188421984220842218422284223842248422584226842278422884229842308423184232842338423484235842368423784238842398424084241842428424384244842458424684247842488424984250842518425284253842548425584256842578425884259842608426184262842638426484265842668426784268842698427084271842728427384274842758427684277842788427984280842818428284283842848428584286842878428884289842908429184292842938429484295842968429784298842998430084301843028430384304843058430684307843088430984310843118431284313843148431584316843178431884319843208432184322843238432484325843268432784328843298433084331843328433384334843358433684337843388433984340843418434284343843448434584346843478434884349843508435184352843538435484355843568435784358843598436084361843628436384364843658436684367843688436984370843718437284373843748437584376843778437884379843808438184382843838438484385843868438784388843898439084391843928439384394843958439684397843988439984400844018440284403844048440584406844078440884409844108441184412844138441484415844168441784418844198442084421844228442384424844258442684427844288442984430844318443284433844348443584436844378443884439844408444184442844438444484445844468444784448844498445084451844528445384454844558445684457844588445984460844618446284463844648446584466844678446884469844708447184472844738447484475844768447784478844798448084481844828448384484844858448684487844888448984490844918449284493844948449584496844978449884499845008450184502845038450484505845068450784508845098451084511845128451384514845158451684517845188451984520845218452284523845248452584526845278452884529845308453184532845338453484535845368453784538845398454084541845428454384544845458454684547845488454984550845518455284553845548455584556845578455884559845608456184562845638456484565845668456784568845698457084571845728457384574845758457684577845788457984580845818458284583845848458584586845878458884589845908459184592845938459484595845968459784598845998460084601846028460384604846058460684607846088460984610846118461284613846148461584616846178461884619846208462184622846238462484625846268462784628846298463084631846328463384634846358463684637846388463984640846418464284643846448464584646846478464884649846508465184652846538465484655846568465784658846598466084661846628466384664846658466684667846688466984670846718467284673846748467584676846778467884679846808468184682846838468484685846868468784688846898469084691846928469384694846958469684697846988469984700847018470284703847048470584706847078470884709847108471184712847138471484715847168471784718847198472084721847228472384724847258472684727847288472984730847318473284733847348473584736847378473884739847408474184742847438474484745847468474784748847498475084751847528475384754847558475684757847588475984760847618476284763847648476584766847678476884769847708477184772847738477484775847768477784778847798478084781847828478384784847858478684787847888478984790847918479284793847948479584796847978479884799848008480184802848038480484805848068480784808848098481084811848128481384814848158481684817848188481984820848218482284823848248482584826848278482884829848308483184832848338483484835848368483784838848398484084841848428484384844848458484684847848488484984850848518485284853848548485584856848578485884859848608486184862848638486484865848668486784868848698487084871848728487384874848758487684877848788487984880848818488284883848848488584886848878488884889848908489184892848938489484895848968489784898848998490084901849028490384904849058490684907849088490984910849118491284913849148491584916849178491884919849208492184922849238492484925849268492784928849298493084931849328493384934849358493684937849388493984940849418494284943849448494584946849478494884949849508495184952849538495484955849568495784958849598496084961849628496384964849658496684967849688496984970849718497284973849748497584976849778497884979849808498184982849838498484985849868498784988849898499084991849928499384994849958499684997849988499985000850018500285003850048500585006850078500885009850108501185012850138501485015850168501785018850198502085021850228502385024850258502685027850288502985030850318503285033850348503585036850378503885039850408504185042850438504485045850468504785048850498505085051850528505385054850558505685057850588505985060850618506285063850648506585066850678506885069850708507185072850738507485075850768507785078850798508085081850828508385084850858508685087850888508985090850918509285093850948509585096850978509885099851008510185102851038510485105851068510785108851098511085111851128511385114851158511685117851188511985120851218512285123851248512585126851278512885129851308513185132851338513485135851368513785138851398514085141851428514385144851458514685147851488514985150851518515285153851548515585156851578515885159851608516185162851638516485165851668516785168851698517085171851728517385174851758517685177851788517985180851818518285183851848518585186851878518885189851908519185192851938519485195851968519785198851998520085201852028520385204852058520685207852088520985210852118521285213852148521585216852178521885219852208522185222852238522485225852268522785228852298523085231852328523385234852358523685237852388523985240852418524285243852448524585246852478524885249852508525185252852538525485255852568525785258852598526085261852628526385264852658526685267852688526985270852718527285273852748527585276852778527885279852808528185282852838528485285852868528785288852898529085291852928529385294852958529685297852988529985300853018530285303853048530585306853078530885309853108531185312853138531485315853168531785318853198532085321853228532385324853258532685327853288532985330853318533285333853348533585336853378533885339853408534185342853438534485345853468534785348853498535085351853528535385354853558535685357853588535985360853618536285363853648536585366853678536885369853708537185372853738537485375853768537785378853798538085381853828538385384853858538685387853888538985390853918539285393853948539585396853978539885399854008540185402854038540485405854068540785408854098541085411854128541385414854158541685417854188541985420854218542285423854248542585426854278542885429854308543185432854338543485435854368543785438854398544085441854428544385444854458544685447854488544985450854518545285453854548545585456854578545885459854608546185462854638546485465854668546785468854698547085471854728547385474854758547685477854788547985480854818548285483854848548585486854878548885489854908549185492854938549485495854968549785498854998550085501855028550385504855058550685507855088550985510855118551285513855148551585516855178551885519855208552185522855238552485525855268552785528855298553085531855328553385534855358553685537855388553985540855418554285543855448554585546855478554885549855508555185552855538555485555855568555785558855598556085561855628556385564855658556685567855688556985570855718557285573855748557585576855778557885579855808558185582855838558485585855868558785588855898559085591855928559385594855958559685597855988559985600856018560285603856048560585606856078560885609856108561185612856138561485615856168561785618856198562085621856228562385624856258562685627856288562985630856318563285633856348563585636856378563885639856408564185642856438564485645856468564785648856498565085651856528565385654856558565685657856588565985660856618566285663856648566585666856678566885669856708567185672856738567485675856768567785678856798568085681856828568385684856858568685687856888568985690856918569285693856948569585696856978569885699857008570185702857038570485705857068570785708857098571085711857128571385714857158571685717857188571985720857218572285723857248572585726857278572885729857308573185732857338573485735857368573785738857398574085741857428574385744857458574685747857488574985750857518575285753857548575585756857578575885759857608576185762857638576485765857668576785768857698577085771857728577385774857758577685777857788577985780857818578285783857848578585786857878578885789857908579185792857938579485795857968579785798857998580085801858028580385804858058580685807858088580985810858118581285813858148581585816858178581885819858208582185822858238582485825858268582785828858298583085831858328583385834858358583685837858388583985840858418584285843858448584585846858478584885849858508585185852858538585485855858568585785858858598586085861858628586385864858658586685867858688586985870858718587285873858748587585876858778587885879858808588185882858838588485885858868588785888858898589085891858928589385894858958589685897858988589985900859018590285903859048590585906859078590885909859108591185912859138591485915859168591785918859198592085921859228592385924859258592685927859288592985930859318593285933859348593585936859378593885939859408594185942859438594485945859468594785948859498595085951859528595385954859558595685957859588595985960859618596285963859648596585966859678596885969859708597185972859738597485975859768597785978859798598085981859828598385984859858598685987859888598985990859918599285993859948599585996859978599885999860008600186002860038600486005860068600786008860098601086011860128601386014860158601686017860188601986020860218602286023860248602586026860278602886029860308603186032860338603486035860368603786038860398604086041860428604386044860458604686047860488604986050860518605286053860548605586056860578605886059860608606186062860638606486065860668606786068860698607086071860728607386074860758607686077860788607986080860818608286083860848608586086860878608886089860908609186092860938609486095860968609786098860998610086101861028610386104861058610686107861088610986110861118611286113861148611586116861178611886119861208612186122861238612486125861268612786128861298613086131861328613386134861358613686137861388613986140861418614286143861448614586146861478614886149861508615186152861538615486155861568615786158861598616086161861628616386164861658616686167861688616986170861718617286173861748617586176861778617886179861808618186182861838618486185861868618786188861898619086191861928619386194861958619686197861988619986200862018620286203862048620586206862078620886209862108621186212862138621486215862168621786218862198622086221862228622386224862258622686227862288622986230862318623286233862348623586236862378623886239862408624186242862438624486245862468624786248862498625086251862528625386254862558625686257862588625986260862618626286263862648626586266862678626886269862708627186272862738627486275862768627786278862798628086281862828628386284862858628686287862888628986290862918629286293862948629586296862978629886299863008630186302863038630486305863068630786308863098631086311863128631386314863158631686317863188631986320863218632286323863248632586326863278632886329863308633186332863338633486335863368633786338863398634086341863428634386344863458634686347863488634986350863518635286353863548635586356863578635886359863608636186362863638636486365863668636786368863698637086371863728637386374863758637686377863788637986380863818638286383863848638586386863878638886389863908639186392863938639486395863968639786398863998640086401864028640386404864058640686407864088640986410864118641286413864148641586416864178641886419864208642186422864238642486425864268642786428864298643086431864328643386434864358643686437864388643986440864418644286443864448644586446864478644886449864508645186452864538645486455864568645786458864598646086461864628646386464864658646686467864688646986470864718647286473864748647586476864778647886479864808648186482864838648486485864868648786488864898649086491864928649386494864958649686497864988649986500865018650286503865048650586506865078650886509865108651186512865138651486515865168651786518865198652086521865228652386524865258652686527865288652986530865318653286533865348653586536865378653886539865408654186542865438654486545865468654786548865498655086551865528655386554865558655686557865588655986560865618656286563865648656586566865678656886569865708657186572865738657486575865768657786578865798658086581865828658386584865858658686587865888658986590865918659286593865948659586596865978659886599866008660186602866038660486605866068660786608866098661086611866128661386614866158661686617866188661986620866218662286623866248662586626866278662886629866308663186632866338663486635866368663786638866398664086641866428664386644866458664686647866488664986650866518665286653866548665586656866578665886659866608666186662866638666486665866668666786668866698667086671866728667386674866758667686677866788667986680866818668286683866848668586686866878668886689866908669186692866938669486695866968669786698866998670086701867028670386704867058670686707867088670986710867118671286713867148671586716867178671886719867208672186722867238672486725867268672786728867298673086731867328673386734867358673686737867388673986740867418674286743867448674586746867478674886749867508675186752867538675486755867568675786758867598676086761867628676386764867658676686767867688676986770867718677286773867748677586776867778677886779867808678186782867838678486785867868678786788867898679086791867928679386794867958679686797867988679986800868018680286803868048680586806868078680886809868108681186812868138681486815868168681786818868198682086821868228682386824868258682686827868288682986830868318683286833868348683586836868378683886839868408684186842868438684486845868468684786848868498685086851868528685386854868558685686857868588685986860868618686286863868648686586866868678686886869868708687186872868738687486875868768687786878868798688086881868828688386884868858688686887868888688986890868918689286893868948689586896868978689886899869008690186902869038690486905869068690786908869098691086911869128691386914869158691686917869188691986920869218692286923869248692586926869278692886929869308693186932869338693486935869368693786938869398694086941869428694386944869458694686947869488694986950869518695286953869548695586956869578695886959869608696186962869638696486965869668696786968869698697086971869728697386974869758697686977869788697986980869818698286983869848698586986869878698886989869908699186992869938699486995869968699786998869998700087001870028700387004870058700687007870088700987010870118701287013870148701587016870178701887019870208702187022870238702487025870268702787028870298703087031870328703387034870358703687037870388703987040870418704287043870448704587046870478704887049870508705187052870538705487055870568705787058870598706087061870628706387064870658706687067870688706987070870718707287073870748707587076870778707887079870808708187082870838708487085870868708787088870898709087091870928709387094870958709687097870988709987100871018710287103871048710587106871078710887109871108711187112871138711487115871168711787118871198712087121871228712387124871258712687127871288712987130871318713287133871348713587136871378713887139871408714187142871438714487145871468714787148871498715087151871528715387154871558715687157871588715987160871618716287163871648716587166871678716887169871708717187172871738717487175871768717787178871798718087181871828718387184871858718687187871888718987190871918719287193871948719587196871978719887199872008720187202872038720487205872068720787208872098721087211872128721387214872158721687217872188721987220872218722287223872248722587226872278722887229872308723187232872338723487235872368723787238872398724087241872428724387244872458724687247872488724987250872518725287253872548725587256872578725887259872608726187262872638726487265872668726787268872698727087271872728727387274872758727687277872788727987280872818728287283872848728587286872878728887289872908729187292872938729487295872968729787298872998730087301873028730387304873058730687307873088730987310873118731287313873148731587316873178731887319873208732187322873238732487325873268732787328873298733087331873328733387334873358733687337873388733987340873418734287343873448734587346873478734887349873508735187352873538735487355873568735787358873598736087361873628736387364873658736687367873688736987370873718737287373873748737587376873778737887379873808738187382873838738487385873868738787388873898739087391873928739387394873958739687397873988739987400874018740287403874048740587406874078740887409874108741187412874138741487415874168741787418874198742087421874228742387424874258742687427874288742987430874318743287433874348743587436874378743887439874408744187442874438744487445874468744787448874498745087451874528745387454874558745687457874588745987460874618746287463874648746587466874678746887469874708747187472874738747487475874768747787478874798748087481874828748387484874858748687487874888748987490874918749287493874948749587496874978749887499875008750187502875038750487505875068750787508875098751087511875128751387514875158751687517875188751987520875218752287523875248752587526875278752887529875308753187532875338753487535875368753787538875398754087541875428754387544875458754687547875488754987550875518755287553875548755587556875578755887559875608756187562875638756487565875668756787568875698757087571875728757387574875758757687577875788757987580875818758287583875848758587586875878758887589875908759187592875938759487595875968759787598875998760087601876028760387604876058760687607876088760987610876118761287613876148761587616876178761887619876208762187622876238762487625876268762787628876298763087631876328763387634876358763687637876388763987640876418764287643876448764587646876478764887649876508765187652876538765487655876568765787658876598766087661876628766387664876658766687667876688766987670876718767287673876748767587676876778767887679876808768187682876838768487685876868768787688876898769087691876928769387694876958769687697876988769987700877018770287703877048770587706877078770887709877108771187712877138771487715877168771787718877198772087721877228772387724877258772687727877288772987730877318773287733877348773587736877378773887739877408774187742877438774487745877468774787748877498775087751877528775387754877558775687757877588775987760877618776287763877648776587766877678776887769877708777187772877738777487775877768777787778877798778087781877828778387784877858778687787877888778987790877918779287793877948779587796877978779887799878008780187802878038780487805878068780787808878098781087811878128781387814878158781687817878188781987820878218782287823878248782587826878278782887829878308783187832878338783487835878368783787838878398784087841878428784387844878458784687847878488784987850878518785287853878548785587856878578785887859878608786187862878638786487865878668786787868878698787087871878728787387874878758787687877878788787987880878818788287883878848788587886878878788887889878908789187892878938789487895878968789787898878998790087901879028790387904879058790687907879088790987910879118791287913879148791587916879178791887919879208792187922879238792487925879268792787928879298793087931879328793387934879358793687937879388793987940879418794287943879448794587946879478794887949879508795187952879538795487955879568795787958879598796087961879628796387964879658796687967879688796987970879718797287973879748797587976879778797887979879808798187982879838798487985879868798787988879898799087991879928799387994879958799687997879988799988000880018800288003880048800588006880078800888009880108801188012880138801488015880168801788018880198802088021880228802388024880258802688027880288802988030880318803288033880348803588036880378803888039880408804188042880438804488045880468804788048880498805088051880528805388054880558805688057880588805988060880618806288063880648806588066880678806888069880708807188072880738807488075880768807788078880798808088081880828808388084880858808688087880888808988090880918809288093880948809588096880978809888099881008810188102881038810488105881068810788108881098811088111881128811388114881158811688117881188811988120881218812288123881248812588126881278812888129881308813188132881338813488135881368813788138881398814088141881428814388144881458814688147881488814988150881518815288153881548815588156881578815888159881608816188162881638816488165881668816788168881698817088171881728817388174881758817688177881788817988180881818818288183881848818588186881878818888189881908819188192881938819488195881968819788198881998820088201882028820388204882058820688207882088820988210882118821288213882148821588216882178821888219882208822188222882238822488225882268822788228882298823088231882328823388234882358823688237882388823988240882418824288243882448824588246882478824888249882508825188252882538825488255882568825788258882598826088261882628826388264882658826688267882688826988270882718827288273882748827588276882778827888279882808828188282882838828488285882868828788288882898829088291882928829388294882958829688297882988829988300883018830288303883048830588306883078830888309883108831188312883138831488315883168831788318883198832088321883228832388324883258832688327883288832988330883318833288333883348833588336883378833888339883408834188342883438834488345883468834788348883498835088351883528835388354883558835688357883588835988360883618836288363883648836588366883678836888369883708837188372883738837488375883768837788378883798838088381883828838388384883858838688387883888838988390883918839288393883948839588396883978839888399884008840188402884038840488405884068840788408884098841088411884128841388414884158841688417884188841988420884218842288423884248842588426884278842888429884308843188432884338843488435884368843788438884398844088441884428844388444884458844688447884488844988450884518845288453884548845588456884578845888459884608846188462884638846488465884668846788468884698847088471884728847388474884758847688477884788847988480884818848288483884848848588486884878848888489884908849188492884938849488495884968849788498884998850088501885028850388504885058850688507885088850988510885118851288513885148851588516885178851888519885208852188522885238852488525885268852788528885298853088531885328853388534885358853688537885388853988540885418854288543885448854588546885478854888549885508855188552885538855488555885568855788558885598856088561885628856388564885658856688567885688856988570885718857288573885748857588576885778857888579885808858188582885838858488585885868858788588885898859088591885928859388594885958859688597885988859988600886018860288603886048860588606886078860888609886108861188612886138861488615886168861788618886198862088621886228862388624886258862688627886288862988630886318863288633886348863588636886378863888639886408864188642886438864488645886468864788648886498865088651886528865388654886558865688657886588865988660886618866288663886648866588666886678866888669886708867188672886738867488675886768867788678886798868088681886828868388684886858868688687886888868988690886918869288693886948869588696886978869888699887008870188702887038870488705887068870788708887098871088711887128871388714887158871688717887188871988720887218872288723887248872588726887278872888729887308873188732887338873488735887368873788738887398874088741887428874388744887458874688747887488874988750887518875288753887548875588756887578875888759887608876188762887638876488765887668876788768887698877088771887728877388774887758877688777887788877988780887818878288783887848878588786887878878888789887908879188792887938879488795887968879788798887998880088801888028880388804888058880688807888088880988810888118881288813888148881588816888178881888819888208882188822888238882488825888268882788828888298883088831888328883388834888358883688837888388883988840888418884288843888448884588846888478884888849888508885188852888538885488855888568885788858888598886088861888628886388864888658886688867888688886988870888718887288873888748887588876888778887888879888808888188882888838888488885888868888788888888898889088891888928889388894888958889688897888988889988900889018890288903889048890588906889078890888909889108891188912889138891488915889168891788918889198892088921889228892388924889258892688927889288892988930889318893288933889348893588936889378893888939889408894188942889438894488945889468894788948889498895088951889528895388954889558895688957889588895988960889618896288963889648896588966889678896888969889708897188972889738897488975889768897788978889798898088981889828898388984889858898688987889888898988990889918899288993889948899588996889978899888999890008900189002890038900489005890068900789008890098901089011890128901389014890158901689017890188901989020890218902289023890248902589026890278902889029890308903189032890338903489035890368903789038890398904089041890428904389044890458904689047890488904989050890518905289053890548905589056890578905889059890608906189062890638906489065890668906789068890698907089071890728907389074890758907689077890788907989080890818908289083890848908589086890878908889089890908909189092890938909489095890968909789098890998910089101891028910389104891058910689107891088910989110891118911289113891148911589116891178911889119891208912189122891238912489125891268912789128891298913089131891328913389134891358913689137891388913989140891418914289143891448914589146891478914889149891508915189152891538915489155891568915789158891598916089161891628916389164891658916689167891688916989170891718917289173891748917589176891778917889179891808918189182891838918489185891868918789188891898919089191891928919389194891958919689197891988919989200892018920289203892048920589206892078920889209892108921189212892138921489215892168921789218892198922089221892228922389224892258922689227892288922989230892318923289233892348923589236892378923889239892408924189242892438924489245892468924789248892498925089251892528925389254892558925689257892588925989260892618926289263892648926589266892678926889269892708927189272892738927489275892768927789278892798928089281892828928389284892858928689287892888928989290892918929289293892948929589296892978929889299893008930189302893038930489305893068930789308893098931089311893128931389314893158931689317893188931989320893218932289323893248932589326893278932889329893308933189332893338933489335893368933789338893398934089341893428934389344893458934689347893488934989350893518935289353893548935589356893578935889359893608936189362893638936489365893668936789368893698937089371893728937389374893758937689377893788937989380893818938289383893848938589386893878938889389893908939189392893938939489395893968939789398893998940089401894028940389404894058940689407894088940989410894118941289413894148941589416894178941889419894208942189422894238942489425894268942789428894298943089431894328943389434894358943689437894388943989440894418944289443894448944589446894478944889449894508945189452894538945489455894568945789458894598946089461894628946389464894658946689467894688946989470894718947289473894748947589476894778947889479894808948189482894838948489485894868948789488894898949089491894928949389494894958949689497894988949989500895018950289503895048950589506895078950889509895108951189512895138951489515895168951789518895198952089521895228952389524895258952689527895288952989530895318953289533895348953589536895378953889539895408954189542895438954489545895468954789548895498955089551895528955389554895558955689557895588955989560895618956289563895648956589566895678956889569895708957189572895738957489575895768957789578895798958089581895828958389584895858958689587895888958989590895918959289593895948959589596895978959889599896008960189602896038960489605896068960789608896098961089611896128961389614896158961689617896188961989620896218962289623896248962589626896278962889629896308963189632896338963489635896368963789638896398964089641896428964389644896458964689647896488964989650896518965289653896548965589656896578965889659896608966189662896638966489665896668966789668896698967089671896728967389674896758967689677896788967989680896818968289683896848968589686896878968889689896908969189692896938969489695896968969789698896998970089701897028970389704897058970689707897088970989710897118971289713897148971589716897178971889719897208972189722897238972489725897268972789728897298973089731897328973389734897358973689737897388973989740897418974289743897448974589746897478974889749897508975189752897538975489755897568975789758897598976089761897628976389764897658976689767897688976989770897718977289773897748977589776897778977889779897808978189782897838978489785897868978789788897898979089791897928979389794897958979689797897988979989800898018980289803898048980589806898078980889809898108981189812898138981489815898168981789818898198982089821898228982389824898258982689827898288982989830898318983289833898348983589836898378983889839898408984189842898438984489845898468984789848898498985089851898528985389854898558985689857898588985989860898618986289863898648986589866898678986889869898708987189872898738987489875898768987789878898798988089881898828988389884898858988689887898888988989890898918989289893898948989589896898978989889899899008990189902899038990489905899068990789908899098991089911899128991389914899158991689917899188991989920899218992289923899248992589926899278992889929899308993189932899338993489935899368993789938899398994089941899428994389944899458994689947899488994989950899518995289953899548995589956899578995889959899608996189962899638996489965899668996789968899698997089971899728997389974899758997689977899788997989980899818998289983899848998589986899878998889989899908999189992899938999489995899968999789998899999000090001900029000390004900059000690007900089000990010900119001290013900149001590016900179001890019900209002190022900239002490025900269002790028900299003090031900329003390034900359003690037900389003990040900419004290043900449004590046900479004890049900509005190052900539005490055900569005790058900599006090061900629006390064900659006690067900689006990070900719007290073900749007590076900779007890079900809008190082900839008490085900869008790088900899009090091900929009390094900959009690097900989009990100901019010290103901049010590106901079010890109901109011190112901139011490115901169011790118901199012090121901229012390124901259012690127901289012990130901319013290133901349013590136901379013890139901409014190142901439014490145901469014790148901499015090151901529015390154901559015690157901589015990160901619016290163901649016590166901679016890169901709017190172901739017490175901769017790178901799018090181901829018390184901859018690187901889018990190901919019290193901949019590196901979019890199902009020190202902039020490205902069020790208902099021090211902129021390214902159021690217902189021990220902219022290223902249022590226902279022890229902309023190232902339023490235902369023790238902399024090241902429024390244902459024690247902489024990250902519025290253902549025590256902579025890259902609026190262902639026490265902669026790268902699027090271902729027390274902759027690277902789027990280902819028290283902849028590286902879028890289902909029190292902939029490295902969029790298902999030090301903029030390304903059030690307903089030990310903119031290313903149031590316903179031890319903209032190322903239032490325903269032790328903299033090331903329033390334903359033690337903389033990340903419034290343903449034590346903479034890349903509035190352903539035490355903569035790358903599036090361903629036390364903659036690367903689036990370903719037290373903749037590376903779037890379903809038190382903839038490385903869038790388903899039090391903929039390394903959039690397903989039990400904019040290403904049040590406904079040890409904109041190412904139041490415904169041790418904199042090421904229042390424904259042690427904289042990430904319043290433904349043590436904379043890439904409044190442904439044490445904469044790448904499045090451904529045390454904559045690457904589045990460904619046290463904649046590466904679046890469904709047190472904739047490475904769047790478904799048090481904829048390484904859048690487904889048990490904919049290493904949049590496904979049890499905009050190502905039050490505905069050790508905099051090511905129051390514905159051690517905189051990520905219052290523905249052590526905279052890529905309053190532905339053490535905369053790538905399054090541905429054390544905459054690547905489054990550905519055290553905549055590556905579055890559905609056190562905639056490565905669056790568905699057090571905729057390574905759057690577905789057990580905819058290583905849058590586905879058890589905909059190592905939059490595905969059790598905999060090601906029060390604906059060690607906089060990610906119061290613906149061590616906179061890619906209062190622906239062490625906269062790628906299063090631906329063390634906359063690637906389063990640906419064290643906449064590646906479064890649906509065190652906539065490655906569065790658906599066090661906629066390664906659066690667906689066990670906719067290673906749067590676906779067890679906809068190682906839068490685906869068790688906899069090691906929069390694906959069690697906989069990700907019070290703907049070590706907079070890709907109071190712907139071490715907169071790718907199072090721907229072390724907259072690727907289072990730907319073290733907349073590736907379073890739907409074190742907439074490745907469074790748907499075090751907529075390754907559075690757907589075990760907619076290763907649076590766907679076890769907709077190772907739077490775907769077790778907799078090781907829078390784907859078690787907889078990790907919079290793907949079590796907979079890799908009080190802908039080490805908069080790808908099081090811908129081390814908159081690817908189081990820908219082290823908249082590826908279082890829908309083190832908339083490835908369083790838908399084090841908429084390844908459084690847908489084990850908519085290853908549085590856908579085890859908609086190862908639086490865908669086790868908699087090871908729087390874908759087690877908789087990880908819088290883908849088590886908879088890889908909089190892908939089490895908969089790898908999090090901909029090390904909059090690907909089090990910909119091290913909149091590916909179091890919909209092190922909239092490925909269092790928909299093090931909329093390934909359093690937909389093990940909419094290943909449094590946909479094890949909509095190952909539095490955909569095790958909599096090961909629096390964909659096690967909689096990970909719097290973909749097590976909779097890979909809098190982909839098490985909869098790988909899099090991909929099390994909959099690997909989099991000910019100291003910049100591006910079100891009910109101191012910139101491015910169101791018910199102091021910229102391024910259102691027910289102991030910319103291033910349103591036910379103891039910409104191042910439104491045910469104791048910499105091051910529105391054910559105691057910589105991060910619106291063910649106591066910679106891069910709107191072910739107491075910769107791078910799108091081910829108391084910859108691087910889108991090910919109291093910949109591096910979109891099911009110191102911039110491105911069110791108911099111091111911129111391114911159111691117911189111991120911219112291123911249112591126911279112891129911309113191132911339113491135911369113791138911399114091141911429114391144911459114691147911489114991150911519115291153911549115591156911579115891159911609116191162911639116491165911669116791168911699117091171911729117391174911759117691177911789117991180911819118291183911849118591186911879118891189911909119191192911939119491195911969119791198911999120091201912029120391204912059120691207912089120991210912119121291213912149121591216912179121891219912209122191222912239122491225912269122791228912299123091231912329123391234912359123691237912389123991240912419124291243912449124591246912479124891249912509125191252912539125491255912569125791258912599126091261912629126391264912659126691267912689126991270912719127291273912749127591276912779127891279912809128191282912839128491285912869128791288912899129091291912929129391294912959129691297912989129991300913019130291303913049130591306913079130891309913109131191312913139131491315913169131791318913199132091321913229132391324913259132691327913289132991330913319133291333913349133591336913379133891339913409134191342913439134491345913469134791348913499135091351913529135391354913559135691357913589135991360913619136291363913649136591366913679136891369913709137191372913739137491375913769137791378913799138091381913829138391384913859138691387913889138991390913919139291393913949139591396913979139891399914009140191402914039140491405914069140791408914099141091411914129141391414914159141691417914189141991420914219142291423914249142591426914279142891429914309143191432914339143491435914369143791438914399144091441914429144391444914459144691447914489144991450914519145291453914549145591456914579145891459914609146191462914639146491465914669146791468914699147091471914729147391474914759147691477914789147991480914819148291483914849148591486914879148891489914909149191492914939149491495914969149791498914999150091501915029150391504915059150691507915089150991510915119151291513915149151591516915179151891519915209152191522915239152491525915269152791528915299153091531915329153391534915359153691537915389153991540915419154291543915449154591546915479154891549915509155191552915539155491555915569155791558915599156091561915629156391564915659156691567915689156991570915719157291573915749157591576915779157891579915809158191582915839158491585915869158791588915899159091591915929159391594915959159691597915989159991600916019160291603916049160591606916079160891609916109161191612916139161491615916169161791618916199162091621916229162391624916259162691627916289162991630916319163291633916349163591636916379163891639916409164191642916439164491645916469164791648916499165091651916529165391654916559165691657916589165991660916619166291663916649166591666916679166891669916709167191672916739167491675916769167791678916799168091681916829168391684916859168691687916889168991690916919169291693916949169591696916979169891699917009170191702917039170491705917069170791708917099171091711917129171391714917159171691717917189171991720917219172291723917249172591726917279172891729917309173191732917339173491735917369173791738917399174091741917429174391744917459174691747917489174991750917519175291753917549175591756917579175891759917609176191762917639176491765917669176791768917699177091771917729177391774917759177691777917789177991780917819178291783917849178591786917879178891789917909179191792917939179491795917969179791798917999180091801918029180391804918059180691807918089180991810918119181291813918149181591816918179181891819918209182191822918239182491825918269182791828918299183091831918329183391834918359183691837918389183991840918419184291843918449184591846918479184891849918509185191852918539185491855918569185791858918599186091861918629186391864918659186691867918689186991870918719187291873918749187591876918779187891879918809188191882918839188491885918869188791888918899189091891918929189391894918959189691897918989189991900919019190291903919049190591906919079190891909919109191191912919139191491915919169191791918919199192091921919229192391924919259192691927919289192991930919319193291933919349193591936919379193891939919409194191942919439194491945919469194791948919499195091951919529195391954919559195691957919589195991960919619196291963919649196591966919679196891969919709197191972919739197491975919769197791978919799198091981919829198391984919859198691987919889198991990919919199291993919949199591996919979199891999920009200192002920039200492005920069200792008920099201092011920129201392014920159201692017920189201992020920219202292023920249202592026920279202892029920309203192032920339203492035920369203792038920399204092041920429204392044920459204692047920489204992050920519205292053920549205592056920579205892059920609206192062920639206492065920669206792068920699207092071920729207392074920759207692077920789207992080920819208292083920849208592086920879208892089920909209192092920939209492095920969209792098920999210092101921029210392104921059210692107921089210992110921119211292113921149211592116921179211892119921209212192122921239212492125921269212792128921299213092131921329213392134921359213692137921389213992140921419214292143921449214592146921479214892149921509215192152921539215492155921569215792158921599216092161921629216392164921659216692167921689216992170921719217292173921749217592176921779217892179921809218192182921839218492185921869218792188921899219092191921929219392194921959219692197921989219992200922019220292203922049220592206922079220892209922109221192212922139221492215922169221792218922199222092221922229222392224922259222692227922289222992230922319223292233922349223592236922379223892239922409224192242922439224492245922469224792248922499225092251922529225392254922559225692257922589225992260922619226292263922649226592266922679226892269922709227192272922739227492275922769227792278922799228092281922829228392284922859228692287922889228992290922919229292293922949229592296922979229892299923009230192302923039230492305923069230792308923099231092311923129231392314923159231692317923189231992320923219232292323923249232592326923279232892329923309233192332923339233492335923369233792338923399234092341923429234392344923459234692347923489234992350923519235292353923549235592356923579235892359923609236192362923639236492365923669236792368923699237092371923729237392374923759237692377923789237992380923819238292383923849238592386923879238892389923909239192392923939239492395923969239792398923999240092401924029240392404924059240692407924089240992410924119241292413924149241592416924179241892419924209242192422924239242492425924269242792428924299243092431924329243392434924359243692437924389243992440924419244292443924449244592446924479244892449924509245192452924539245492455924569245792458924599246092461924629246392464924659246692467924689246992470924719247292473924749247592476924779247892479924809248192482924839248492485924869248792488924899249092491924929249392494924959249692497924989249992500925019250292503925049250592506925079250892509925109251192512925139251492515925169251792518925199252092521925229252392524925259252692527925289252992530925319253292533925349253592536925379253892539925409254192542925439254492545925469254792548925499255092551925529255392554925559255692557925589255992560925619256292563925649256592566925679256892569925709257192572925739257492575925769257792578925799258092581925829258392584925859258692587925889258992590925919259292593925949259592596925979259892599926009260192602926039260492605926069260792608926099261092611926129261392614926159261692617926189261992620926219262292623926249262592626926279262892629926309263192632926339263492635926369263792638926399264092641926429264392644926459264692647926489264992650926519265292653926549265592656926579265892659926609266192662926639266492665926669266792668926699267092671926729267392674926759267692677926789267992680926819268292683926849268592686926879268892689926909269192692926939269492695926969269792698926999270092701927029270392704927059270692707927089270992710927119271292713927149271592716927179271892719927209272192722927239272492725927269272792728927299273092731927329273392734927359273692737927389273992740927419274292743927449274592746927479274892749927509275192752927539275492755927569275792758927599276092761927629276392764927659276692767927689276992770927719277292773927749277592776927779277892779927809278192782927839278492785927869278792788927899279092791927929279392794927959279692797927989279992800928019280292803928049280592806928079280892809928109281192812928139281492815928169281792818928199282092821928229282392824928259282692827928289282992830928319283292833928349283592836928379283892839928409284192842928439284492845928469284792848928499285092851928529285392854928559285692857928589285992860928619286292863928649286592866928679286892869928709287192872928739287492875928769287792878928799288092881928829288392884928859288692887928889288992890928919289292893928949289592896928979289892899929009290192902929039290492905929069290792908929099291092911929129291392914929159291692917929189291992920929219292292923929249292592926929279292892929929309293192932929339293492935929369293792938929399294092941929429294392944929459294692947929489294992950929519295292953929549295592956929579295892959929609296192962929639296492965929669296792968929699297092971929729297392974929759297692977929789297992980
  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 The current define statements for the shader.
  65. * @returns The resulting defines with defines of the current rank removed.
  66. */
  67. EffectFallbacks.prototype.reduce = function (currentDefines) {
  68. // First we try to switch to CPU skinning
  69. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0) {
  70. this._mesh.computeBonesUsingShaders = false;
  71. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  72. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  73. var scene = this._mesh.getScene();
  74. for (var index = 0; index < scene.meshes.length; index++) {
  75. var otherMesh = scene.meshes[index];
  76. if (otherMesh.material === this._mesh.material && otherMesh.computeBonesUsingShaders && otherMesh.numBoneInfluencers > 0) {
  77. otherMesh.computeBonesUsingShaders = false;
  78. }
  79. }
  80. }
  81. else {
  82. var currentFallbacks = this._defines[this._currentRank];
  83. if (currentFallbacks) {
  84. for (var index = 0; index < currentFallbacks.length; index++) {
  85. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  86. }
  87. }
  88. this._currentRank++;
  89. }
  90. return currentDefines;
  91. };
  92. return EffectFallbacks;
  93. }());
  94. BABYLON.EffectFallbacks = EffectFallbacks;
  95. /**
  96. * Options to be used when creating an effect.
  97. */
  98. var EffectCreationOptions = /** @class */ (function () {
  99. function EffectCreationOptions() {
  100. }
  101. return EffectCreationOptions;
  102. }());
  103. BABYLON.EffectCreationOptions = EffectCreationOptions;
  104. /**
  105. * Effect containing vertex and fragment shader that can be executed on an object.
  106. */
  107. var Effect = /** @class */ (function () {
  108. /**
  109. * Instantiates an effect.
  110. * An effect can be used to create/manage/execute vertex and fragment shaders.
  111. * @param baseName Name of the effect.
  112. * @param attributesNamesOrOptions List of attribute names that will be passed to the shader or set of all options to create the effect.
  113. * @param uniformsNamesOrEngine List of uniform variable names that will be passed to the shader or the engine that will be used to render effect.
  114. * @param samplers List of sampler variables that will be passed to the shader.
  115. * @param engine Engine to be used to render the effect
  116. * @param defines Define statements to be added to the shader.
  117. * @param fallbacks Possible fallbacks for this effect to improve performance when needed.
  118. * @param onCompiled Callback that will be called when the shader is compiled.
  119. * @param onError Callback that will be called if an error occurs during shader compilation.
  120. * @param indexParameters Parameters to be used with Babylons include syntax to iterate over an array (eg. {lights: 10})
  121. */
  122. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  123. if (samplers === void 0) { samplers = null; }
  124. if (defines === void 0) { defines = null; }
  125. if (fallbacks === void 0) { fallbacks = null; }
  126. if (onCompiled === void 0) { onCompiled = null; }
  127. if (onError === void 0) { onError = null; }
  128. var _this = this;
  129. /**
  130. * Unique ID of the effect.
  131. */
  132. this.uniqueId = 0;
  133. /**
  134. * Observable that will be called when the shader is compiled.
  135. */
  136. this.onCompileObservable = new BABYLON.Observable();
  137. /**
  138. * Observable that will be called if an error occurs during shader compilation.
  139. */
  140. this.onErrorObservable = new BABYLON.Observable();
  141. /**
  142. * Observable that will be called when effect is bound.
  143. */
  144. this.onBindObservable = new BABYLON.Observable();
  145. this._uniformBuffersNames = {};
  146. this._isReady = false;
  147. this._compilationError = "";
  148. this.name = baseName;
  149. if (attributesNamesOrOptions.attributes) {
  150. var options = attributesNamesOrOptions;
  151. this._engine = uniformsNamesOrEngine;
  152. this._attributesNames = options.attributes;
  153. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  154. this._samplers = options.samplers;
  155. this.defines = options.defines;
  156. this.onError = options.onError;
  157. this.onCompiled = options.onCompiled;
  158. this._fallbacks = options.fallbacks;
  159. this._indexParameters = options.indexParameters;
  160. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  161. if (options.uniformBuffersNames) {
  162. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  163. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  164. }
  165. }
  166. }
  167. else {
  168. this._engine = engine;
  169. this.defines = defines;
  170. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  171. this._samplers = samplers;
  172. this._attributesNames = attributesNamesOrOptions;
  173. this.onError = onError;
  174. this.onCompiled = onCompiled;
  175. this._indexParameters = indexParameters;
  176. this._fallbacks = fallbacks;
  177. }
  178. this.uniqueId = Effect._uniqueIdSeed++;
  179. var vertexSource;
  180. var fragmentSource;
  181. if (baseName.vertexElement) {
  182. vertexSource = document.getElementById(baseName.vertexElement);
  183. if (!vertexSource) {
  184. vertexSource = baseName.vertexElement;
  185. }
  186. }
  187. else {
  188. vertexSource = baseName.vertex || baseName;
  189. }
  190. if (baseName.fragmentElement) {
  191. fragmentSource = document.getElementById(baseName.fragmentElement);
  192. if (!fragmentSource) {
  193. fragmentSource = baseName.fragmentElement;
  194. }
  195. }
  196. else {
  197. fragmentSource = baseName.fragment || baseName;
  198. }
  199. var finalVertexCode;
  200. this._loadVertexShaderAsync(vertexSource)
  201. .then(function (vertexCode) {
  202. return _this._processIncludesAsync(vertexCode);
  203. })
  204. .then(function (vertexCodeWithIncludes) {
  205. finalVertexCode = _this._processShaderConversion(vertexCodeWithIncludes, false);
  206. return _this._loadFragmentShaderAsync(fragmentSource);
  207. })
  208. .then(function (fragmentCode) {
  209. return _this._processIncludesAsync(fragmentCode);
  210. })
  211. .then(function (fragmentCodeWithIncludes) {
  212. var migratedFragmentCode = _this._processShaderConversion(fragmentCodeWithIncludes, true);
  213. if (baseName) {
  214. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  215. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  216. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + finalVertexCode;
  217. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  218. }
  219. else {
  220. _this._vertexSourceCode = finalVertexCode;
  221. _this._fragmentSourceCode = migratedFragmentCode;
  222. }
  223. _this._prepareEffect();
  224. });
  225. }
  226. Object.defineProperty(Effect.prototype, "key", {
  227. /**
  228. * Unique key for this effect
  229. */
  230. get: function () {
  231. return this._key;
  232. },
  233. enumerable: true,
  234. configurable: true
  235. });
  236. /**
  237. * If the effect has been compiled and prepared.
  238. * @returns if the effect is compiled and prepared.
  239. */
  240. Effect.prototype.isReady = function () {
  241. return this._isReady;
  242. };
  243. /**
  244. * The engine the effect was initialized with.
  245. * @returns the engine.
  246. */
  247. Effect.prototype.getEngine = function () {
  248. return this._engine;
  249. };
  250. /**
  251. * The compiled webGL program for the effect
  252. * @returns the webGL program.
  253. */
  254. Effect.prototype.getProgram = function () {
  255. return this._program;
  256. };
  257. /**
  258. * The set of names of attribute variables for the shader.
  259. * @returns An array of attribute names.
  260. */
  261. Effect.prototype.getAttributesNames = function () {
  262. return this._attributesNames;
  263. };
  264. /**
  265. * Returns the attribute at the given index.
  266. * @param index The index of the attribute.
  267. * @returns The location of the attribute.
  268. */
  269. Effect.prototype.getAttributeLocation = function (index) {
  270. return this._attributes[index];
  271. };
  272. /**
  273. * Returns the attribute based on the name of the variable.
  274. * @param name of the attribute to look up.
  275. * @returns the attribute location.
  276. */
  277. Effect.prototype.getAttributeLocationByName = function (name) {
  278. var index = this._attributesNames.indexOf(name);
  279. return this._attributes[index];
  280. };
  281. /**
  282. * The number of attributes.
  283. * @returns the numnber of attributes.
  284. */
  285. Effect.prototype.getAttributesCount = function () {
  286. return this._attributes.length;
  287. };
  288. /**
  289. * Gets the index of a uniform variable.
  290. * @param uniformName of the uniform to look up.
  291. * @returns the index.
  292. */
  293. Effect.prototype.getUniformIndex = function (uniformName) {
  294. return this._uniformsNames.indexOf(uniformName);
  295. };
  296. /**
  297. * Returns the attribute based on the name of the variable.
  298. * @param uniformName of the uniform to look up.
  299. * @returns the location of the uniform.
  300. */
  301. Effect.prototype.getUniform = function (uniformName) {
  302. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  303. };
  304. /**
  305. * Returns an array of sampler variable names
  306. * @returns The array of sampler variable neames.
  307. */
  308. Effect.prototype.getSamplers = function () {
  309. return this._samplers;
  310. };
  311. /**
  312. * The error from the last compilation.
  313. * @returns the error string.
  314. */
  315. Effect.prototype.getCompilationError = function () {
  316. return this._compilationError;
  317. };
  318. /**
  319. * Adds a callback to the onCompiled observable and call the callback imediatly if already ready.
  320. * @param func The callback to be used.
  321. */
  322. Effect.prototype.executeWhenCompiled = function (func) {
  323. if (this.isReady()) {
  324. func(this);
  325. return;
  326. }
  327. this.onCompileObservable.add(function (effect) {
  328. func(effect);
  329. });
  330. };
  331. /** @ignore */
  332. Effect.prototype._loadVertexShaderAsync = function (vertex) {
  333. if (BABYLON.Tools.IsWindowObjectExist()) {
  334. // DOM element ?
  335. if (vertex instanceof HTMLElement) {
  336. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  337. return Promise.resolve(vertexCode);
  338. }
  339. }
  340. // Base64 encoded ?
  341. if (vertex.substr(0, 7) === "base64:") {
  342. var vertexBinary = window.atob(vertex.substr(7));
  343. return Promise.resolve(vertexBinary);
  344. }
  345. // Is in local store ?
  346. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  347. return Promise.resolve(Effect.ShadersStore[vertex + "VertexShader"]);
  348. }
  349. var vertexShaderUrl;
  350. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  351. vertexShaderUrl = vertex;
  352. }
  353. else {
  354. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  355. }
  356. // Vertex shader
  357. return this._engine._loadFileAsync(vertexShaderUrl + ".vertex.fx");
  358. };
  359. /** @ignore */
  360. Effect.prototype._loadFragmentShaderAsync = function (fragment) {
  361. if (BABYLON.Tools.IsWindowObjectExist()) {
  362. // DOM element ?
  363. if (fragment instanceof HTMLElement) {
  364. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  365. return Promise.resolve(fragmentCode);
  366. }
  367. }
  368. // Base64 encoded ?
  369. if (fragment.substr(0, 7) === "base64:") {
  370. var fragmentBinary = window.atob(fragment.substr(7));
  371. return Promise.resolve(fragmentBinary);
  372. }
  373. // Is in local store ?
  374. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  375. return Promise.resolve(Effect.ShadersStore[fragment + "PixelShader"]);
  376. }
  377. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  378. return Promise.resolve(Effect.ShadersStore[fragment + "FragmentShader"]);
  379. }
  380. var fragmentShaderUrl;
  381. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  382. fragmentShaderUrl = fragment;
  383. }
  384. else {
  385. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  386. }
  387. // Fragment shader
  388. return this._engine._loadFileAsync(fragmentShaderUrl + ".fragment.fx");
  389. };
  390. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  391. // Rebuild shaders source code
  392. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n" : "";
  393. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  394. vertexCode = prefix + vertexCode;
  395. fragmentCode = prefix + fragmentCode;
  396. // Number lines of shaders source code
  397. var i = 2;
  398. var regex = /\n/gm;
  399. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  400. i = 2;
  401. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  402. // Dump shaders name and formatted source code
  403. if (this.name.vertexElement) {
  404. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  405. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  406. }
  407. else if (this.name.vertex) {
  408. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  409. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  410. }
  411. else {
  412. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  413. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  414. }
  415. };
  416. ;
  417. Effect.prototype._processShaderConversion = function (sourceCode, isFragment) {
  418. var preparedSourceCode = this._processPrecision(sourceCode);
  419. if (this._engine.webGLVersion == 1) {
  420. return preparedSourceCode;
  421. }
  422. // Already converted
  423. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  424. return preparedSourceCode.replace("#version 300 es", "");
  425. }
  426. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  427. // Remove extensions
  428. // #extension GL_OES_standard_derivatives : enable
  429. // #extension GL_EXT_shader_texture_lod : enable
  430. // #extension GL_EXT_frag_depth : enable
  431. // #extension GL_EXT_draw_buffers : require
  432. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  433. var result = preparedSourceCode.replace(regex, "");
  434. // Migrate to GLSL v300
  435. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  436. result = result.replace(/attribute[ \t]/g, "in ");
  437. result = result.replace(/[ \t]attribute/g, " in");
  438. if (isFragment) {
  439. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  440. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  441. result = result.replace(/texture2D\s*\(/g, "texture(");
  442. result = result.replace(/textureCube\s*\(/g, "texture(");
  443. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  444. result = result.replace(/gl_FragColor/g, "glFragColor");
  445. result = result.replace(/gl_FragData/g, "glFragData");
  446. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  447. }
  448. return result;
  449. };
  450. Effect.prototype._processIncludesAsync = function (sourceCode) {
  451. var _this = this;
  452. return new Promise(function (resolve, reject) {
  453. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  454. var match = regex.exec(sourceCode);
  455. var returnValue = sourceCode;
  456. while (match != null) {
  457. var includeFile = match[1];
  458. // Uniform declaration
  459. if (includeFile.indexOf("__decl__") !== -1) {
  460. includeFile = includeFile.replace(/__decl__/, "");
  461. if (_this._engine.supportsUniformBuffers) {
  462. includeFile = includeFile.replace(/Vertex/, "Ubo");
  463. includeFile = includeFile.replace(/Fragment/, "Ubo");
  464. }
  465. includeFile = includeFile + "Declaration";
  466. }
  467. if (Effect.IncludesShadersStore[includeFile]) {
  468. // Substitution
  469. var includeContent = Effect.IncludesShadersStore[includeFile];
  470. if (match[2]) {
  471. var splits = match[3].split(",");
  472. for (var index = 0; index < splits.length; index += 2) {
  473. var source = new RegExp(splits[index], "g");
  474. var dest = splits[index + 1];
  475. includeContent = includeContent.replace(source, dest);
  476. }
  477. }
  478. if (match[4]) {
  479. var indexString = match[5];
  480. if (indexString.indexOf("..") !== -1) {
  481. var indexSplits = indexString.split("..");
  482. var minIndex = parseInt(indexSplits[0]);
  483. var maxIndex = parseInt(indexSplits[1]);
  484. var sourceIncludeContent = includeContent.slice(0);
  485. includeContent = "";
  486. if (isNaN(maxIndex)) {
  487. maxIndex = _this._indexParameters[indexSplits[1]];
  488. }
  489. for (var i = minIndex; i < maxIndex; i++) {
  490. if (!_this._engine.supportsUniformBuffers) {
  491. // Ubo replacement
  492. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  493. return p1 + "{X}";
  494. });
  495. }
  496. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  497. }
  498. }
  499. else {
  500. if (!_this._engine.supportsUniformBuffers) {
  501. // Ubo replacement
  502. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  503. return p1 + "{X}";
  504. });
  505. }
  506. includeContent = includeContent.replace(/\{X\}/g, indexString);
  507. }
  508. }
  509. // Replace
  510. returnValue = returnValue.replace(match[0], includeContent);
  511. }
  512. else {
  513. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  514. _this._engine._loadFileAsync(includeShaderUrl)
  515. .then(function (fileContent) {
  516. Effect.IncludesShadersStore[includeFile] = fileContent;
  517. return _this._processIncludesAsync(returnValue);
  518. })
  519. .then(function (returnValue) {
  520. resolve(returnValue);
  521. });
  522. return;
  523. }
  524. match = regex.exec(sourceCode);
  525. }
  526. resolve(returnValue);
  527. });
  528. };
  529. Effect.prototype._processPrecision = function (source) {
  530. if (source.indexOf("precision highp float") === -1) {
  531. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  532. source = "precision mediump float;\n" + source;
  533. }
  534. else {
  535. source = "precision highp float;\n" + source;
  536. }
  537. }
  538. else {
  539. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  540. source = source.replace("precision highp float", "precision mediump float");
  541. }
  542. }
  543. return source;
  544. };
  545. /**
  546. * Recompiles the webGL program
  547. * @param vertexSourceCode The source code for the vertex shader.
  548. * @param fragmentSourceCode The source code for the fragment shader.
  549. * @param onCompiled Callback called when completed.
  550. * @param onError Callback called on error.
  551. */
  552. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  553. var _this = this;
  554. this._isReady = false;
  555. this._vertexSourceCodeOverride = vertexSourceCode;
  556. this._fragmentSourceCodeOverride = fragmentSourceCode;
  557. this.onError = function (effect, error) {
  558. if (onError) {
  559. onError(error);
  560. }
  561. };
  562. this.onCompiled = function () {
  563. var scenes = _this.getEngine().scenes;
  564. for (var i = 0; i < scenes.length; i++) {
  565. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  566. }
  567. if (onCompiled) {
  568. onCompiled(_this._program);
  569. }
  570. };
  571. this._fallbacks = null;
  572. this._prepareEffect();
  573. };
  574. /**
  575. * Gets the uniform locations of the the specified variable names
  576. * @param names THe names of the variables to lookup.
  577. * @returns Array of locations in the same order as variable names.
  578. */
  579. Effect.prototype.getSpecificUniformLocations = function (names) {
  580. var engine = this._engine;
  581. return engine.getUniforms(this._program, names);
  582. };
  583. /**
  584. * Prepares the effect
  585. */
  586. Effect.prototype._prepareEffect = function () {
  587. var attributesNames = this._attributesNames;
  588. var defines = this.defines;
  589. var fallbacks = this._fallbacks;
  590. this._valueCache = {};
  591. var previousProgram = this._program;
  592. try {
  593. var engine = this._engine;
  594. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  595. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  596. }
  597. else {
  598. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  599. }
  600. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  601. if (engine.supportsUniformBuffers) {
  602. for (var name in this._uniformBuffersNames) {
  603. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  604. }
  605. }
  606. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  607. this._attributes = engine.getAttributes(this._program, attributesNames);
  608. var index;
  609. for (index = 0; index < this._samplers.length; index++) {
  610. var sampler = this.getUniform(this._samplers[index]);
  611. if (sampler == null) {
  612. this._samplers.splice(index, 1);
  613. index--;
  614. }
  615. }
  616. engine.bindSamplers(this);
  617. this._compilationError = "";
  618. this._isReady = true;
  619. if (this.onCompiled) {
  620. this.onCompiled(this);
  621. }
  622. this.onCompileObservable.notifyObservers(this);
  623. this.onCompileObservable.clear();
  624. // Unbind mesh reference in fallbacks
  625. if (this._fallbacks) {
  626. this._fallbacks.unBindMesh();
  627. }
  628. if (previousProgram) {
  629. this.getEngine()._deleteProgram(previousProgram);
  630. }
  631. }
  632. catch (e) {
  633. this._compilationError = e.message;
  634. // Let's go through fallbacks then
  635. BABYLON.Tools.Error("Unable to compile effect:");
  636. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  637. return " " + uniform;
  638. }));
  639. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  640. return " " + attribute;
  641. }));
  642. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  643. BABYLON.Tools.Error("Error: " + this._compilationError);
  644. if (previousProgram) {
  645. this._program = previousProgram;
  646. this._isReady = true;
  647. if (this.onError) {
  648. this.onError(this, this._compilationError);
  649. }
  650. this.onErrorObservable.notifyObservers(this);
  651. }
  652. if (fallbacks && fallbacks.isMoreFallbacks) {
  653. BABYLON.Tools.Error("Trying next fallback.");
  654. this.defines = fallbacks.reduce(this.defines);
  655. this._prepareEffect();
  656. }
  657. else {
  658. if (this.onError) {
  659. this.onError(this, this._compilationError);
  660. }
  661. this.onErrorObservable.notifyObservers(this);
  662. this.onErrorObservable.clear();
  663. // Unbind mesh reference in fallbacks
  664. if (this._fallbacks) {
  665. this._fallbacks.unBindMesh();
  666. }
  667. }
  668. }
  669. };
  670. Object.defineProperty(Effect.prototype, "isSupported", {
  671. /**
  672. * Checks if the effect is supported. (Must be called after compilation)
  673. */
  674. get: function () {
  675. return this._compilationError === "";
  676. },
  677. enumerable: true,
  678. configurable: true
  679. });
  680. /**
  681. * Binds a texture to the engine to be used as output of the shader.
  682. * @param channel Name of the output variable.
  683. * @param texture Texture to bind.
  684. */
  685. Effect.prototype._bindTexture = function (channel, texture) {
  686. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  687. };
  688. /**
  689. * Sets a texture on the engine to be used in the shader.
  690. * @param channel Name of the sampler variable.
  691. * @param texture Texture to set.
  692. */
  693. Effect.prototype.setTexture = function (channel, texture) {
  694. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  695. };
  696. /**
  697. * Sets an array of textures on the engine to be used in the shader.
  698. * @param channel Name of the variable.
  699. * @param textures Textures to set.
  700. */
  701. Effect.prototype.setTextureArray = function (channel, textures) {
  702. if (this._samplers.indexOf(channel + "Ex") === -1) {
  703. var initialPos = this._samplers.indexOf(channel);
  704. for (var index = 1; index < textures.length; index++) {
  705. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  706. }
  707. }
  708. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  709. };
  710. /**
  711. * 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)
  712. * @param channel Name of the sampler variable.
  713. * @param postProcess Post process to get the input texture from.
  714. */
  715. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  716. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  717. };
  718. /** @ignore */
  719. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  720. var cache = this._valueCache[uniformName];
  721. var flag = matrix.updateFlag;
  722. if (cache !== undefined && cache === flag) {
  723. return false;
  724. }
  725. this._valueCache[uniformName] = flag;
  726. return true;
  727. };
  728. /** @ignore */
  729. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  730. var cache = this._valueCache[uniformName];
  731. if (!cache) {
  732. cache = [x, y];
  733. this._valueCache[uniformName] = cache;
  734. return true;
  735. }
  736. var changed = false;
  737. if (cache[0] !== x) {
  738. cache[0] = x;
  739. changed = true;
  740. }
  741. if (cache[1] !== y) {
  742. cache[1] = y;
  743. changed = true;
  744. }
  745. return changed;
  746. };
  747. /** @ignore */
  748. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  749. var cache = this._valueCache[uniformName];
  750. if (!cache) {
  751. cache = [x, y, z];
  752. this._valueCache[uniformName] = cache;
  753. return true;
  754. }
  755. var changed = false;
  756. if (cache[0] !== x) {
  757. cache[0] = x;
  758. changed = true;
  759. }
  760. if (cache[1] !== y) {
  761. cache[1] = y;
  762. changed = true;
  763. }
  764. if (cache[2] !== z) {
  765. cache[2] = z;
  766. changed = true;
  767. }
  768. return changed;
  769. };
  770. /** @ignore */
  771. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  772. var cache = this._valueCache[uniformName];
  773. if (!cache) {
  774. cache = [x, y, z, w];
  775. this._valueCache[uniformName] = cache;
  776. return true;
  777. }
  778. var changed = false;
  779. if (cache[0] !== x) {
  780. cache[0] = x;
  781. changed = true;
  782. }
  783. if (cache[1] !== y) {
  784. cache[1] = y;
  785. changed = true;
  786. }
  787. if (cache[2] !== z) {
  788. cache[2] = z;
  789. changed = true;
  790. }
  791. if (cache[3] !== w) {
  792. cache[3] = w;
  793. changed = true;
  794. }
  795. return changed;
  796. };
  797. /**
  798. * Binds a buffer to a uniform.
  799. * @param buffer Buffer to bind.
  800. * @param name Name of the uniform variable to bind to.
  801. */
  802. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  803. var bufferName = this._uniformBuffersNames[name];
  804. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  805. return;
  806. }
  807. Effect._baseCache[bufferName] = buffer;
  808. this._engine.bindUniformBufferBase(buffer, bufferName);
  809. };
  810. /**
  811. * Binds block to a uniform.
  812. * @param blockName Name of the block to bind.
  813. * @param index Index to bind.
  814. */
  815. Effect.prototype.bindUniformBlock = function (blockName, index) {
  816. this._engine.bindUniformBlock(this._program, blockName, index);
  817. };
  818. /**
  819. * Sets an interger value on a uniform variable.
  820. * @param uniformName Name of the variable.
  821. * @param value Value to be set.
  822. * @returns this effect.
  823. */
  824. Effect.prototype.setInt = function (uniformName, value) {
  825. var cache = this._valueCache[uniformName];
  826. if (cache !== undefined && cache === value)
  827. return this;
  828. this._valueCache[uniformName] = value;
  829. this._engine.setInt(this.getUniform(uniformName), value);
  830. return this;
  831. };
  832. /**
  833. * Sets an int array on a uniform variable.
  834. * @param uniformName Name of the variable.
  835. * @param array array to be set.
  836. * @returns this effect.
  837. */
  838. Effect.prototype.setIntArray = function (uniformName, array) {
  839. this._valueCache[uniformName] = null;
  840. this._engine.setIntArray(this.getUniform(uniformName), array);
  841. return this;
  842. };
  843. /**
  844. * 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)
  845. * @param uniformName Name of the variable.
  846. * @param array array to be set.
  847. * @returns this effect.
  848. */
  849. Effect.prototype.setIntArray2 = function (uniformName, array) {
  850. this._valueCache[uniformName] = null;
  851. this._engine.setIntArray2(this.getUniform(uniformName), array);
  852. return this;
  853. };
  854. /**
  855. * 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)
  856. * @param uniformName Name of the variable.
  857. * @param array array to be set.
  858. * @returns this effect.
  859. */
  860. Effect.prototype.setIntArray3 = function (uniformName, array) {
  861. this._valueCache[uniformName] = null;
  862. this._engine.setIntArray3(this.getUniform(uniformName), array);
  863. return this;
  864. };
  865. /**
  866. * 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)
  867. * @param uniformName Name of the variable.
  868. * @param array array to be set.
  869. * @returns this effect.
  870. */
  871. Effect.prototype.setIntArray4 = function (uniformName, array) {
  872. this._valueCache[uniformName] = null;
  873. this._engine.setIntArray4(this.getUniform(uniformName), array);
  874. return this;
  875. };
  876. /**
  877. * Sets an float array on a uniform variable.
  878. * @param uniformName Name of the variable.
  879. * @param array array to be set.
  880. * @returns this effect.
  881. */
  882. Effect.prototype.setFloatArray = function (uniformName, array) {
  883. this._valueCache[uniformName] = null;
  884. this._engine.setFloatArray(this.getUniform(uniformName), array);
  885. return this;
  886. };
  887. /**
  888. * 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)
  889. * @param uniformName Name of the variable.
  890. * @param array array to be set.
  891. * @returns this effect.
  892. */
  893. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  894. this._valueCache[uniformName] = null;
  895. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  896. return this;
  897. };
  898. /**
  899. * 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)
  900. * @param uniformName Name of the variable.
  901. * @param array array to be set.
  902. * @returns this effect.
  903. */
  904. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  905. this._valueCache[uniformName] = null;
  906. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  907. return this;
  908. };
  909. /**
  910. * 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)
  911. * @param uniformName Name of the variable.
  912. * @param array array to be set.
  913. * @returns this effect.
  914. */
  915. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  916. this._valueCache[uniformName] = null;
  917. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  918. return this;
  919. };
  920. /**
  921. * Sets an array on a uniform variable.
  922. * @param uniformName Name of the variable.
  923. * @param array array to be set.
  924. * @returns this effect.
  925. */
  926. Effect.prototype.setArray = function (uniformName, array) {
  927. this._valueCache[uniformName] = null;
  928. this._engine.setArray(this.getUniform(uniformName), array);
  929. return this;
  930. };
  931. /**
  932. * 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)
  933. * @param uniformName Name of the variable.
  934. * @param array array to be set.
  935. * @returns this effect.
  936. */
  937. Effect.prototype.setArray2 = function (uniformName, array) {
  938. this._valueCache[uniformName] = null;
  939. this._engine.setArray2(this.getUniform(uniformName), array);
  940. return this;
  941. };
  942. /**
  943. * 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)
  944. * @param uniformName Name of the variable.
  945. * @param array array to be set.
  946. * @returns this effect.
  947. */
  948. Effect.prototype.setArray3 = function (uniformName, array) {
  949. this._valueCache[uniformName] = null;
  950. this._engine.setArray3(this.getUniform(uniformName), array);
  951. return this;
  952. };
  953. /**
  954. * 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)
  955. * @param uniformName Name of the variable.
  956. * @param array array to be set.
  957. * @returns this effect.
  958. */
  959. Effect.prototype.setArray4 = function (uniformName, array) {
  960. this._valueCache[uniformName] = null;
  961. this._engine.setArray4(this.getUniform(uniformName), array);
  962. return this;
  963. };
  964. /**
  965. * Sets matrices on a uniform variable.
  966. * @param uniformName Name of the variable.
  967. * @param matrices matrices to be set.
  968. * @returns this effect.
  969. */
  970. Effect.prototype.setMatrices = function (uniformName, matrices) {
  971. if (!matrices) {
  972. return this;
  973. }
  974. this._valueCache[uniformName] = null;
  975. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  976. return this;
  977. };
  978. /**
  979. * Sets matrix on a uniform variable.
  980. * @param uniformName Name of the variable.
  981. * @param matrix matrix to be set.
  982. * @returns this effect.
  983. */
  984. Effect.prototype.setMatrix = function (uniformName, matrix) {
  985. if (this._cacheMatrix(uniformName, matrix)) {
  986. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  987. }
  988. return this;
  989. };
  990. /**
  991. * 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)
  992. * @param uniformName Name of the variable.
  993. * @param matrix matrix to be set.
  994. * @returns this effect.
  995. */
  996. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  997. this._valueCache[uniformName] = null;
  998. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  999. return this;
  1000. };
  1001. /**
  1002. * Sets a 2x2 matrix on a uniform variable. (Speicified as [1,2,3,4] will result in [1,2][3,4] matrix)
  1003. * @param uniformName Name of the variable.
  1004. * @param matrix matrix to be set.
  1005. * @returns this effect.
  1006. */
  1007. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  1008. this._valueCache[uniformName] = null;
  1009. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  1010. return this;
  1011. };
  1012. /**
  1013. * Sets a float on a uniform variable.
  1014. * @param uniformName Name of the variable.
  1015. * @param value value to be set.
  1016. * @returns this effect.
  1017. */
  1018. Effect.prototype.setFloat = function (uniformName, value) {
  1019. var cache = this._valueCache[uniformName];
  1020. if (cache !== undefined && cache === value)
  1021. return this;
  1022. this._valueCache[uniformName] = value;
  1023. this._engine.setFloat(this.getUniform(uniformName), value);
  1024. return this;
  1025. };
  1026. /**
  1027. * Sets a boolean on a uniform variable.
  1028. * @param uniformName Name of the variable.
  1029. * @param bool value to be set.
  1030. * @returns this effect.
  1031. */
  1032. Effect.prototype.setBool = function (uniformName, bool) {
  1033. var cache = this._valueCache[uniformName];
  1034. if (cache !== undefined && cache === bool)
  1035. return this;
  1036. this._valueCache[uniformName] = bool;
  1037. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  1038. return this;
  1039. };
  1040. /**
  1041. * Sets a Vector2 on a uniform variable.
  1042. * @param uniformName Name of the variable.
  1043. * @param vector2 vector2 to be set.
  1044. * @returns this effect.
  1045. */
  1046. Effect.prototype.setVector2 = function (uniformName, vector2) {
  1047. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  1048. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  1049. }
  1050. return this;
  1051. };
  1052. /**
  1053. * Sets a float2 on a uniform variable.
  1054. * @param uniformName Name of the variable.
  1055. * @param x First float in float2.
  1056. * @param y Second float in float2.
  1057. * @returns this effect.
  1058. */
  1059. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  1060. if (this._cacheFloat2(uniformName, x, y)) {
  1061. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  1062. }
  1063. return this;
  1064. };
  1065. /**
  1066. * Sets a Vector3 on a uniform variable.
  1067. * @param uniformName Name of the variable.
  1068. * @param vector3 Value to be set.
  1069. * @returns this effect.
  1070. */
  1071. Effect.prototype.setVector3 = function (uniformName, vector3) {
  1072. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  1073. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  1074. }
  1075. return this;
  1076. };
  1077. /**
  1078. * Sets a float3 on a uniform variable.
  1079. * @param uniformName Name of the variable.
  1080. * @param x First float in float3.
  1081. * @param y Second float in float3.
  1082. * @param z Third float in float3.
  1083. * @returns this effect.
  1084. */
  1085. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  1086. if (this._cacheFloat3(uniformName, x, y, z)) {
  1087. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  1088. }
  1089. return this;
  1090. };
  1091. /**
  1092. * Sets a Vector4 on a uniform variable.
  1093. * @param uniformName Name of the variable.
  1094. * @param vector4 Value to be set.
  1095. * @returns this effect.
  1096. */
  1097. Effect.prototype.setVector4 = function (uniformName, vector4) {
  1098. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  1099. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  1100. }
  1101. return this;
  1102. };
  1103. /**
  1104. * Sets a float4 on a uniform variable.
  1105. * @param uniformName Name of the variable.
  1106. * @param x First float in float4.
  1107. * @param y Second float in float4.
  1108. * @param z Third float in float4.
  1109. * @param w Fourth float in float4.
  1110. * @returns this effect.
  1111. */
  1112. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  1113. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  1114. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  1115. }
  1116. return this;
  1117. };
  1118. /**
  1119. * Sets a Color3 on a uniform variable.
  1120. * @param uniformName Name of the variable.
  1121. * @param color3 Value to be set.
  1122. * @returns this effect.
  1123. */
  1124. Effect.prototype.setColor3 = function (uniformName, color3) {
  1125. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  1126. this._engine.setColor3(this.getUniform(uniformName), color3);
  1127. }
  1128. return this;
  1129. };
  1130. /**
  1131. * Sets a Color4 on a uniform variable.
  1132. * @param uniformName Name of the variable.
  1133. * @param color3 Value to be set.
  1134. * @param alpha Alpha value to be set.
  1135. * @returns this effect.
  1136. */
  1137. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  1138. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  1139. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  1140. }
  1141. return this;
  1142. };
  1143. /**
  1144. * Resets the cache of effects.
  1145. */
  1146. Effect.ResetCache = function () {
  1147. Effect._baseCache = {};
  1148. };
  1149. Effect._uniqueIdSeed = 0;
  1150. Effect._baseCache = {};
  1151. // Statics
  1152. /**
  1153. * Store of each shader (The can be looked up using effect.key)
  1154. */
  1155. Effect.ShadersStore = {};
  1156. /**
  1157. * Store of each included file for a shader (The can be looked up using effect.key)
  1158. */
  1159. Effect.IncludesShadersStore = {};
  1160. return Effect;
  1161. }());
  1162. BABYLON.Effect = Effect;
  1163. })(BABYLON || (BABYLON = {}));
  1164. //# sourceMappingURL=babylon.effect.js.map
  1165. //# sourceMappingURL=babylon.types.js.map
  1166. var BABYLON;
  1167. (function (BABYLON) {
  1168. var KeyboardEventTypes = /** @class */ (function () {
  1169. function KeyboardEventTypes() {
  1170. }
  1171. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  1172. get: function () {
  1173. return KeyboardEventTypes._KEYDOWN;
  1174. },
  1175. enumerable: true,
  1176. configurable: true
  1177. });
  1178. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  1179. get: function () {
  1180. return KeyboardEventTypes._KEYUP;
  1181. },
  1182. enumerable: true,
  1183. configurable: true
  1184. });
  1185. KeyboardEventTypes._KEYDOWN = 0x01;
  1186. KeyboardEventTypes._KEYUP = 0x02;
  1187. return KeyboardEventTypes;
  1188. }());
  1189. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  1190. var KeyboardInfo = /** @class */ (function () {
  1191. function KeyboardInfo(type, event) {
  1192. this.type = type;
  1193. this.event = event;
  1194. }
  1195. return KeyboardInfo;
  1196. }());
  1197. BABYLON.KeyboardInfo = KeyboardInfo;
  1198. /**
  1199. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1200. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  1201. */
  1202. var KeyboardInfoPre = /** @class */ (function (_super) {
  1203. __extends(KeyboardInfoPre, _super);
  1204. function KeyboardInfoPre(type, event) {
  1205. var _this = _super.call(this, type, event) || this;
  1206. _this.skipOnPointerObservable = false;
  1207. return _this;
  1208. }
  1209. return KeyboardInfoPre;
  1210. }(KeyboardInfo));
  1211. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  1212. })(BABYLON || (BABYLON = {}));
  1213. //# sourceMappingURL=babylon.keyboardEvents.js.map
  1214. var BABYLON;
  1215. (function (BABYLON) {
  1216. var PointerEventTypes = /** @class */ (function () {
  1217. function PointerEventTypes() {
  1218. }
  1219. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  1220. get: function () {
  1221. return PointerEventTypes._POINTERDOWN;
  1222. },
  1223. enumerable: true,
  1224. configurable: true
  1225. });
  1226. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  1227. get: function () {
  1228. return PointerEventTypes._POINTERUP;
  1229. },
  1230. enumerable: true,
  1231. configurable: true
  1232. });
  1233. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  1234. get: function () {
  1235. return PointerEventTypes._POINTERMOVE;
  1236. },
  1237. enumerable: true,
  1238. configurable: true
  1239. });
  1240. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  1241. get: function () {
  1242. return PointerEventTypes._POINTERWHEEL;
  1243. },
  1244. enumerable: true,
  1245. configurable: true
  1246. });
  1247. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  1248. get: function () {
  1249. return PointerEventTypes._POINTERPICK;
  1250. },
  1251. enumerable: true,
  1252. configurable: true
  1253. });
  1254. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  1255. get: function () {
  1256. return PointerEventTypes._POINTERTAP;
  1257. },
  1258. enumerable: true,
  1259. configurable: true
  1260. });
  1261. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  1262. get: function () {
  1263. return PointerEventTypes._POINTERDOUBLETAP;
  1264. },
  1265. enumerable: true,
  1266. configurable: true
  1267. });
  1268. PointerEventTypes._POINTERDOWN = 0x01;
  1269. PointerEventTypes._POINTERUP = 0x02;
  1270. PointerEventTypes._POINTERMOVE = 0x04;
  1271. PointerEventTypes._POINTERWHEEL = 0x08;
  1272. PointerEventTypes._POINTERPICK = 0x10;
  1273. PointerEventTypes._POINTERTAP = 0x20;
  1274. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  1275. return PointerEventTypes;
  1276. }());
  1277. BABYLON.PointerEventTypes = PointerEventTypes;
  1278. var PointerInfoBase = /** @class */ (function () {
  1279. function PointerInfoBase(type, event) {
  1280. this.type = type;
  1281. this.event = event;
  1282. }
  1283. return PointerInfoBase;
  1284. }());
  1285. BABYLON.PointerInfoBase = PointerInfoBase;
  1286. /**
  1287. * This class is used to store pointer related info for the onPrePointerObservable event.
  1288. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  1289. */
  1290. var PointerInfoPre = /** @class */ (function (_super) {
  1291. __extends(PointerInfoPre, _super);
  1292. function PointerInfoPre(type, event, localX, localY) {
  1293. var _this = _super.call(this, type, event) || this;
  1294. _this.skipOnPointerObservable = false;
  1295. _this.localPosition = new BABYLON.Vector2(localX, localY);
  1296. return _this;
  1297. }
  1298. return PointerInfoPre;
  1299. }(PointerInfoBase));
  1300. BABYLON.PointerInfoPre = PointerInfoPre;
  1301. /**
  1302. * This type contains all the data related to a pointer event in Babylon.js.
  1303. * 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.
  1304. */
  1305. var PointerInfo = /** @class */ (function (_super) {
  1306. __extends(PointerInfo, _super);
  1307. function PointerInfo(type, event, pickInfo) {
  1308. var _this = _super.call(this, type, event) || this;
  1309. _this.pickInfo = pickInfo;
  1310. return _this;
  1311. }
  1312. return PointerInfo;
  1313. }(PointerInfoBase));
  1314. BABYLON.PointerInfo = PointerInfo;
  1315. })(BABYLON || (BABYLON = {}));
  1316. //# sourceMappingURL=babylon.pointerEvents.js.map
  1317. var BABYLON;
  1318. (function (BABYLON) {
  1319. BABYLON.ToGammaSpace = 1 / 2.2;
  1320. BABYLON.ToLinearSpace = 2.2;
  1321. BABYLON.Epsilon = 0.001;
  1322. /**
  1323. * Class used to hold a RBG color
  1324. */
  1325. var Color3 = /** @class */ (function () {
  1326. /**
  1327. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  1328. * @param r defines the red component (between 0 and 1, default is 0)
  1329. * @param g defines the green component (between 0 and 1, default is 0)
  1330. * @param b defines the blue component (between 0 and 1, default is 0)
  1331. */
  1332. function Color3(
  1333. /**
  1334. * Defines the red component (between 0 and 1, default is 0)
  1335. */
  1336. r,
  1337. /**
  1338. * Defines the green component (between 0 and 1, default is 0)
  1339. */
  1340. g,
  1341. /**
  1342. * Defines the blue component (between 0 and 1, default is 0)
  1343. */
  1344. b) {
  1345. if (r === void 0) { r = 0; }
  1346. if (g === void 0) { g = 0; }
  1347. if (b === void 0) { b = 0; }
  1348. this.r = r;
  1349. this.g = g;
  1350. this.b = b;
  1351. }
  1352. /**
  1353. * Creates a string with the Color3 current values
  1354. * @returns the string representation of the Color3 object
  1355. */
  1356. Color3.prototype.toString = function () {
  1357. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1358. };
  1359. /**
  1360. * Returns the string "Color3"
  1361. * @returns "Color3"
  1362. */
  1363. Color3.prototype.getClassName = function () {
  1364. return "Color3";
  1365. };
  1366. /**
  1367. * Compute the Color3 hash code
  1368. * @returns an unique number that can be used to hash Color3 objects
  1369. */
  1370. Color3.prototype.getHashCode = function () {
  1371. var hash = this.r || 0;
  1372. hash = (hash * 397) ^ (this.g || 0);
  1373. hash = (hash * 397) ^ (this.b || 0);
  1374. return hash;
  1375. };
  1376. // Operators
  1377. /**
  1378. * Stores in the passed array from the passed starting index the red, green, blue values as successive elements
  1379. * @param array defines the array where to store the r,g,b components
  1380. * @param index defines an optional index in the target array to define where to start storing values
  1381. * @returns the current Color3 object
  1382. */
  1383. Color3.prototype.toArray = function (array, index) {
  1384. if (index === undefined) {
  1385. index = 0;
  1386. }
  1387. array[index] = this.r;
  1388. array[index + 1] = this.g;
  1389. array[index + 2] = this.b;
  1390. return this;
  1391. };
  1392. /**
  1393. * Returns a new {BABYLON.Color4} object from the current Color3 and the passed alpha
  1394. * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1)
  1395. * @returns a new {BABYLON.Color4} object
  1396. */
  1397. Color3.prototype.toColor4 = function (alpha) {
  1398. if (alpha === void 0) { alpha = 1; }
  1399. return new Color4(this.r, this.g, this.b, alpha);
  1400. };
  1401. /**
  1402. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1403. * @returns the new array
  1404. */
  1405. Color3.prototype.asArray = function () {
  1406. var result = new Array();
  1407. this.toArray(result, 0);
  1408. return result;
  1409. };
  1410. /**
  1411. * Returns the luminance value
  1412. * @returns a float value
  1413. */
  1414. Color3.prototype.toLuminance = function () {
  1415. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1416. };
  1417. /**
  1418. * Multiply each Color3 rgb values by the passed Color3 rgb values in a new Color3 object
  1419. * @param otherColor defines the second operand
  1420. * @returns the new Color3 object
  1421. */
  1422. Color3.prototype.multiply = function (otherColor) {
  1423. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1424. };
  1425. /**
  1426. * Multiply the rgb values of the Color3 and the passed Color3 and stores the result in the object "result"
  1427. * @param otherColor defines the second operand
  1428. * @param result defines the Color3 object where to store the result
  1429. * @returns the current Color3
  1430. */
  1431. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1432. result.r = this.r * otherColor.r;
  1433. result.g = this.g * otherColor.g;
  1434. result.b = this.b * otherColor.b;
  1435. return this;
  1436. };
  1437. /**
  1438. * Determines equality between Color3 objects
  1439. * @param otherColor defines the second operand
  1440. * @returns true if the rgb values are equal to the passed ones
  1441. */
  1442. Color3.prototype.equals = function (otherColor) {
  1443. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1444. };
  1445. /**
  1446. * Determines equality between the current Color3 object and a set of r,b,g values
  1447. * @param r defines the red component to check
  1448. * @param g defines the green component to check
  1449. * @param b defines the blue component to check
  1450. * @returns true if the rgb values are equal to the passed ones
  1451. */
  1452. Color3.prototype.equalsFloats = function (r, g, b) {
  1453. return this.r === r && this.g === g && this.b === b;
  1454. };
  1455. /**
  1456. * Multiplies in place each rgb value by scale
  1457. * @param scale defines the scaling factor
  1458. * @returns the updated Color3.
  1459. */
  1460. Color3.prototype.scale = function (scale) {
  1461. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1462. };
  1463. /**
  1464. * Multiplies the rgb values by scale and stores the result into "result"
  1465. * @param scale defines the scaling factor
  1466. * @param result defines the Color3 object where to store the result
  1467. * @returns the unmodified current Color3.
  1468. */
  1469. Color3.prototype.scaleToRef = function (scale, result) {
  1470. result.r = this.r * scale;
  1471. result.g = this.g * scale;
  1472. result.b = this.b * scale;
  1473. return this;
  1474. };
  1475. /**
  1476. * Clamps the rgb values by the min and max values and stores the result into "result"
  1477. * @param min defines minimum clamping value (default is 0)
  1478. * @param max defines maximum clamping value (default is 1)
  1479. * @param result defines color to store the result into
  1480. * @returns the original Color3
  1481. */
  1482. Color3.prototype.clampToRef = function (min, max, result) {
  1483. if (min === void 0) { min = 0; }
  1484. if (max === void 0) { max = 1; }
  1485. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1486. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1487. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1488. return this;
  1489. };
  1490. /**
  1491. * Creates a new Color3 set with the added values of the current Color3 and of the passed one
  1492. * @param otherColor defines the second operand
  1493. * @returns the new Color3
  1494. */
  1495. Color3.prototype.add = function (otherColor) {
  1496. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1497. };
  1498. /**
  1499. * Stores the result of the addition of the current Color3 and passed one rgb values into "result"
  1500. * @param otherColor defines the second operand
  1501. * @param result defines Color3 object to store the result into
  1502. * @returns the unmodified current Color3
  1503. */
  1504. Color3.prototype.addToRef = function (otherColor, result) {
  1505. result.r = this.r + otherColor.r;
  1506. result.g = this.g + otherColor.g;
  1507. result.b = this.b + otherColor.b;
  1508. return this;
  1509. };
  1510. /**
  1511. * Returns a new Color3 set with the subtracted values of the passed one from the current Color3
  1512. * @param otherColor defines the second operand
  1513. * @returns the new Color3
  1514. */
  1515. Color3.prototype.subtract = function (otherColor) {
  1516. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1517. };
  1518. /**
  1519. * Stores the result of the subtraction of passed one from the current Color3 rgb values into "result"
  1520. * @param otherColor defines the second operand
  1521. * @param result defines Color3 object to store the result into
  1522. * @returns the unmodified current Color3
  1523. */
  1524. Color3.prototype.subtractToRef = function (otherColor, result) {
  1525. result.r = this.r - otherColor.r;
  1526. result.g = this.g - otherColor.g;
  1527. result.b = this.b - otherColor.b;
  1528. return this;
  1529. };
  1530. /**
  1531. * Copy the current object
  1532. * @returns a new Color3 copied the current one
  1533. */
  1534. Color3.prototype.clone = function () {
  1535. return new Color3(this.r, this.g, this.b);
  1536. };
  1537. /**
  1538. * Copies the rgb values from the source in the current Color3
  1539. * @param source defines the source Color3 object
  1540. * @returns the updated Color3 object
  1541. */
  1542. Color3.prototype.copyFrom = function (source) {
  1543. this.r = source.r;
  1544. this.g = source.g;
  1545. this.b = source.b;
  1546. return this;
  1547. };
  1548. /**
  1549. * Updates the Color3 rgb values from the passed floats
  1550. * @param r defines the red component to read from
  1551. * @param g defines the green component to read from
  1552. * @param b defines the blue component to read from
  1553. * @returns the current Color3 object
  1554. */
  1555. Color3.prototype.copyFromFloats = function (r, g, b) {
  1556. this.r = r;
  1557. this.g = g;
  1558. this.b = b;
  1559. return this;
  1560. };
  1561. /**
  1562. * Updates the Color3 rgb values from the passed floats
  1563. * @param r defines the red component to read from
  1564. * @param g defines the green component to read from
  1565. * @param b defines the blue component to read from
  1566. * @returns the current Color3 object
  1567. */
  1568. Color3.prototype.set = function (r, g, b) {
  1569. return this.copyFromFloats(r, g, b);
  1570. };
  1571. /**
  1572. * Compute the Color3 hexadecimal code as a string
  1573. * @returns a string containing the hexadecimal representation of the Color3 object
  1574. */
  1575. Color3.prototype.toHexString = function () {
  1576. var intR = (this.r * 255) | 0;
  1577. var intG = (this.g * 255) | 0;
  1578. var intB = (this.b * 255) | 0;
  1579. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1580. };
  1581. /**
  1582. * Computes a new Color3 converted from the current one to linear space
  1583. * @returns a new Color3 object
  1584. */
  1585. Color3.prototype.toLinearSpace = function () {
  1586. var convertedColor = new Color3();
  1587. this.toLinearSpaceToRef(convertedColor);
  1588. return convertedColor;
  1589. };
  1590. /**
  1591. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1592. * @param convertedColor defines the Color3 object where to store the linear space version
  1593. * @returns the unmodified Color3
  1594. */
  1595. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1596. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1597. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1598. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1599. return this;
  1600. };
  1601. /**
  1602. * Computes a new Color3 converted from the current one to gamma space
  1603. * @returns a new Color3 object
  1604. */
  1605. Color3.prototype.toGammaSpace = function () {
  1606. var convertedColor = new Color3();
  1607. this.toGammaSpaceToRef(convertedColor);
  1608. return convertedColor;
  1609. };
  1610. /**
  1611. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1612. * @param convertedColor defines the Color3 object where to store the gamma space version
  1613. * @returns the unmodified Color3
  1614. */
  1615. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1616. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1617. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1618. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1619. return this;
  1620. };
  1621. // Statics
  1622. /**
  1623. * Creates a new Color3 from the string containing valid hexadecimal values
  1624. * @param hex defines a string containing valid hexadecimal values
  1625. * @returns a new Color3 object
  1626. */
  1627. Color3.FromHexString = function (hex) {
  1628. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1629. //Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
  1630. return new Color3(0, 0, 0);
  1631. }
  1632. var r = parseInt(hex.substring(1, 3), 16);
  1633. var g = parseInt(hex.substring(3, 5), 16);
  1634. var b = parseInt(hex.substring(5, 7), 16);
  1635. return Color3.FromInts(r, g, b);
  1636. };
  1637. /**
  1638. * Creates a new Vector3 from the starting index of the passed array
  1639. * @param array defines the source array
  1640. * @param offset defines an offset in the source array
  1641. * @returns a new Color3 object
  1642. */
  1643. Color3.FromArray = function (array, offset) {
  1644. if (offset === void 0) { offset = 0; }
  1645. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1646. };
  1647. /**
  1648. * Creates a new Color3 from integer values (< 256)
  1649. * @param r defines the red component to read from (value between 0 and 255)
  1650. * @param g defines the green component to read from (value between 0 and 255)
  1651. * @param b defines the blue component to read from (value between 0 and 255)
  1652. * @returns a new Color3 object
  1653. */
  1654. Color3.FromInts = function (r, g, b) {
  1655. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1656. };
  1657. /**
  1658. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1659. * @param start defines the start Color3 value
  1660. * @param end defines the end Color3 value
  1661. * @param amount defines the gradient value between start and end
  1662. * @returns a new Color3 object
  1663. */
  1664. Color3.Lerp = function (start, end, amount) {
  1665. var r = start.r + ((end.r - start.r) * amount);
  1666. var g = start.g + ((end.g - start.g) * amount);
  1667. var b = start.b + ((end.b - start.b) * amount);
  1668. return new Color3(r, g, b);
  1669. };
  1670. /**
  1671. * Returns a Color3 value containing a red color
  1672. * @returns a new Color3 object
  1673. */
  1674. Color3.Red = function () { return new Color3(1, 0, 0); };
  1675. /**
  1676. * Returns a Color3 value containing a green color
  1677. * @returns a new Color3 object
  1678. */
  1679. Color3.Green = function () { return new Color3(0, 1, 0); };
  1680. /**
  1681. * Returns a Color3 value containing a blue color
  1682. * @returns a new Color3 object
  1683. */
  1684. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1685. /**
  1686. * Returns a Color3 value containing a black color
  1687. * @returns a new Color3 object
  1688. */
  1689. Color3.Black = function () { return new Color3(0, 0, 0); };
  1690. /**
  1691. * Returns a Color3 value containing a white color
  1692. * @returns a new Color3 object
  1693. */
  1694. Color3.White = function () { return new Color3(1, 1, 1); };
  1695. /**
  1696. * Returns a Color3 value containing a purple color
  1697. * @returns a new Color3 object
  1698. */
  1699. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1700. /**
  1701. * Returns a Color3 value containing a magenta color
  1702. * @returns a new Color3 object
  1703. */
  1704. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1705. /**
  1706. * Returns a Color3 value containing a yellow color
  1707. * @returns a new Color3 object
  1708. */
  1709. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1710. /**
  1711. * Returns a Color3 value containing a gray color
  1712. * @returns a new Color3 object
  1713. */
  1714. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1715. /**
  1716. * Returns a Color3 value containing a teal color
  1717. * @returns a new Color3 object
  1718. */
  1719. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1720. /**
  1721. * Returns a Color3 value containing a random color
  1722. * @returns a new Color3 object
  1723. */
  1724. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1725. return Color3;
  1726. }());
  1727. BABYLON.Color3 = Color3;
  1728. /**
  1729. * Class used to hold a RBGA color
  1730. */
  1731. var Color4 = /** @class */ (function () {
  1732. /**
  1733. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1734. * @param r defines the red component (between 0 and 1, default is 0)
  1735. * @param g defines the green component (between 0 and 1, default is 0)
  1736. * @param b defines the blue component (between 0 and 1, default is 0)
  1737. * @param a defines the alpha component (between 0 and 1, default is 1)
  1738. */
  1739. function Color4(
  1740. /**
  1741. * Defines the red component (between 0 and 1, default is 0)
  1742. */
  1743. r,
  1744. /**
  1745. * Defines the green component (between 0 and 1, default is 0)
  1746. */
  1747. g,
  1748. /**
  1749. * Defines the blue component (between 0 and 1, default is 0)
  1750. */
  1751. b,
  1752. /**
  1753. * Defines the alpha component (between 0 and 1, default is 1)
  1754. */
  1755. a) {
  1756. if (r === void 0) { r = 0; }
  1757. if (g === void 0) { g = 0; }
  1758. if (b === void 0) { b = 0; }
  1759. if (a === void 0) { a = 1; }
  1760. this.r = r;
  1761. this.g = g;
  1762. this.b = b;
  1763. this.a = a;
  1764. }
  1765. // Operators
  1766. /**
  1767. * Adds in place the passed Color4 values to the current Color4 object
  1768. * @param right defines the second operand
  1769. * @returns the current updated Color4 object
  1770. */
  1771. Color4.prototype.addInPlace = function (right) {
  1772. this.r += right.r;
  1773. this.g += right.g;
  1774. this.b += right.b;
  1775. this.a += right.a;
  1776. return this;
  1777. };
  1778. /**
  1779. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1780. * @returns the new array
  1781. */
  1782. Color4.prototype.asArray = function () {
  1783. var result = new Array();
  1784. this.toArray(result, 0);
  1785. return result;
  1786. };
  1787. /**
  1788. * Stores from the starting index in the passed array the Color4 successive values
  1789. * @param array defines the array where to store the r,g,b components
  1790. * @param index defines an optional index in the target array to define where to start storing values
  1791. * @returns the current Color4 object
  1792. */
  1793. Color4.prototype.toArray = function (array, index) {
  1794. if (index === undefined) {
  1795. index = 0;
  1796. }
  1797. array[index] = this.r;
  1798. array[index + 1] = this.g;
  1799. array[index + 2] = this.b;
  1800. array[index + 3] = this.a;
  1801. return this;
  1802. };
  1803. /**
  1804. * Creates a new Color4 set with the added values of the current Color4 and of the passed one
  1805. * @param right defines the second operand
  1806. * @returns a new Color4 object
  1807. */
  1808. Color4.prototype.add = function (right) {
  1809. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1810. };
  1811. /**
  1812. * Creates a new Color4 set with the subtracted values of the passed one from the current Color4
  1813. * @param right defines the second operand
  1814. * @returns a new Color4 object
  1815. */
  1816. Color4.prototype.subtract = function (right) {
  1817. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1818. };
  1819. /**
  1820. * Subtracts the passed ones from the current Color4 values and stores the results in "result"
  1821. * @param right defines the second operand
  1822. * @param result defines the Color4 object where to store the result
  1823. * @returns the current Color4 object
  1824. */
  1825. Color4.prototype.subtractToRef = function (right, result) {
  1826. result.r = this.r - right.r;
  1827. result.g = this.g - right.g;
  1828. result.b = this.b - right.b;
  1829. result.a = this.a - right.a;
  1830. return this;
  1831. };
  1832. /**
  1833. * Creates a new Color4 with the current Color4 values multiplied by scale
  1834. * @param scale defines the scaling factor to apply
  1835. * @returns a new Color4 object
  1836. */
  1837. Color4.prototype.scale = function (scale) {
  1838. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  1839. };
  1840. /**
  1841. * Multiplies the current Color4 values by scale and stores the result in "result"
  1842. * @param scale defines the scaling factor to apply
  1843. * @param result defines the Color4 object where to store the result
  1844. * @returns the current Color4.
  1845. */
  1846. Color4.prototype.scaleToRef = function (scale, result) {
  1847. result.r = this.r * scale;
  1848. result.g = this.g * scale;
  1849. result.b = this.b * scale;
  1850. result.a = this.a * scale;
  1851. return this;
  1852. };
  1853. /**
  1854. * Clamps the rgb values by the min and max values and stores the result into "result"
  1855. * @param min defines minimum clamping value (default is 0)
  1856. * @param max defines maximum clamping value (default is 1)
  1857. * @param result defines color to store the result into.
  1858. * @returns the cuurent Color4
  1859. */
  1860. Color4.prototype.clampToRef = function (min, max, result) {
  1861. if (min === void 0) { min = 0; }
  1862. if (max === void 0) { max = 1; }
  1863. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1864. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1865. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1866. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  1867. return this;
  1868. };
  1869. /**
  1870. * Multipy an Color4 value by another and return a new Color4 object
  1871. * @param color defines the Color4 value to multiply by
  1872. * @returns a new Color4 object
  1873. */
  1874. Color4.prototype.multiply = function (color) {
  1875. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  1876. };
  1877. /**
  1878. * Multipy a Color4 value by another and push the result in a reference value
  1879. * @param color defines the Color4 value to multiply by
  1880. * @param result defines the Color4 to fill the result in
  1881. * @returns the result Color4
  1882. */
  1883. Color4.prototype.multiplyToRef = function (color, result) {
  1884. result.r = this.r * color.r;
  1885. result.g = this.g * color.g;
  1886. result.b = this.b * color.b;
  1887. result.a = this.a * color.a;
  1888. return result;
  1889. };
  1890. /**
  1891. * Creates a string with the Color4 current values
  1892. * @returns the string representation of the Color4 object
  1893. */
  1894. Color4.prototype.toString = function () {
  1895. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  1896. };
  1897. /**
  1898. * Returns the string "Color4"
  1899. * @returns "Color4"
  1900. */
  1901. Color4.prototype.getClassName = function () {
  1902. return "Color4";
  1903. };
  1904. /**
  1905. * Compute the Color4 hash code
  1906. * @returns an unique number that can be used to hash Color4 objects
  1907. */
  1908. Color4.prototype.getHashCode = function () {
  1909. var hash = this.r || 0;
  1910. hash = (hash * 397) ^ (this.g || 0);
  1911. hash = (hash * 397) ^ (this.b || 0);
  1912. hash = (hash * 397) ^ (this.a || 0);
  1913. return hash;
  1914. };
  1915. /**
  1916. * Creates a new Color4 copied from the current one
  1917. * @returns a new Color4 object
  1918. */
  1919. Color4.prototype.clone = function () {
  1920. return new Color4(this.r, this.g, this.b, this.a);
  1921. };
  1922. /**
  1923. * Copies the passed Color4 values into the current one
  1924. * @param source defines the source Color4 object
  1925. * @returns the current updated Color4 object
  1926. */
  1927. Color4.prototype.copyFrom = function (source) {
  1928. this.r = source.r;
  1929. this.g = source.g;
  1930. this.b = source.b;
  1931. this.a = source.a;
  1932. return this;
  1933. };
  1934. /**
  1935. * Copies the passed float values into the current one
  1936. * @param r defines the red component to read from
  1937. * @param g defines the green component to read from
  1938. * @param b defines the blue component to read from
  1939. * @param a defines the alpha component to read from
  1940. * @returns the current updated Color4 object
  1941. */
  1942. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  1943. this.r = r;
  1944. this.g = g;
  1945. this.b = b;
  1946. this.a = a;
  1947. return this;
  1948. };
  1949. /**
  1950. * Copies the passed float values into the current one
  1951. * @param r defines the red component to read from
  1952. * @param g defines the green component to read from
  1953. * @param b defines the blue component to read from
  1954. * @param a defines the alpha component to read from
  1955. * @returns the current updated Color4 object
  1956. */
  1957. Color4.prototype.set = function (r, g, b, a) {
  1958. return this.copyFromFloats(r, g, b, a);
  1959. };
  1960. /**
  1961. * Compute the Color4 hexadecimal code as a string
  1962. * @returns a string containing the hexadecimal representation of the Color4 object
  1963. */
  1964. Color4.prototype.toHexString = function () {
  1965. var intR = (this.r * 255) | 0;
  1966. var intG = (this.g * 255) | 0;
  1967. var intB = (this.b * 255) | 0;
  1968. var intA = (this.a * 255) | 0;
  1969. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  1970. };
  1971. /**
  1972. * Computes a new Color4 converted from the current one to linear space
  1973. * @returns a new Color4 object
  1974. */
  1975. Color4.prototype.toLinearSpace = function () {
  1976. var convertedColor = new Color4();
  1977. this.toLinearSpaceToRef(convertedColor);
  1978. return convertedColor;
  1979. };
  1980. /**
  1981. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  1982. * @param convertedColor defines the Color4 object where to store the linear space version
  1983. * @returns the unmodified Color4
  1984. */
  1985. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  1986. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1987. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1988. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1989. convertedColor.a = this.a;
  1990. return this;
  1991. };
  1992. /**
  1993. * Computes a new Color4 converted from the current one to gamma space
  1994. * @returns a new Color4 object
  1995. */
  1996. Color4.prototype.toGammaSpace = function () {
  1997. var convertedColor = new Color4();
  1998. this.toGammaSpaceToRef(convertedColor);
  1999. return convertedColor;
  2000. };
  2001. /**
  2002. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  2003. * @param convertedColor defines the Color4 object where to store the gamma space version
  2004. * @returns the unmodified Color4
  2005. */
  2006. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  2007. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  2008. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  2009. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  2010. convertedColor.a = this.a;
  2011. return this;
  2012. };
  2013. // Statics
  2014. /**
  2015. * Creates a new Color4 from the string containing valid hexadecimal values
  2016. * @param hex defines a string containing valid hexadecimal values
  2017. * @returns a new Color4 object
  2018. */
  2019. Color4.FromHexString = function (hex) {
  2020. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  2021. //Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
  2022. return new Color4(0.0, 0.0, 0.0, 0.0);
  2023. }
  2024. var r = parseInt(hex.substring(1, 3), 16);
  2025. var g = parseInt(hex.substring(3, 5), 16);
  2026. var b = parseInt(hex.substring(5, 7), 16);
  2027. var a = parseInt(hex.substring(7, 9), 16);
  2028. return Color4.FromInts(r, g, b, a);
  2029. };
  2030. /**
  2031. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2032. * @param left defines the start value
  2033. * @param right defines the end value
  2034. * @param amount defines the gradient factor
  2035. * @returns a new Color4 object
  2036. */
  2037. Color4.Lerp = function (left, right, amount) {
  2038. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  2039. Color4.LerpToRef(left, right, amount, result);
  2040. return result;
  2041. };
  2042. /**
  2043. * Set the passed "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2044. * @param left defines the start value
  2045. * @param right defines the end value
  2046. * @param amount defines the gradient factor
  2047. * @param result defines the Color4 object where to store data
  2048. */
  2049. Color4.LerpToRef = function (left, right, amount, result) {
  2050. result.r = left.r + (right.r - left.r) * amount;
  2051. result.g = left.g + (right.g - left.g) * amount;
  2052. result.b = left.b + (right.b - left.b) * amount;
  2053. result.a = left.a + (right.a - left.a) * amount;
  2054. };
  2055. /**
  2056. * Creates a new Color4 from the starting index element of the passed array
  2057. * @param array defines the source array to read from
  2058. * @param offset defines the offset in the source array
  2059. * @returns a new Color4 object
  2060. */
  2061. Color4.FromArray = function (array, offset) {
  2062. if (offset === void 0) { offset = 0; }
  2063. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2064. };
  2065. /**
  2066. * Creates a new Color3 from integer values (< 256)
  2067. * @param r defines the red component to read from (value between 0 and 255)
  2068. * @param g defines the green component to read from (value between 0 and 255)
  2069. * @param b defines the blue component to read from (value between 0 and 255)
  2070. * @param a defines the alpha component to read from (value between 0 and 255)
  2071. * @returns a new Color3 object
  2072. */
  2073. Color4.FromInts = function (r, g, b, a) {
  2074. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  2075. };
  2076. /**
  2077. * Check the content of a given array and convert it to an array containing RGBA data
  2078. * If the original array was already containing count * 4 values then it is returned directly
  2079. * @param colors defines the array to check
  2080. * @param count defines the number of RGBA data to expect
  2081. * @returns an array containing count * 4 values (RGBA)
  2082. */
  2083. Color4.CheckColors4 = function (colors, count) {
  2084. // Check if color3 was used
  2085. if (colors.length === count * 3) {
  2086. var colors4 = [];
  2087. for (var index = 0; index < colors.length; index += 3) {
  2088. var newIndex = (index / 3) * 4;
  2089. colors4[newIndex] = colors[index];
  2090. colors4[newIndex + 1] = colors[index + 1];
  2091. colors4[newIndex + 2] = colors[index + 2];
  2092. colors4[newIndex + 3] = 1.0;
  2093. }
  2094. return colors4;
  2095. }
  2096. return colors;
  2097. };
  2098. return Color4;
  2099. }());
  2100. BABYLON.Color4 = Color4;
  2101. var Vector2 = /** @class */ (function () {
  2102. /**
  2103. * Creates a new Vector2 from the passed x and y coordinates.
  2104. */
  2105. function Vector2(x, y) {
  2106. this.x = x;
  2107. this.y = y;
  2108. }
  2109. /**
  2110. * Returns a string with the Vector2 coordinates.
  2111. */
  2112. Vector2.prototype.toString = function () {
  2113. return "{X: " + this.x + " Y:" + this.y + "}";
  2114. };
  2115. /**
  2116. * Returns the string "Vector2"
  2117. */
  2118. Vector2.prototype.getClassName = function () {
  2119. return "Vector2";
  2120. };
  2121. /**
  2122. * Returns the Vector2 hash code as a number.
  2123. */
  2124. Vector2.prototype.getHashCode = function () {
  2125. var hash = this.x || 0;
  2126. hash = (hash * 397) ^ (this.y || 0);
  2127. return hash;
  2128. };
  2129. // Operators
  2130. /**
  2131. * Sets the Vector2 coordinates in the passed array or Float32Array from the passed index.
  2132. * Returns the Vector2.
  2133. */
  2134. Vector2.prototype.toArray = function (array, index) {
  2135. if (index === void 0) { index = 0; }
  2136. array[index] = this.x;
  2137. array[index + 1] = this.y;
  2138. return this;
  2139. };
  2140. /**
  2141. * Returns a new array with 2 elements : the Vector2 coordinates.
  2142. */
  2143. Vector2.prototype.asArray = function () {
  2144. var result = new Array();
  2145. this.toArray(result, 0);
  2146. return result;
  2147. };
  2148. /**
  2149. * Sets the Vector2 coordinates with the passed Vector2 coordinates.
  2150. * Returns the updated Vector2.
  2151. */
  2152. Vector2.prototype.copyFrom = function (source) {
  2153. this.x = source.x;
  2154. this.y = source.y;
  2155. return this;
  2156. };
  2157. /**
  2158. * Sets the Vector2 coordinates with the passed floats.
  2159. * Returns the updated Vector2.
  2160. */
  2161. Vector2.prototype.copyFromFloats = function (x, y) {
  2162. this.x = x;
  2163. this.y = y;
  2164. return this;
  2165. };
  2166. /**
  2167. * Sets the Vector2 coordinates with the passed floats.
  2168. * Returns the updated Vector2.
  2169. */
  2170. Vector2.prototype.set = function (x, y) {
  2171. return this.copyFromFloats(x, y);
  2172. };
  2173. /**
  2174. * Returns a new Vector2 set with the addition of the current Vector2 and the passed one coordinates.
  2175. */
  2176. Vector2.prototype.add = function (otherVector) {
  2177. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2178. };
  2179. /**
  2180. * Sets the "result" coordinates with the addition of the current Vector2 and the passed one coordinates.
  2181. * Returns the Vector2.
  2182. */
  2183. Vector2.prototype.addToRef = function (otherVector, result) {
  2184. result.x = this.x + otherVector.x;
  2185. result.y = this.y + otherVector.y;
  2186. return this;
  2187. };
  2188. /**
  2189. * Set the Vector2 coordinates by adding the passed Vector2 coordinates.
  2190. * Returns the updated Vector2.
  2191. */
  2192. Vector2.prototype.addInPlace = function (otherVector) {
  2193. this.x += otherVector.x;
  2194. this.y += otherVector.y;
  2195. return this;
  2196. };
  2197. /**
  2198. * Returns a new Vector2 by adding the current Vector2 coordinates to the passed Vector3 x, y coordinates.
  2199. */
  2200. Vector2.prototype.addVector3 = function (otherVector) {
  2201. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2202. };
  2203. /**
  2204. * Returns a new Vector2 set with the subtracted coordinates of the passed one from the current Vector2.
  2205. */
  2206. Vector2.prototype.subtract = function (otherVector) {
  2207. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  2208. };
  2209. /**
  2210. * Sets the "result" coordinates with the subtraction of the passed one from the current Vector2 coordinates.
  2211. * Returns the Vector2.
  2212. */
  2213. Vector2.prototype.subtractToRef = function (otherVector, result) {
  2214. result.x = this.x - otherVector.x;
  2215. result.y = this.y - otherVector.y;
  2216. return this;
  2217. };
  2218. /**
  2219. * Sets the current Vector2 coordinates by subtracting from it the passed one coordinates.
  2220. * Returns the updated Vector2.
  2221. */
  2222. Vector2.prototype.subtractInPlace = function (otherVector) {
  2223. this.x -= otherVector.x;
  2224. this.y -= otherVector.y;
  2225. return this;
  2226. };
  2227. /**
  2228. * Multiplies in place the current Vector2 coordinates by the passed ones.
  2229. * Returns the updated Vector2.
  2230. */
  2231. Vector2.prototype.multiplyInPlace = function (otherVector) {
  2232. this.x *= otherVector.x;
  2233. this.y *= otherVector.y;
  2234. return this;
  2235. };
  2236. /**
  2237. * Returns a new Vector2 set with the multiplication of the current Vector2 and the passed one coordinates.
  2238. */
  2239. Vector2.prototype.multiply = function (otherVector) {
  2240. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  2241. };
  2242. /**
  2243. * Sets "result" coordinates with the multiplication of the current Vector2 and the passed one coordinates.
  2244. * Returns the Vector2.
  2245. */
  2246. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  2247. result.x = this.x * otherVector.x;
  2248. result.y = this.y * otherVector.y;
  2249. return this;
  2250. };
  2251. /**
  2252. * Returns a new Vector2 set with the Vector2 coordinates multiplied by the passed floats.
  2253. */
  2254. Vector2.prototype.multiplyByFloats = function (x, y) {
  2255. return new Vector2(this.x * x, this.y * y);
  2256. };
  2257. /**
  2258. * Returns a new Vector2 set with the Vector2 coordinates divided by the passed one coordinates.
  2259. */
  2260. Vector2.prototype.divide = function (otherVector) {
  2261. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  2262. };
  2263. /**
  2264. * Sets the "result" coordinates with the Vector2 divided by the passed one coordinates.
  2265. * Returns the Vector2.
  2266. */
  2267. Vector2.prototype.divideToRef = function (otherVector, result) {
  2268. result.x = this.x / otherVector.x;
  2269. result.y = this.y / otherVector.y;
  2270. return this;
  2271. };
  2272. /**
  2273. * Divides the current Vector3 coordinates by the passed ones.
  2274. * Returns the updated Vector3.
  2275. */
  2276. Vector2.prototype.divideInPlace = function (otherVector) {
  2277. return this.divideToRef(otherVector, this);
  2278. };
  2279. /**
  2280. * Returns a new Vector2 with current Vector2 negated coordinates.
  2281. */
  2282. Vector2.prototype.negate = function () {
  2283. return new Vector2(-this.x, -this.y);
  2284. };
  2285. /**
  2286. * Multiply the Vector2 coordinates by scale.
  2287. * Returns the updated Vector2.
  2288. */
  2289. Vector2.prototype.scaleInPlace = function (scale) {
  2290. this.x *= scale;
  2291. this.y *= scale;
  2292. return this;
  2293. };
  2294. /**
  2295. * Returns a new Vector2 scaled by "scale" from the current Vector2.
  2296. */
  2297. Vector2.prototype.scale = function (scale) {
  2298. return new Vector2(this.x * scale, this.y * scale);
  2299. };
  2300. /**
  2301. * Boolean : True if the passed vector coordinates strictly equal the current Vector2 ones.
  2302. */
  2303. Vector2.prototype.equals = function (otherVector) {
  2304. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  2305. };
  2306. /**
  2307. * Boolean : True if the passed vector coordinates are close to the current ones by a distance of epsilon.
  2308. */
  2309. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2310. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2311. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  2312. };
  2313. // Properties
  2314. /**
  2315. * Returns the vector length (float).
  2316. */
  2317. Vector2.prototype.length = function () {
  2318. return Math.sqrt(this.x * this.x + this.y * this.y);
  2319. };
  2320. /**
  2321. * Returns the vector squared length (float);
  2322. */
  2323. Vector2.prototype.lengthSquared = function () {
  2324. return (this.x * this.x + this.y * this.y);
  2325. };
  2326. // Methods
  2327. /**
  2328. * Normalize the vector.
  2329. * Returns the updated Vector2.
  2330. */
  2331. Vector2.prototype.normalize = function () {
  2332. var len = this.length();
  2333. if (len === 0)
  2334. return this;
  2335. var num = 1.0 / len;
  2336. this.x *= num;
  2337. this.y *= num;
  2338. return this;
  2339. };
  2340. /**
  2341. * Returns a new Vector2 copied from the Vector2.
  2342. */
  2343. Vector2.prototype.clone = function () {
  2344. return new Vector2(this.x, this.y);
  2345. };
  2346. // Statics
  2347. /**
  2348. * Returns a new Vector2(0, 0)
  2349. */
  2350. Vector2.Zero = function () {
  2351. return new Vector2(0, 0);
  2352. };
  2353. /**
  2354. * Returns a new Vector2(1, 1)
  2355. */
  2356. Vector2.One = function () {
  2357. return new Vector2(1, 1);
  2358. };
  2359. /**
  2360. * Returns a new Vector2 set from the passed index element of the passed array.
  2361. */
  2362. Vector2.FromArray = function (array, offset) {
  2363. if (offset === void 0) { offset = 0; }
  2364. return new Vector2(array[offset], array[offset + 1]);
  2365. };
  2366. /**
  2367. * Sets "result" from the passed index element of the passed array.
  2368. */
  2369. Vector2.FromArrayToRef = function (array, offset, result) {
  2370. result.x = array[offset];
  2371. result.y = array[offset + 1];
  2372. };
  2373. /**
  2374. * Retuns a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the passed four Vector2.
  2375. */
  2376. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2377. var squared = amount * amount;
  2378. var cubed = amount * squared;
  2379. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2380. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2381. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2382. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2383. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2384. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2385. return new Vector2(x, y);
  2386. };
  2387. /**
  2388. * 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".
  2389. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2390. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate.
  2391. */
  2392. Vector2.Clamp = function (value, min, max) {
  2393. var x = value.x;
  2394. x = (x > max.x) ? max.x : x;
  2395. x = (x < min.x) ? min.x : x;
  2396. var y = value.y;
  2397. y = (y > max.y) ? max.y : y;
  2398. y = (y < min.y) ? min.y : y;
  2399. return new Vector2(x, y);
  2400. };
  2401. /**
  2402. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2".
  2403. */
  2404. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2405. var squared = amount * amount;
  2406. var cubed = amount * squared;
  2407. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2408. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2409. var part3 = (cubed - (2.0 * squared)) + amount;
  2410. var part4 = cubed - squared;
  2411. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2412. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2413. return new Vector2(x, y);
  2414. };
  2415. /**
  2416. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2417. */
  2418. Vector2.Lerp = function (start, end, amount) {
  2419. var x = start.x + ((end.x - start.x) * amount);
  2420. var y = start.y + ((end.y - start.y) * amount);
  2421. return new Vector2(x, y);
  2422. };
  2423. /**
  2424. * Returns the dot product (float) of the vector "left" and the vector "right".
  2425. */
  2426. Vector2.Dot = function (left, right) {
  2427. return left.x * right.x + left.y * right.y;
  2428. };
  2429. /**
  2430. * Returns a new Vector2 equal to the normalized passed vector.
  2431. */
  2432. Vector2.Normalize = function (vector) {
  2433. var newVector = vector.clone();
  2434. newVector.normalize();
  2435. return newVector;
  2436. };
  2437. /**
  2438. * Returns a new Vecto2 set with the minimal coordinate values from the "left" and "right" vectors.
  2439. */
  2440. Vector2.Minimize = function (left, right) {
  2441. var x = (left.x < right.x) ? left.x : right.x;
  2442. var y = (left.y < right.y) ? left.y : right.y;
  2443. return new Vector2(x, y);
  2444. };
  2445. /**
  2446. * Returns a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors.
  2447. */
  2448. Vector2.Maximize = function (left, right) {
  2449. var x = (left.x > right.x) ? left.x : right.x;
  2450. var y = (left.y > right.y) ? left.y : right.y;
  2451. return new Vector2(x, y);
  2452. };
  2453. /**
  2454. * Returns a new Vecto2 set with the transformed coordinates of the passed vector by the passed transformation matrix.
  2455. */
  2456. Vector2.Transform = function (vector, transformation) {
  2457. var r = Vector2.Zero();
  2458. Vector2.TransformToRef(vector, transformation, r);
  2459. return r;
  2460. };
  2461. /**
  2462. * Transforms the passed vector coordinates by the passed transformation matrix and stores the result in the vector "result" coordinates.
  2463. */
  2464. Vector2.TransformToRef = function (vector, transformation, result) {
  2465. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2466. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2467. result.x = x;
  2468. result.y = y;
  2469. };
  2470. /**
  2471. * Boolean : True if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2472. */
  2473. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2474. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2475. var sign = a < 0 ? -1 : 1;
  2476. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2477. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2478. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2479. };
  2480. /**
  2481. * Returns the distance (float) between the vectors "value1" and "value2".
  2482. */
  2483. Vector2.Distance = function (value1, value2) {
  2484. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2485. };
  2486. /**
  2487. * Returns the squared distance (float) between the vectors "value1" and "value2".
  2488. */
  2489. Vector2.DistanceSquared = function (value1, value2) {
  2490. var x = value1.x - value2.x;
  2491. var y = value1.y - value2.y;
  2492. return (x * x) + (y * y);
  2493. };
  2494. /**
  2495. * Returns a new Vecto2 located at the center of the vectors "value1" and "value2".
  2496. */
  2497. Vector2.Center = function (value1, value2) {
  2498. var center = value1.add(value2);
  2499. center.scaleInPlace(0.5);
  2500. return center;
  2501. };
  2502. /**
  2503. * Returns the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2504. */
  2505. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2506. var l2 = Vector2.DistanceSquared(segA, segB);
  2507. if (l2 === 0.0) {
  2508. return Vector2.Distance(p, segA);
  2509. }
  2510. var v = segB.subtract(segA);
  2511. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2512. var proj = segA.add(v.multiplyByFloats(t, t));
  2513. return Vector2.Distance(p, proj);
  2514. };
  2515. return Vector2;
  2516. }());
  2517. BABYLON.Vector2 = Vector2;
  2518. /**
  2519. * Classed used to store (x,y,z) vector representation
  2520. * A Vector3 is the main object used in 3D geometry
  2521. * It can represent etiher the coordinates of a point the space, either a direction
  2522. * Reminder: Babylon.js uses a left handed forward facing system
  2523. */
  2524. var Vector3 = /** @class */ (function () {
  2525. /**
  2526. * Creates a new Vector3 object from the passed x, y, z (floats) coordinates.
  2527. * @param x defines the first coordinates (on X axis)
  2528. * @param y defines the second coordinates (on Y axis)
  2529. * @param z defines the third coordinates (on Z axis)
  2530. */
  2531. function Vector3(
  2532. /**
  2533. * Defines the first coordinates (on X axis)
  2534. */
  2535. x,
  2536. /**
  2537. * Defines the second coordinates (on Y axis)
  2538. */
  2539. y,
  2540. /**
  2541. * Defines the third coordinates (on Z axis)
  2542. */
  2543. z) {
  2544. this.x = x;
  2545. this.y = y;
  2546. this.z = z;
  2547. }
  2548. /**
  2549. * Creates a string representation of the Vector3
  2550. * @returns a string with the Vector3 coordinates.
  2551. */
  2552. Vector3.prototype.toString = function () {
  2553. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2554. };
  2555. /**
  2556. * Gets the class name
  2557. * @returns the string "Vector3"
  2558. */
  2559. Vector3.prototype.getClassName = function () {
  2560. return "Vector3";
  2561. };
  2562. /**
  2563. * Creates the Vector3 hash code
  2564. * @returns a number which tends to be unique between Vector3 instances
  2565. */
  2566. Vector3.prototype.getHashCode = function () {
  2567. var hash = this.x || 0;
  2568. hash = (hash * 397) ^ (this.y || 0);
  2569. hash = (hash * 397) ^ (this.z || 0);
  2570. return hash;
  2571. };
  2572. // Operators
  2573. /**
  2574. * Creates an array containing three elements : the coordinates of the Vector3
  2575. * @returns a new array of numbers
  2576. */
  2577. Vector3.prototype.asArray = function () {
  2578. var result = [];
  2579. this.toArray(result, 0);
  2580. return result;
  2581. };
  2582. /**
  2583. * Populates the passed array or Float32Array from the passed index with the successive coordinates of the Vector3
  2584. * @param array defines the destination array
  2585. * @param index defines the offset in the destination array
  2586. * @returns the current Vector3
  2587. */
  2588. Vector3.prototype.toArray = function (array, index) {
  2589. if (index === void 0) { index = 0; }
  2590. array[index] = this.x;
  2591. array[index + 1] = this.y;
  2592. array[index + 2] = this.z;
  2593. return this;
  2594. };
  2595. /**
  2596. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  2597. * @returns a new Quaternion object, computed from the Vector3 coordinates
  2598. */
  2599. Vector3.prototype.toQuaternion = function () {
  2600. var result = new Quaternion(0.0, 0.0, 0.0, 1.0);
  2601. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  2602. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  2603. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  2604. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  2605. var cosy = Math.cos(this.y * 0.5);
  2606. var siny = Math.sin(this.y * 0.5);
  2607. result.x = coszMinusx * siny;
  2608. result.y = -sinzMinusx * siny;
  2609. result.z = sinxPlusz * cosy;
  2610. result.w = cosxPlusz * cosy;
  2611. return result;
  2612. };
  2613. /**
  2614. * Adds the passed vector to the current Vector3
  2615. * @param otherVector defines the second operand
  2616. * @returns the current updated Vector3
  2617. */
  2618. Vector3.prototype.addInPlace = function (otherVector) {
  2619. this.x += otherVector.x;
  2620. this.y += otherVector.y;
  2621. this.z += otherVector.z;
  2622. return this;
  2623. };
  2624. /**
  2625. * Gets a new Vector3, result of the addition the current Vector3 and the passed vector
  2626. * @param otherVector defines the second operand
  2627. * @returns the resulting Vector3
  2628. */
  2629. Vector3.prototype.add = function (otherVector) {
  2630. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2631. };
  2632. /**
  2633. * Adds the current Vector3 to the passed one and stores the result in the vector "result"
  2634. * @param otherVector defines the second operand
  2635. * @param result defines the Vector3 object where to store the result
  2636. * @returns the current Vector3
  2637. */
  2638. Vector3.prototype.addToRef = function (otherVector, result) {
  2639. result.x = this.x + otherVector.x;
  2640. result.y = this.y + otherVector.y;
  2641. result.z = this.z + otherVector.z;
  2642. return this;
  2643. };
  2644. /**
  2645. * Subtract the passed vector from the current Vector3
  2646. * @param otherVector defines the second operand
  2647. * @returns the current updated Vector3
  2648. */
  2649. Vector3.prototype.subtractInPlace = function (otherVector) {
  2650. this.x -= otherVector.x;
  2651. this.y -= otherVector.y;
  2652. this.z -= otherVector.z;
  2653. return this;
  2654. };
  2655. /**
  2656. * Returns a new Vector3, result of the subtraction of the passed vector from the current Vector3
  2657. * @param otherVector defines the second operand
  2658. * @returns the resulting Vector3
  2659. */
  2660. Vector3.prototype.subtract = function (otherVector) {
  2661. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2662. };
  2663. /**
  2664. * Subtracts the passed vector from the current Vector3 and stores the result in the vector "result".
  2665. * @param otherVector defines the second operand
  2666. * @param result defines the Vector3 object where to store the result
  2667. * @returns the current Vector3
  2668. */
  2669. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2670. result.x = this.x - otherVector.x;
  2671. result.y = this.y - otherVector.y;
  2672. result.z = this.z - otherVector.z;
  2673. return this;
  2674. };
  2675. /**
  2676. * Returns a new Vector3 set with the subtraction of the passed floats from the current Vector3 coordinates
  2677. * @param x defines the x coordinate of the operand
  2678. * @param y defines the y coordinate of the operand
  2679. * @param z defines the z coordinate of the operand
  2680. * @returns the resulting Vector3
  2681. */
  2682. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2683. return new Vector3(this.x - x, this.y - y, this.z - z);
  2684. };
  2685. /**
  2686. * Subtracts the passed floats from the current Vector3 coordinates and set the passed vector "result" with this result
  2687. * @param x defines the x coordinate of the operand
  2688. * @param y defines the y coordinate of the operand
  2689. * @param z defines the z coordinate of the operand
  2690. * @param result defines the Vector3 object where to store the result
  2691. * @returns the current Vector3
  2692. */
  2693. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  2694. result.x = this.x - x;
  2695. result.y = this.y - y;
  2696. result.z = this.z - z;
  2697. return this;
  2698. };
  2699. /**
  2700. * Gets a new Vector3 set with the current Vector3 negated coordinates
  2701. * @returns a new Vector3
  2702. */
  2703. Vector3.prototype.negate = function () {
  2704. return new Vector3(-this.x, -this.y, -this.z);
  2705. };
  2706. /**
  2707. * Multiplies the Vector3 coordinates by the float "scale"
  2708. * @param scale defines the multiplier factor
  2709. * @returns the current updated Vector3
  2710. */
  2711. Vector3.prototype.scaleInPlace = function (scale) {
  2712. this.x *= scale;
  2713. this.y *= scale;
  2714. this.z *= scale;
  2715. return this;
  2716. };
  2717. /**
  2718. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  2719. * @param scale defines the multiplier factor
  2720. * @returns a new Vector3
  2721. */
  2722. Vector3.prototype.scale = function (scale) {
  2723. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  2724. };
  2725. /**
  2726. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the passed vector "result" coordinates
  2727. * @param scale defines the multiplier factor
  2728. * @param result defines the Vector3 object where to store the result
  2729. * @returns the current Vector3
  2730. */
  2731. Vector3.prototype.scaleToRef = function (scale, result) {
  2732. result.x = this.x * scale;
  2733. result.y = this.y * scale;
  2734. result.z = this.z * scale;
  2735. return this;
  2736. };
  2737. /**
  2738. * Returns true if the current Vector3 and the passed vector coordinates are strictly equal
  2739. * @param otherVector defines the second operand
  2740. * @returns true if both vectors are equals
  2741. */
  2742. Vector3.prototype.equals = function (otherVector) {
  2743. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  2744. };
  2745. /**
  2746. * Returns true if the current Vector3 and the passed vector coordinates are distant less than epsilon
  2747. * @param otherVector defines the second operand
  2748. * @param epsilon defines the minimal distance to define values as equals
  2749. * @returns true if both vectors are distant less than epsilon
  2750. */
  2751. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2752. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2753. 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);
  2754. };
  2755. /**
  2756. * Returns true if the current Vector3 coordinates equals the passed floats
  2757. * @param x defines the x coordinate of the operand
  2758. * @param y defines the y coordinate of the operand
  2759. * @param z defines the z coordinate of the operand
  2760. * @returns true if both vectors are equals
  2761. */
  2762. Vector3.prototype.equalsToFloats = function (x, y, z) {
  2763. return this.x === x && this.y === y && this.z === z;
  2764. };
  2765. /**
  2766. * Multiplies the current Vector3 coordinates by the passed ones
  2767. * @param otherVector defines the second operand
  2768. * @returns the current updated Vector3
  2769. */
  2770. Vector3.prototype.multiplyInPlace = function (otherVector) {
  2771. this.x *= otherVector.x;
  2772. this.y *= otherVector.y;
  2773. this.z *= otherVector.z;
  2774. return this;
  2775. };
  2776. /**
  2777. * Returns a new Vector3, result of the multiplication of the current Vector3 by the passed vector
  2778. * @param otherVector defines the second operand
  2779. * @returns the new Vector3
  2780. */
  2781. Vector3.prototype.multiply = function (otherVector) {
  2782. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  2783. };
  2784. /**
  2785. * Multiplies the current Vector3 by the passed one and stores the result in the passed vector "result"
  2786. * @param otherVector defines the second operand
  2787. * @param result defines the Vector3 object where to store the result
  2788. * @returns the current Vector3
  2789. */
  2790. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  2791. result.x = this.x * otherVector.x;
  2792. result.y = this.y * otherVector.y;
  2793. result.z = this.z * otherVector.z;
  2794. return this;
  2795. };
  2796. /**
  2797. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the passed floats
  2798. * @param x defines the x coordinate of the operand
  2799. * @param y defines the y coordinate of the operand
  2800. * @param z defines the z coordinate of the operand
  2801. * @returns the new Vector3
  2802. */
  2803. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  2804. return new Vector3(this.x * x, this.y * y, this.z * z);
  2805. };
  2806. /**
  2807. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the passed ones
  2808. * @param otherVector defines the second operand
  2809. * @returns the new Vector3
  2810. */
  2811. Vector3.prototype.divide = function (otherVector) {
  2812. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  2813. };
  2814. /**
  2815. * Divides the current Vector3 coordinates by the passed ones and stores the result in the passed vector "result"
  2816. * @param otherVector defines the second operand
  2817. * @param result defines the Vector3 object where to store the result
  2818. * @returns the current Vector3
  2819. */
  2820. Vector3.prototype.divideToRef = function (otherVector, result) {
  2821. result.x = this.x / otherVector.x;
  2822. result.y = this.y / otherVector.y;
  2823. result.z = this.z / otherVector.z;
  2824. return this;
  2825. };
  2826. /**
  2827. * Divides the current Vector3 coordinates by the passed ones.
  2828. * @param otherVector defines the second operand
  2829. * @returns the current updated Vector3
  2830. */
  2831. Vector3.prototype.divideInPlace = function (otherVector) {
  2832. return this.divideToRef(otherVector, this);
  2833. };
  2834. /**
  2835. * Updates the current Vector3 with the minimal coordinate values between its and the passed vector ones
  2836. * @param other defines the second operand
  2837. * @returns the current updated Vector3
  2838. */
  2839. Vector3.prototype.minimizeInPlace = function (other) {
  2840. if (other.x < this.x)
  2841. this.x = other.x;
  2842. if (other.y < this.y)
  2843. this.y = other.y;
  2844. if (other.z < this.z)
  2845. this.z = other.z;
  2846. return this;
  2847. };
  2848. /**
  2849. * Updates the current Vector3 with the maximal coordinate values between its and the passed vector ones.
  2850. * @param other defines the second operand
  2851. * @returns the current updated Vector3
  2852. */
  2853. Vector3.prototype.maximizeInPlace = function (other) {
  2854. if (other.x > this.x)
  2855. this.x = other.x;
  2856. if (other.y > this.y)
  2857. this.y = other.y;
  2858. if (other.z > this.z)
  2859. this.z = other.z;
  2860. return this;
  2861. };
  2862. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  2863. /**
  2864. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  2865. */
  2866. get: function () {
  2867. var absX = Math.abs(this.x);
  2868. var absY = Math.abs(this.y);
  2869. if (absX !== absY) {
  2870. return true;
  2871. }
  2872. var absZ = Math.abs(this.z);
  2873. if (absX !== absZ) {
  2874. return true;
  2875. }
  2876. if (absY !== absZ) {
  2877. return true;
  2878. }
  2879. return false;
  2880. },
  2881. enumerable: true,
  2882. configurable: true
  2883. });
  2884. // Properties
  2885. /**
  2886. * Gets the length of the Vector3
  2887. * @returns the length of the Vecto3
  2888. */
  2889. Vector3.prototype.length = function () {
  2890. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  2891. };
  2892. /**
  2893. * Gets the squared length of the Vector3
  2894. * @returns squared length of the Vector3
  2895. */
  2896. Vector3.prototype.lengthSquared = function () {
  2897. return (this.x * this.x + this.y * this.y + this.z * this.z);
  2898. };
  2899. /**
  2900. * Normalize the current Vector3.
  2901. * Please note that this is an in place operation.
  2902. * @returns the current updated Vector3
  2903. */
  2904. Vector3.prototype.normalize = function () {
  2905. var len = this.length();
  2906. if (len === 0 || len === 1.0)
  2907. return this;
  2908. var num = 1.0 / len;
  2909. this.x *= num;
  2910. this.y *= num;
  2911. this.z *= num;
  2912. return this;
  2913. };
  2914. /**
  2915. * Normalize the current Vector3 to a new vector
  2916. * @returns the new Vector3
  2917. */
  2918. Vector3.prototype.normalizeToNew = function () {
  2919. var normalized = new Vector3(0, 0, 0);
  2920. this.normalizeToRef(normalized);
  2921. return normalized;
  2922. };
  2923. /**
  2924. * Normalize the current Vector3 to the reference
  2925. * @param reference define the Vector3 to update
  2926. * @returns the updated Vector3
  2927. */
  2928. Vector3.prototype.normalizeToRef = function (reference) {
  2929. var len = this.length();
  2930. if (len === 0 || len === 1.0) {
  2931. reference.set(this.x, this.y, this.z);
  2932. return reference;
  2933. }
  2934. var scale = 1.0 / len;
  2935. this.scaleToRef(scale, reference);
  2936. return reference;
  2937. };
  2938. /**
  2939. * Creates a new Vector3 copied from the current Vector3
  2940. * @returns the new Vector3
  2941. */
  2942. Vector3.prototype.clone = function () {
  2943. return new Vector3(this.x, this.y, this.z);
  2944. };
  2945. /**
  2946. * Copies the passed vector coordinates to the current Vector3 ones
  2947. * @param source defines the source Vector3
  2948. * @returns the current updated Vector3
  2949. */
  2950. Vector3.prototype.copyFrom = function (source) {
  2951. this.x = source.x;
  2952. this.y = source.y;
  2953. this.z = source.z;
  2954. return this;
  2955. };
  2956. /**
  2957. * Copies the passed floats to the current Vector3 coordinates
  2958. * @param x defines the x coordinate of the operand
  2959. * @param y defines the y coordinate of the operand
  2960. * @param z defines the z coordinate of the operand
  2961. * @returns the current updated Vector3
  2962. */
  2963. Vector3.prototype.copyFromFloats = function (x, y, z) {
  2964. this.x = x;
  2965. this.y = y;
  2966. this.z = z;
  2967. return this;
  2968. };
  2969. /**
  2970. * Copies the passed floats to the current Vector3 coordinates
  2971. * @param x defines the x coordinate of the operand
  2972. * @param y defines the y coordinate of the operand
  2973. * @param z defines the z coordinate of the operand
  2974. * @returns the current updated Vector3
  2975. */
  2976. Vector3.prototype.set = function (x, y, z) {
  2977. return this.copyFromFloats(x, y, z);
  2978. };
  2979. // Statics
  2980. /**
  2981. * Get the clip factor between two vectors
  2982. * @param vector0 defines the first operand
  2983. * @param vector1 defines the second operand
  2984. * @param axis defines the axis to use
  2985. * @param size defines the size along the axis
  2986. * @returns the clip factor
  2987. */
  2988. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  2989. var d0 = Vector3.Dot(vector0, axis) - size;
  2990. var d1 = Vector3.Dot(vector1, axis) - size;
  2991. var s = d0 / (d0 - d1);
  2992. return s;
  2993. };
  2994. /**
  2995. * Get angle between two vectors
  2996. * @param vector0 angle between vector0 and vector1
  2997. * @param vector1 angle between vector0 and vector1
  2998. * @param normal direction of the normal
  2999. * @return the angle between vector0 and vector1
  3000. */
  3001. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  3002. var v0 = vector0.clone().normalize();
  3003. var v1 = vector1.clone().normalize();
  3004. var dot = Vector3.Dot(v0, v1);
  3005. var n = Vector3.Cross(v0, v1);
  3006. if (Vector3.Dot(n, normal) > 0) {
  3007. return Math.acos(dot);
  3008. }
  3009. return -Math.acos(dot);
  3010. };
  3011. /**
  3012. * Returns a new Vector3 set from the index "offset" of the passed array
  3013. * @param array defines the source array
  3014. * @param offset defines the offset in the source array
  3015. * @returns the new Vector3
  3016. */
  3017. Vector3.FromArray = function (array, offset) {
  3018. if (!offset) {
  3019. offset = 0;
  3020. }
  3021. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  3022. };
  3023. /**
  3024. * Returns a new Vector3 set from the index "offset" of the passed Float32Array
  3025. * This function is deprecated. Use FromArray instead
  3026. * @param array defines the source array
  3027. * @param offset defines the offset in the source array
  3028. * @returns the new Vector3
  3029. */
  3030. Vector3.FromFloatArray = function (array, offset) {
  3031. return Vector3.FromArray(array, offset);
  3032. };
  3033. /**
  3034. * Sets the passed vector "result" with the element values from the index "offset" of the passed array
  3035. * @param array defines the source array
  3036. * @param offset defines the offset in the source array
  3037. * @param result defines the Vector3 where to store the result
  3038. */
  3039. Vector3.FromArrayToRef = function (array, offset, result) {
  3040. result.x = array[offset];
  3041. result.y = array[offset + 1];
  3042. result.z = array[offset + 2];
  3043. };
  3044. /**
  3045. * Sets the passed vector "result" with the element values from the index "offset" of the passed Float32Array
  3046. * This function is deprecated. Use FromArrayToRef instead.
  3047. * @param array defines the source array
  3048. * @param offset defines the offset in the source array
  3049. * @param result defines the Vector3 where to store the result
  3050. */
  3051. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  3052. return Vector3.FromArrayToRef(array, offset, result);
  3053. };
  3054. /**
  3055. * Sets the passed vector "result" with the passed floats.
  3056. * @param x defines the x coordinate of the source
  3057. * @param y defines the y coordinate of the source
  3058. * @param z defines the z coordinate of the source
  3059. * @param result defines the Vector3 where to store the result
  3060. */
  3061. Vector3.FromFloatsToRef = function (x, y, z, result) {
  3062. result.x = x;
  3063. result.y = y;
  3064. result.z = z;
  3065. };
  3066. /**
  3067. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  3068. * @returns a new empty Vector3
  3069. */
  3070. Vector3.Zero = function () {
  3071. return new Vector3(0.0, 0.0, 0.0);
  3072. };
  3073. /**
  3074. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  3075. * @returns a new unit Vector3
  3076. */
  3077. Vector3.One = function () {
  3078. return new Vector3(1.0, 1.0, 1.0);
  3079. };
  3080. /**
  3081. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  3082. * @returns a new up Vector3
  3083. */
  3084. Vector3.Up = function () {
  3085. return new Vector3(0.0, 1.0, 0.0);
  3086. };
  3087. /**
  3088. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  3089. * @returns a new forward Vector3
  3090. */
  3091. Vector3.Forward = function () {
  3092. return new Vector3(0.0, 0.0, 1.0);
  3093. };
  3094. /**
  3095. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3096. * @returns a new right Vector3
  3097. */
  3098. Vector3.Right = function () {
  3099. return new Vector3(1.0, 0.0, 0.0);
  3100. };
  3101. /**
  3102. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3103. * @returns a new left Vector3
  3104. */
  3105. Vector3.Left = function () {
  3106. return new Vector3(-1.0, 0.0, 0.0);
  3107. };
  3108. /**
  3109. * Returns a new Vector3 set with the result of the transformation by the passed matrix of the passed vector.
  3110. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3111. * @param vector defines the Vector3 to transform
  3112. * @param transformation defines the transformation matrix
  3113. * @returns the transformed Vector3
  3114. */
  3115. Vector3.TransformCoordinates = function (vector, transformation) {
  3116. var result = Vector3.Zero();
  3117. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3118. return result;
  3119. };
  3120. /**
  3121. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed vector
  3122. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3123. * @param vector defines the Vector3 to transform
  3124. * @param transformation defines the transformation matrix
  3125. * @param result defines the Vector3 where to store the result
  3126. */
  3127. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3128. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3129. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3130. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3131. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3132. result.x = x / w;
  3133. result.y = y / w;
  3134. result.z = z / w;
  3135. };
  3136. /**
  3137. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed floats (x, y, z)
  3138. * This method computes tranformed coordinates only, not transformed direction vectors
  3139. * @param x define the x coordinate of the source vector
  3140. * @param y define the y coordinate of the source vector
  3141. * @param z define the z coordinate of the source vector
  3142. * @param transformation defines the transformation matrix
  3143. * @param result defines the Vector3 where to store the result
  3144. */
  3145. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3146. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3147. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3148. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3149. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3150. result.x = rx / rw;
  3151. result.y = ry / rw;
  3152. result.z = rz / rw;
  3153. };
  3154. /**
  3155. * Returns a new Vector3 set with the result of the normal transformation by the passed matrix of the passed vector
  3156. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3157. * @param vector defines the Vector3 to transform
  3158. * @param transformation defines the transformation matrix
  3159. * @returns the new Vector3
  3160. */
  3161. Vector3.TransformNormal = function (vector, transformation) {
  3162. var result = Vector3.Zero();
  3163. Vector3.TransformNormalToRef(vector, transformation, result);
  3164. return result;
  3165. };
  3166. /**
  3167. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector
  3168. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3169. * @param vector defines the Vector3 to transform
  3170. * @param transformation defines the transformation matrix
  3171. * @param result defines the Vector3 where to store the result
  3172. */
  3173. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3174. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3175. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3176. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3177. result.x = x;
  3178. result.y = y;
  3179. result.z = z;
  3180. };
  3181. /**
  3182. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z)
  3183. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3184. * @param x define the x coordinate of the source vector
  3185. * @param y define the y coordinate of the source vector
  3186. * @param z define the z coordinate of the source vector
  3187. * @param transformation defines the transformation matrix
  3188. * @param result defines the Vector3 where to store the result
  3189. */
  3190. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3191. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3192. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3193. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3194. };
  3195. /**
  3196. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3197. * @param value1 defines the first control point
  3198. * @param value2 defines the second control point
  3199. * @param value3 defines the third control point
  3200. * @param value4 defines the fourth control point
  3201. * @param amount defines the amount on the spline to use
  3202. * @returns the new Vector3
  3203. */
  3204. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3205. var squared = amount * amount;
  3206. var cubed = amount * squared;
  3207. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3208. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3209. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3210. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3211. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3212. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3213. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3214. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3215. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3216. return new Vector3(x, y, z);
  3217. };
  3218. /**
  3219. * 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"
  3220. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3221. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3222. * @param value defines the current value
  3223. * @param min defines the lower range value
  3224. * @param max defines the upper range value
  3225. * @returns the new Vector3
  3226. */
  3227. Vector3.Clamp = function (value, min, max) {
  3228. var x = value.x;
  3229. x = (x > max.x) ? max.x : x;
  3230. x = (x < min.x) ? min.x : x;
  3231. var y = value.y;
  3232. y = (y > max.y) ? max.y : y;
  3233. y = (y < min.y) ? min.y : y;
  3234. var z = value.z;
  3235. z = (z > max.z) ? max.z : z;
  3236. z = (z < min.z) ? min.z : z;
  3237. return new Vector3(x, y, z);
  3238. };
  3239. /**
  3240. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3241. * @param value1 defines the first control point
  3242. * @param tangent1 defines the first tangent vector
  3243. * @param value2 defines the second control point
  3244. * @param tangent2 defines the second tangent vector
  3245. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3246. * @returns the new Vector3
  3247. */
  3248. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3249. var squared = amount * amount;
  3250. var cubed = amount * squared;
  3251. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3252. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3253. var part3 = (cubed - (2.0 * squared)) + amount;
  3254. var part4 = cubed - squared;
  3255. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3256. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3257. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3258. return new Vector3(x, y, z);
  3259. };
  3260. /**
  3261. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3262. * @param start defines the start value
  3263. * @param end defines the end value
  3264. * @param amount max defines amount between both (between 0 and 1)
  3265. * @returns the new Vector3
  3266. */
  3267. Vector3.Lerp = function (start, end, amount) {
  3268. var result = new Vector3(0, 0, 0);
  3269. Vector3.LerpToRef(start, end, amount, result);
  3270. return result;
  3271. };
  3272. /**
  3273. * Sets the passed vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3274. * @param start defines the start value
  3275. * @param end defines the end value
  3276. * @param amount max defines amount between both (between 0 and 1)
  3277. * @param result defines the Vector3 where to store the result
  3278. */
  3279. Vector3.LerpToRef = function (start, end, amount, result) {
  3280. result.x = start.x + ((end.x - start.x) * amount);
  3281. result.y = start.y + ((end.y - start.y) * amount);
  3282. result.z = start.z + ((end.z - start.z) * amount);
  3283. };
  3284. /**
  3285. * Returns the dot product (float) between the vectors "left" and "right"
  3286. * @param left defines the left operand
  3287. * @param right defines the right operand
  3288. * @returns the dot product
  3289. */
  3290. Vector3.Dot = function (left, right) {
  3291. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3292. };
  3293. /**
  3294. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3295. * The cross product is then orthogonal to both "left" and "right"
  3296. * @param left defines the left operand
  3297. * @param right defines the right operand
  3298. * @returns the cross product
  3299. */
  3300. Vector3.Cross = function (left, right) {
  3301. var result = Vector3.Zero();
  3302. Vector3.CrossToRef(left, right, result);
  3303. return result;
  3304. };
  3305. /**
  3306. * Sets the passed vector "result" with the cross product of "left" and "right"
  3307. * The cross product is then orthogonal to both "left" and "right"
  3308. * @param left defines the left operand
  3309. * @param right defines the right operand
  3310. * @param result defines the Vector3 where to store the result
  3311. */
  3312. Vector3.CrossToRef = function (left, right, result) {
  3313. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3314. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3315. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3316. result.copyFrom(MathTmp.Vector3[0]);
  3317. };
  3318. /**
  3319. * Returns a new Vector3 as the normalization of the passed vector
  3320. * @param vector defines the Vector3 to normalize
  3321. * @returns the new Vector3
  3322. */
  3323. Vector3.Normalize = function (vector) {
  3324. var result = Vector3.Zero();
  3325. Vector3.NormalizeToRef(vector, result);
  3326. return result;
  3327. };
  3328. /**
  3329. * Sets the passed vector "result" with the normalization of the passed first vector
  3330. * @param vector defines the Vector3 to normalize
  3331. * @param result defines the Vector3 where to store the result
  3332. */
  3333. Vector3.NormalizeToRef = function (vector, result) {
  3334. result.copyFrom(vector);
  3335. result.normalize();
  3336. };
  3337. /**
  3338. * Project a Vector3 onto screen space
  3339. * @param vector defines the Vector3 to project
  3340. * @param world defines the world matrix to use
  3341. * @param transform defines the transform (view x projection) matrix to use
  3342. * @param viewport defines the screen viewport to use
  3343. * @returns the new Vector3
  3344. */
  3345. Vector3.Project = function (vector, world, transform, viewport) {
  3346. var cw = viewport.width;
  3347. var ch = viewport.height;
  3348. var cx = viewport.x;
  3349. var cy = viewport.y;
  3350. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3351. 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);
  3352. var matrix = MathTmp.Matrix[0];
  3353. world.multiplyToRef(transform, matrix);
  3354. matrix.multiplyToRef(viewportMatrix, matrix);
  3355. return Vector3.TransformCoordinates(vector, matrix);
  3356. };
  3357. /**
  3358. * Unproject from screen space to object space
  3359. * @param source defines the screen space Vector3 to use
  3360. * @param viewportWidth defines the current width of the viewport
  3361. * @param viewportHeight defines the current height of the viewport
  3362. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3363. * @param transform defines the transform (view x projection) matrix to use
  3364. * @returns the new Vector3
  3365. */
  3366. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3367. var matrix = MathTmp.Matrix[0];
  3368. world.multiplyToRef(transform, matrix);
  3369. matrix.invert();
  3370. source.x = source.x / viewportWidth * 2 - 1;
  3371. source.y = -(source.y / viewportHeight * 2 - 1);
  3372. var vector = Vector3.TransformCoordinates(source, matrix);
  3373. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3374. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3375. vector = vector.scale(1.0 / num);
  3376. }
  3377. return vector;
  3378. };
  3379. /**
  3380. * Unproject from screen space to object space
  3381. * @param source defines the screen space Vector3 to use
  3382. * @param viewportWidth defines the current width of the viewport
  3383. * @param viewportHeight defines the current height of the viewport
  3384. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3385. * @param view defines the view matrix to use
  3386. * @param projection defines the projection matrix to use
  3387. * @returns the new Vector3
  3388. */
  3389. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3390. var result = Vector3.Zero();
  3391. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3392. return result;
  3393. };
  3394. /**
  3395. * Unproject from screen space to object space
  3396. * @param source defines the screen space Vector3 to use
  3397. * @param viewportWidth defines the current width of the viewport
  3398. * @param viewportHeight defines the current height of the viewport
  3399. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3400. * @param view defines the view matrix to use
  3401. * @param projection defines the projection matrix to use
  3402. * @param result defines the Vector3 where to store the result
  3403. */
  3404. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3405. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3406. };
  3407. /**
  3408. * Unproject from screen space to object space
  3409. * @param sourceX defines the screen space x coordinate to use
  3410. * @param sourceY defines the screen space y coordinate to use
  3411. * @param sourceZ defines the screen space z coordinate to use
  3412. * @param viewportWidth defines the current width of the viewport
  3413. * @param viewportHeight defines the current height of the viewport
  3414. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3415. * @param view defines the view matrix to use
  3416. * @param projection defines the projection matrix to use
  3417. * @param result defines the Vector3 where to store the result
  3418. */
  3419. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3420. var matrix = MathTmp.Matrix[0];
  3421. world.multiplyToRef(view, matrix);
  3422. matrix.multiplyToRef(projection, matrix);
  3423. matrix.invert();
  3424. var screenSource = MathTmp.Vector3[0];
  3425. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3426. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3427. screenSource.z = 2 * sourceZ - 1.0;
  3428. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3429. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3430. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3431. result.scaleInPlace(1.0 / num);
  3432. }
  3433. };
  3434. /**
  3435. * Gets the minimal coordinate values between two Vector3
  3436. * @param left defines the first operand
  3437. * @param right defines the second operand
  3438. * @returns the new Vector3
  3439. */
  3440. Vector3.Minimize = function (left, right) {
  3441. var min = left.clone();
  3442. min.minimizeInPlace(right);
  3443. return min;
  3444. };
  3445. /**
  3446. * Gets the maximal coordinate values between two Vector3
  3447. * @param left defines the first operand
  3448. * @param right defines the second operand
  3449. * @returns the new Vector3
  3450. */
  3451. Vector3.Maximize = function (left, right) {
  3452. var max = left.clone();
  3453. max.maximizeInPlace(right);
  3454. return max;
  3455. };
  3456. /**
  3457. * Returns the distance between the vectors "value1" and "value2"
  3458. * @param value1 defines the first operand
  3459. * @param value2 defines the second operand
  3460. * @returns the distance
  3461. */
  3462. Vector3.Distance = function (value1, value2) {
  3463. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3464. };
  3465. /**
  3466. * Returns the squared distance between the vectors "value1" and "value2"
  3467. * @param value1 defines the first operand
  3468. * @param value2 defines the second operand
  3469. * @returns the squared distance
  3470. */
  3471. Vector3.DistanceSquared = function (value1, value2) {
  3472. var x = value1.x - value2.x;
  3473. var y = value1.y - value2.y;
  3474. var z = value1.z - value2.z;
  3475. return (x * x) + (y * y) + (z * z);
  3476. };
  3477. /**
  3478. * Returns a new Vector3 located at the center between "value1" and "value2"
  3479. * @param value1 defines the first operand
  3480. * @param value2 defines the second operand
  3481. * @returns the new Vector3
  3482. */
  3483. Vector3.Center = function (value1, value2) {
  3484. var center = value1.add(value2);
  3485. center.scaleInPlace(0.5);
  3486. return center;
  3487. };
  3488. /**
  3489. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3490. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3491. * to something in order to rotate it from its local system to the given target system
  3492. * Note: axis1, axis2 and axis3 are normalized during this operation
  3493. * @param axis1 defines the first axis
  3494. * @param axis2 defines the second axis
  3495. * @param axis3 defines the third axis
  3496. * @returns a new Vector3
  3497. */
  3498. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3499. var rotation = Vector3.Zero();
  3500. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3501. return rotation;
  3502. };
  3503. /**
  3504. * The same than RotationFromAxis but updates the passed ref Vector3 parameter instead of returning a new Vector3
  3505. * @param axis1 defines the first axis
  3506. * @param axis2 defines the second axis
  3507. * @param axis3 defines the third axis
  3508. * @param ref defines the Vector3 where to store the result
  3509. */
  3510. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3511. var quat = MathTmp.Quaternion[0];
  3512. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3513. quat.toEulerAnglesToRef(ref);
  3514. };
  3515. return Vector3;
  3516. }());
  3517. BABYLON.Vector3 = Vector3;
  3518. //Vector4 class created for EulerAngle class conversion to Quaternion
  3519. var Vector4 = /** @class */ (function () {
  3520. /**
  3521. * Creates a Vector4 object from the passed floats.
  3522. */
  3523. function Vector4(x, y, z, w) {
  3524. this.x = x;
  3525. this.y = y;
  3526. this.z = z;
  3527. this.w = w;
  3528. }
  3529. /**
  3530. * Returns the string with the Vector4 coordinates.
  3531. */
  3532. Vector4.prototype.toString = function () {
  3533. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3534. };
  3535. /**
  3536. * Returns the string "Vector4".
  3537. */
  3538. Vector4.prototype.getClassName = function () {
  3539. return "Vector4";
  3540. };
  3541. /**
  3542. * Returns the Vector4 hash code.
  3543. */
  3544. Vector4.prototype.getHashCode = function () {
  3545. var hash = this.x || 0;
  3546. hash = (hash * 397) ^ (this.y || 0);
  3547. hash = (hash * 397) ^ (this.z || 0);
  3548. hash = (hash * 397) ^ (this.w || 0);
  3549. return hash;
  3550. };
  3551. // Operators
  3552. /**
  3553. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3554. */
  3555. Vector4.prototype.asArray = function () {
  3556. var result = new Array();
  3557. this.toArray(result, 0);
  3558. return result;
  3559. };
  3560. /**
  3561. * Populates the passed array from the passed index with the Vector4 coordinates.
  3562. * Returns the Vector4.
  3563. */
  3564. Vector4.prototype.toArray = function (array, index) {
  3565. if (index === undefined) {
  3566. index = 0;
  3567. }
  3568. array[index] = this.x;
  3569. array[index + 1] = this.y;
  3570. array[index + 2] = this.z;
  3571. array[index + 3] = this.w;
  3572. return this;
  3573. };
  3574. /**
  3575. * Adds the passed vector to the current Vector4.
  3576. * Returns the updated Vector4.
  3577. */
  3578. Vector4.prototype.addInPlace = function (otherVector) {
  3579. this.x += otherVector.x;
  3580. this.y += otherVector.y;
  3581. this.z += otherVector.z;
  3582. this.w += otherVector.w;
  3583. return this;
  3584. };
  3585. /**
  3586. * Returns a new Vector4 as the result of the addition of the current Vector4 and the passed one.
  3587. */
  3588. Vector4.prototype.add = function (otherVector) {
  3589. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3590. };
  3591. /**
  3592. * Updates the passed vector "result" with the result of the addition of the current Vector4 and the passed one.
  3593. * Returns the current Vector4.
  3594. */
  3595. Vector4.prototype.addToRef = function (otherVector, result) {
  3596. result.x = this.x + otherVector.x;
  3597. result.y = this.y + otherVector.y;
  3598. result.z = this.z + otherVector.z;
  3599. result.w = this.w + otherVector.w;
  3600. return this;
  3601. };
  3602. /**
  3603. * Subtract in place the passed vector from the current Vector4.
  3604. * Returns the updated Vector4.
  3605. */
  3606. Vector4.prototype.subtractInPlace = function (otherVector) {
  3607. this.x -= otherVector.x;
  3608. this.y -= otherVector.y;
  3609. this.z -= otherVector.z;
  3610. this.w -= otherVector.w;
  3611. return this;
  3612. };
  3613. /**
  3614. * Returns a new Vector4 with the result of the subtraction of the passed vector from the current Vector4.
  3615. */
  3616. Vector4.prototype.subtract = function (otherVector) {
  3617. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  3618. };
  3619. /**
  3620. * Sets the passed vector "result" with the result of the subtraction of the passed vector from the current Vector4.
  3621. * Returns the current Vector4.
  3622. */
  3623. Vector4.prototype.subtractToRef = function (otherVector, result) {
  3624. result.x = this.x - otherVector.x;
  3625. result.y = this.y - otherVector.y;
  3626. result.z = this.z - otherVector.z;
  3627. result.w = this.w - otherVector.w;
  3628. return this;
  3629. };
  3630. /**
  3631. * Returns a new Vector4 set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  3632. */
  3633. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  3634. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  3635. };
  3636. /**
  3637. * Sets the passed vector "result" set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  3638. * Returns the current Vector4.
  3639. */
  3640. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  3641. result.x = this.x - x;
  3642. result.y = this.y - y;
  3643. result.z = this.z - z;
  3644. result.w = this.w - w;
  3645. return this;
  3646. };
  3647. /**
  3648. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  3649. */
  3650. Vector4.prototype.negate = function () {
  3651. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  3652. };
  3653. /**
  3654. * Multiplies the current Vector4 coordinates by scale (float).
  3655. * Returns the updated Vector4.
  3656. */
  3657. Vector4.prototype.scaleInPlace = function (scale) {
  3658. this.x *= scale;
  3659. this.y *= scale;
  3660. this.z *= scale;
  3661. this.w *= scale;
  3662. return this;
  3663. };
  3664. /**
  3665. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  3666. */
  3667. Vector4.prototype.scale = function (scale) {
  3668. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  3669. };
  3670. /**
  3671. * Sets the passed vector "result" with the current Vector4 coordinates multiplied by scale (float).
  3672. * Returns the current Vector4.
  3673. */
  3674. Vector4.prototype.scaleToRef = function (scale, result) {
  3675. result.x = this.x * scale;
  3676. result.y = this.y * scale;
  3677. result.z = this.z * scale;
  3678. result.w = this.w * scale;
  3679. return this;
  3680. };
  3681. /**
  3682. * Boolean : True if the current Vector4 coordinates are stricly equal to the passed ones.
  3683. */
  3684. Vector4.prototype.equals = function (otherVector) {
  3685. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  3686. };
  3687. /**
  3688. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the passed vector ones.
  3689. */
  3690. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3691. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3692. return otherVector
  3693. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  3694. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  3695. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  3696. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  3697. };
  3698. /**
  3699. * Boolean : True if the passed floats are strictly equal to the current Vector4 coordinates.
  3700. */
  3701. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  3702. return this.x === x && this.y === y && this.z === z && this.w === w;
  3703. };
  3704. /**
  3705. * Multiplies in place the current Vector4 by the passed one.
  3706. * Returns the updated Vector4.
  3707. */
  3708. Vector4.prototype.multiplyInPlace = function (otherVector) {
  3709. this.x *= otherVector.x;
  3710. this.y *= otherVector.y;
  3711. this.z *= otherVector.z;
  3712. this.w *= otherVector.w;
  3713. return this;
  3714. };
  3715. /**
  3716. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the passed one.
  3717. */
  3718. Vector4.prototype.multiply = function (otherVector) {
  3719. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  3720. };
  3721. /**
  3722. * Updates the passed vector "result" with the multiplication result of the current Vector4 and the passed one.
  3723. * Returns the current Vector4.
  3724. */
  3725. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  3726. result.x = this.x * otherVector.x;
  3727. result.y = this.y * otherVector.y;
  3728. result.z = this.z * otherVector.z;
  3729. result.w = this.w * otherVector.w;
  3730. return this;
  3731. };
  3732. /**
  3733. * Returns a new Vector4 set with the multiplication result of the passed floats and the current Vector4 coordinates.
  3734. */
  3735. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  3736. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  3737. };
  3738. /**
  3739. * Returns a new Vector4 set with the division result of the current Vector4 by the passed one.
  3740. */
  3741. Vector4.prototype.divide = function (otherVector) {
  3742. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  3743. };
  3744. /**
  3745. * Updates the passed vector "result" with the division result of the current Vector4 by the passed one.
  3746. * Returns the current Vector4.
  3747. */
  3748. Vector4.prototype.divideToRef = function (otherVector, result) {
  3749. result.x = this.x / otherVector.x;
  3750. result.y = this.y / otherVector.y;
  3751. result.z = this.z / otherVector.z;
  3752. result.w = this.w / otherVector.w;
  3753. return this;
  3754. };
  3755. /**
  3756. * Divides the current Vector3 coordinates by the passed ones.
  3757. * @returns the updated Vector3.
  3758. */
  3759. Vector4.prototype.divideInPlace = function (otherVector) {
  3760. return this.divideToRef(otherVector, this);
  3761. };
  3762. /**
  3763. * Updates the Vector4 coordinates with the minimum values between its own and the passed vector ones
  3764. * @param other defines the second operand
  3765. * @returns the current updated Vector4
  3766. */
  3767. Vector4.prototype.minimizeInPlace = function (other) {
  3768. if (other.x < this.x)
  3769. this.x = other.x;
  3770. if (other.y < this.y)
  3771. this.y = other.y;
  3772. if (other.z < this.z)
  3773. this.z = other.z;
  3774. if (other.w < this.w)
  3775. this.w = other.w;
  3776. return this;
  3777. };
  3778. /**
  3779. * Updates the Vector4 coordinates with the maximum values between its own and the passed vector ones
  3780. * @param other defines the second operand
  3781. * @returns the current updated Vector4
  3782. */
  3783. Vector4.prototype.maximizeInPlace = function (other) {
  3784. if (other.x > this.x)
  3785. this.x = other.x;
  3786. if (other.y > this.y)
  3787. this.y = other.y;
  3788. if (other.z > this.z)
  3789. this.z = other.z;
  3790. if (other.w > this.w)
  3791. this.w = other.w;
  3792. return this;
  3793. };
  3794. // Properties
  3795. /**
  3796. * Returns the Vector4 length (float).
  3797. */
  3798. Vector4.prototype.length = function () {
  3799. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  3800. };
  3801. /**
  3802. * Returns the Vector4 squared length (float).
  3803. */
  3804. Vector4.prototype.lengthSquared = function () {
  3805. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  3806. };
  3807. // Methods
  3808. /**
  3809. * Normalizes in place the Vector4.
  3810. * Returns the updated Vector4.
  3811. */
  3812. Vector4.prototype.normalize = function () {
  3813. var len = this.length();
  3814. if (len === 0)
  3815. return this;
  3816. var num = 1.0 / len;
  3817. this.x *= num;
  3818. this.y *= num;
  3819. this.z *= num;
  3820. this.w *= num;
  3821. return this;
  3822. };
  3823. /**
  3824. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  3825. */
  3826. Vector4.prototype.toVector3 = function () {
  3827. return new Vector3(this.x, this.y, this.z);
  3828. };
  3829. /**
  3830. * Returns a new Vector4 copied from the current one.
  3831. */
  3832. Vector4.prototype.clone = function () {
  3833. return new Vector4(this.x, this.y, this.z, this.w);
  3834. };
  3835. /**
  3836. * Updates the current Vector4 with the passed one coordinates.
  3837. * Returns the updated Vector4.
  3838. */
  3839. Vector4.prototype.copyFrom = function (source) {
  3840. this.x = source.x;
  3841. this.y = source.y;
  3842. this.z = source.z;
  3843. this.w = source.w;
  3844. return this;
  3845. };
  3846. /**
  3847. * Updates the current Vector4 coordinates with the passed floats.
  3848. * Returns the updated Vector4.
  3849. */
  3850. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  3851. this.x = x;
  3852. this.y = y;
  3853. this.z = z;
  3854. this.w = w;
  3855. return this;
  3856. };
  3857. /**
  3858. * Updates the current Vector4 coordinates with the passed floats.
  3859. * Returns the updated Vector4.
  3860. */
  3861. Vector4.prototype.set = function (x, y, z, w) {
  3862. return this.copyFromFloats(x, y, z, w);
  3863. };
  3864. // Statics
  3865. /**
  3866. * Returns a new Vector4 set from the starting index of the passed array.
  3867. */
  3868. Vector4.FromArray = function (array, offset) {
  3869. if (!offset) {
  3870. offset = 0;
  3871. }
  3872. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  3873. };
  3874. /**
  3875. * Updates the passed vector "result" from the starting index of the passed array.
  3876. */
  3877. Vector4.FromArrayToRef = function (array, offset, result) {
  3878. result.x = array[offset];
  3879. result.y = array[offset + 1];
  3880. result.z = array[offset + 2];
  3881. result.w = array[offset + 3];
  3882. };
  3883. /**
  3884. * Updates the passed vector "result" from the starting index of the passed Float32Array.
  3885. */
  3886. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  3887. Vector4.FromArrayToRef(array, offset, result);
  3888. };
  3889. /**
  3890. * Updates the passed vector "result" coordinates from the passed floats.
  3891. */
  3892. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  3893. result.x = x;
  3894. result.y = y;
  3895. result.z = z;
  3896. result.w = w;
  3897. };
  3898. /**
  3899. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  3900. */
  3901. Vector4.Zero = function () {
  3902. return new Vector4(0.0, 0.0, 0.0, 0.0);
  3903. };
  3904. /**
  3905. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  3906. */
  3907. Vector4.One = function () {
  3908. return new Vector4(1.0, 1.0, 1.0, 1.0);
  3909. };
  3910. /**
  3911. * Returns a new normalized Vector4 from the passed one.
  3912. */
  3913. Vector4.Normalize = function (vector) {
  3914. var result = Vector4.Zero();
  3915. Vector4.NormalizeToRef(vector, result);
  3916. return result;
  3917. };
  3918. /**
  3919. * Updates the passed vector "result" from the normalization of the passed one.
  3920. */
  3921. Vector4.NormalizeToRef = function (vector, result) {
  3922. result.copyFrom(vector);
  3923. result.normalize();
  3924. };
  3925. Vector4.Minimize = function (left, right) {
  3926. var min = left.clone();
  3927. min.minimizeInPlace(right);
  3928. return min;
  3929. };
  3930. Vector4.Maximize = function (left, right) {
  3931. var max = left.clone();
  3932. max.maximizeInPlace(right);
  3933. return max;
  3934. };
  3935. /**
  3936. * Returns the distance (float) between the vectors "value1" and "value2".
  3937. */
  3938. Vector4.Distance = function (value1, value2) {
  3939. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  3940. };
  3941. /**
  3942. * Returns the squared distance (float) between the vectors "value1" and "value2".
  3943. */
  3944. Vector4.DistanceSquared = function (value1, value2) {
  3945. var x = value1.x - value2.x;
  3946. var y = value1.y - value2.y;
  3947. var z = value1.z - value2.z;
  3948. var w = value1.w - value2.w;
  3949. return (x * x) + (y * y) + (z * z) + (w * w);
  3950. };
  3951. /**
  3952. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  3953. */
  3954. Vector4.Center = function (value1, value2) {
  3955. var center = value1.add(value2);
  3956. center.scaleInPlace(0.5);
  3957. return center;
  3958. };
  3959. /**
  3960. * Returns a new Vector4 set with the result of the normal transformation by the passed matrix of the passed vector.
  3961. * This methods computes transformed normalized direction vectors only.
  3962. */
  3963. Vector4.TransformNormal = function (vector, transformation) {
  3964. var result = Vector4.Zero();
  3965. Vector4.TransformNormalToRef(vector, transformation, result);
  3966. return result;
  3967. };
  3968. /**
  3969. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  3970. * This methods computes transformed normalized direction vectors only.
  3971. */
  3972. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  3973. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3974. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3975. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3976. result.x = x;
  3977. result.y = y;
  3978. result.z = z;
  3979. result.w = vector.w;
  3980. };
  3981. /**
  3982. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z, w).
  3983. * This methods computes transformed normalized direction vectors only.
  3984. */
  3985. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  3986. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3987. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3988. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3989. result.w = w;
  3990. };
  3991. return Vector4;
  3992. }());
  3993. BABYLON.Vector4 = Vector4;
  3994. var Size = /** @class */ (function () {
  3995. /**
  3996. * Creates a Size object from the passed width and height (floats).
  3997. */
  3998. function Size(width, height) {
  3999. this.width = width;
  4000. this.height = height;
  4001. }
  4002. // Returns a string with the Size width and height.
  4003. Size.prototype.toString = function () {
  4004. return "{W: " + this.width + ", H: " + this.height + "}";
  4005. };
  4006. /**
  4007. * Returns the string "Size"
  4008. */
  4009. Size.prototype.getClassName = function () {
  4010. return "Size";
  4011. };
  4012. /**
  4013. * Returns the Size hash code.
  4014. */
  4015. Size.prototype.getHashCode = function () {
  4016. var hash = this.width || 0;
  4017. hash = (hash * 397) ^ (this.height || 0);
  4018. return hash;
  4019. };
  4020. /**
  4021. * Updates the current size from the passed one.
  4022. * Returns the updated Size.
  4023. */
  4024. Size.prototype.copyFrom = function (src) {
  4025. this.width = src.width;
  4026. this.height = src.height;
  4027. };
  4028. /**
  4029. * Updates in place the current Size from the passed floats.
  4030. * Returns the updated Size.
  4031. */
  4032. Size.prototype.copyFromFloats = function (width, height) {
  4033. this.width = width;
  4034. this.height = height;
  4035. return this;
  4036. };
  4037. /**
  4038. * Updates in place the current Size from the passed floats.
  4039. * Returns the updated Size.
  4040. */
  4041. Size.prototype.set = function (width, height) {
  4042. return this.copyFromFloats(width, height);
  4043. };
  4044. /**
  4045. * Returns a new Size set with the multiplication result of the current Size and the passed floats.
  4046. */
  4047. Size.prototype.multiplyByFloats = function (w, h) {
  4048. return new Size(this.width * w, this.height * h);
  4049. };
  4050. /**
  4051. * Returns a new Size copied from the passed one.
  4052. */
  4053. Size.prototype.clone = function () {
  4054. return new Size(this.width, this.height);
  4055. };
  4056. /**
  4057. * Boolean : True if the current Size and the passed one width and height are strictly equal.
  4058. */
  4059. Size.prototype.equals = function (other) {
  4060. if (!other) {
  4061. return false;
  4062. }
  4063. return (this.width === other.width) && (this.height === other.height);
  4064. };
  4065. Object.defineProperty(Size.prototype, "surface", {
  4066. /**
  4067. * Returns the surface of the Size : width * height (float).
  4068. */
  4069. get: function () {
  4070. return this.width * this.height;
  4071. },
  4072. enumerable: true,
  4073. configurable: true
  4074. });
  4075. /**
  4076. * Returns a new Size set to (0.0, 0.0)
  4077. */
  4078. Size.Zero = function () {
  4079. return new Size(0.0, 0.0);
  4080. };
  4081. /**
  4082. * Returns a new Size set as the addition result of the current Size and the passed one.
  4083. */
  4084. Size.prototype.add = function (otherSize) {
  4085. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  4086. return r;
  4087. };
  4088. /**
  4089. * Returns a new Size set as the subtraction result of the passed one from the current Size.
  4090. */
  4091. Size.prototype.subtract = function (otherSize) {
  4092. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  4093. return r;
  4094. };
  4095. /**
  4096. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  4097. */
  4098. Size.Lerp = function (start, end, amount) {
  4099. var w = start.width + ((end.width - start.width) * amount);
  4100. var h = start.height + ((end.height - start.height) * amount);
  4101. return new Size(w, h);
  4102. };
  4103. return Size;
  4104. }());
  4105. BABYLON.Size = Size;
  4106. var Quaternion = /** @class */ (function () {
  4107. /**
  4108. * Creates a new Quaternion from the passed floats.
  4109. */
  4110. function Quaternion(x, y, z, w) {
  4111. if (x === void 0) { x = 0.0; }
  4112. if (y === void 0) { y = 0.0; }
  4113. if (z === void 0) { z = 0.0; }
  4114. if (w === void 0) { w = 1.0; }
  4115. this.x = x;
  4116. this.y = y;
  4117. this.z = z;
  4118. this.w = w;
  4119. }
  4120. /**
  4121. * Returns a string with the Quaternion coordinates.
  4122. */
  4123. Quaternion.prototype.toString = function () {
  4124. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4125. };
  4126. /**
  4127. * Returns the string "Quaternion".
  4128. */
  4129. Quaternion.prototype.getClassName = function () {
  4130. return "Quaternion";
  4131. };
  4132. /**
  4133. * Returns the Quaternion hash code.
  4134. */
  4135. Quaternion.prototype.getHashCode = function () {
  4136. var hash = this.x || 0;
  4137. hash = (hash * 397) ^ (this.y || 0);
  4138. hash = (hash * 397) ^ (this.z || 0);
  4139. hash = (hash * 397) ^ (this.w || 0);
  4140. return hash;
  4141. };
  4142. /**
  4143. * Returns a new array populated with 4 elements : the Quaternion coordinates.
  4144. */
  4145. Quaternion.prototype.asArray = function () {
  4146. return [this.x, this.y, this.z, this.w];
  4147. };
  4148. /**
  4149. * Boolean : True if the current Quaterion and the passed one coordinates are strictly equal.
  4150. */
  4151. Quaternion.prototype.equals = function (otherQuaternion) {
  4152. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4153. };
  4154. /**
  4155. * Returns a new Quaternion copied from the current one.
  4156. */
  4157. Quaternion.prototype.clone = function () {
  4158. return new Quaternion(this.x, this.y, this.z, this.w);
  4159. };
  4160. /**
  4161. * Updates the current Quaternion from the passed one coordinates.
  4162. * Returns the updated Quaterion.
  4163. */
  4164. Quaternion.prototype.copyFrom = function (other) {
  4165. this.x = other.x;
  4166. this.y = other.y;
  4167. this.z = other.z;
  4168. this.w = other.w;
  4169. return this;
  4170. };
  4171. /**
  4172. * Updates the current Quaternion from the passed float coordinates.
  4173. * Returns the updated Quaterion.
  4174. */
  4175. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4176. this.x = x;
  4177. this.y = y;
  4178. this.z = z;
  4179. this.w = w;
  4180. return this;
  4181. };
  4182. /**
  4183. * Updates the current Quaternion from the passed float coordinates.
  4184. * Returns the updated Quaterion.
  4185. */
  4186. Quaternion.prototype.set = function (x, y, z, w) {
  4187. return this.copyFromFloats(x, y, z, w);
  4188. };
  4189. /**
  4190. * Returns a new Quaternion as the addition result of the passed one and the current Quaternion.
  4191. */
  4192. Quaternion.prototype.add = function (other) {
  4193. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4194. };
  4195. /**
  4196. * Returns a new Quaternion as the subtraction result of the passed one from the current Quaternion.
  4197. */
  4198. Quaternion.prototype.subtract = function (other) {
  4199. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4200. };
  4201. /**
  4202. * Returns a new Quaternion set by multiplying the current Quaterion coordinates by the float "scale".
  4203. */
  4204. Quaternion.prototype.scale = function (value) {
  4205. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4206. };
  4207. /**
  4208. * Returns a new Quaternion set as the quaternion mulplication result of the current one with the passed one "q1".
  4209. */
  4210. Quaternion.prototype.multiply = function (q1) {
  4211. var result = new Quaternion(0, 0, 0, 1.0);
  4212. this.multiplyToRef(q1, result);
  4213. return result;
  4214. };
  4215. /**
  4216. * Sets the passed "result" as the quaternion mulplication result of the current one with the passed one "q1".
  4217. * Returns the current Quaternion.
  4218. */
  4219. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4220. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4221. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4222. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4223. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4224. result.copyFromFloats(x, y, z, w);
  4225. return this;
  4226. };
  4227. /**
  4228. * Updates the current Quaternion with the quaternion mulplication result of itself with the passed one "q1".
  4229. * Returns the updated Quaternion.
  4230. */
  4231. Quaternion.prototype.multiplyInPlace = function (q1) {
  4232. this.multiplyToRef(q1, this);
  4233. return this;
  4234. };
  4235. /**
  4236. * Sets the passed "ref" with the conjugation of the current Quaternion.
  4237. * Returns the current Quaternion.
  4238. */
  4239. Quaternion.prototype.conjugateToRef = function (ref) {
  4240. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4241. return this;
  4242. };
  4243. /**
  4244. * Conjugates in place the current Quaternion.
  4245. * Returns the updated Quaternion.
  4246. */
  4247. Quaternion.prototype.conjugateInPlace = function () {
  4248. this.x *= -1;
  4249. this.y *= -1;
  4250. this.z *= -1;
  4251. return this;
  4252. };
  4253. /**
  4254. * Returns a new Quaternion as the conjugate of the current Quaternion.
  4255. */
  4256. Quaternion.prototype.conjugate = function () {
  4257. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4258. return result;
  4259. };
  4260. /**
  4261. * Returns the Quaternion length (float).
  4262. */
  4263. Quaternion.prototype.length = function () {
  4264. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4265. };
  4266. /**
  4267. * Normalize in place the current Quaternion.
  4268. * Returns the updated Quaternion.
  4269. */
  4270. Quaternion.prototype.normalize = function () {
  4271. var length = 1.0 / this.length();
  4272. this.x *= length;
  4273. this.y *= length;
  4274. this.z *= length;
  4275. this.w *= length;
  4276. return this;
  4277. };
  4278. /**
  4279. * Returns a new Vector3 set with the Euler angles translated from the current Quaternion.
  4280. */
  4281. Quaternion.prototype.toEulerAngles = function (order) {
  4282. if (order === void 0) { order = "YZX"; }
  4283. var result = Vector3.Zero();
  4284. this.toEulerAnglesToRef(result, order);
  4285. return result;
  4286. };
  4287. /**
  4288. * Sets the passed vector3 "result" with the Euler angles translated from the current Quaternion.
  4289. * Returns the current Quaternion.
  4290. */
  4291. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4292. if (order === void 0) { order = "YZX"; }
  4293. var qz = this.z;
  4294. var qx = this.x;
  4295. var qy = this.y;
  4296. var qw = this.w;
  4297. var sqw = qw * qw;
  4298. var sqz = qz * qz;
  4299. var sqx = qx * qx;
  4300. var sqy = qy * qy;
  4301. var zAxisY = qy * qz - qx * qw;
  4302. var limit = .4999999;
  4303. if (zAxisY < -limit) {
  4304. result.y = 2 * Math.atan2(qy, qw);
  4305. result.x = Math.PI / 2;
  4306. result.z = 0;
  4307. }
  4308. else if (zAxisY > limit) {
  4309. result.y = 2 * Math.atan2(qy, qw);
  4310. result.x = -Math.PI / 2;
  4311. result.z = 0;
  4312. }
  4313. else {
  4314. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  4315. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  4316. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  4317. }
  4318. return this;
  4319. };
  4320. /**
  4321. * Updates the passed rotation matrix with the current Quaternion values.
  4322. * Returns the current Quaternion.
  4323. */
  4324. Quaternion.prototype.toRotationMatrix = function (result) {
  4325. var xx = this.x * this.x;
  4326. var yy = this.y * this.y;
  4327. var zz = this.z * this.z;
  4328. var xy = this.x * this.y;
  4329. var zw = this.z * this.w;
  4330. var zx = this.z * this.x;
  4331. var yw = this.y * this.w;
  4332. var yz = this.y * this.z;
  4333. var xw = this.x * this.w;
  4334. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4335. result.m[1] = 2.0 * (xy + zw);
  4336. result.m[2] = 2.0 * (zx - yw);
  4337. result.m[3] = 0;
  4338. result.m[4] = 2.0 * (xy - zw);
  4339. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4340. result.m[6] = 2.0 * (yz + xw);
  4341. result.m[7] = 0;
  4342. result.m[8] = 2.0 * (zx + yw);
  4343. result.m[9] = 2.0 * (yz - xw);
  4344. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4345. result.m[11] = 0;
  4346. result.m[12] = 0;
  4347. result.m[13] = 0;
  4348. result.m[14] = 0;
  4349. result.m[15] = 1.0;
  4350. result._markAsUpdated();
  4351. return this;
  4352. };
  4353. /**
  4354. * Updates the current Quaternion from the passed rotation matrix values.
  4355. * Returns the updated Quaternion.
  4356. */
  4357. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  4358. Quaternion.FromRotationMatrixToRef(matrix, this);
  4359. return this;
  4360. };
  4361. // Statics
  4362. /**
  4363. * Returns a new Quaternion set from the passed rotation matrix values.
  4364. */
  4365. Quaternion.FromRotationMatrix = function (matrix) {
  4366. var result = new Quaternion();
  4367. Quaternion.FromRotationMatrixToRef(matrix, result);
  4368. return result;
  4369. };
  4370. /**
  4371. * Updates the passed quaternion "result" with the passed rotation matrix values.
  4372. */
  4373. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  4374. var data = matrix.m;
  4375. var m11 = data[0], m12 = data[4], m13 = data[8];
  4376. var m21 = data[1], m22 = data[5], m23 = data[9];
  4377. var m31 = data[2], m32 = data[6], m33 = data[10];
  4378. var trace = m11 + m22 + m33;
  4379. var s;
  4380. if (trace > 0) {
  4381. s = 0.5 / Math.sqrt(trace + 1.0);
  4382. result.w = 0.25 / s;
  4383. result.x = (m32 - m23) * s;
  4384. result.y = (m13 - m31) * s;
  4385. result.z = (m21 - m12) * s;
  4386. }
  4387. else if (m11 > m22 && m11 > m33) {
  4388. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  4389. result.w = (m32 - m23) / s;
  4390. result.x = 0.25 * s;
  4391. result.y = (m12 + m21) / s;
  4392. result.z = (m13 + m31) / s;
  4393. }
  4394. else if (m22 > m33) {
  4395. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  4396. result.w = (m13 - m31) / s;
  4397. result.x = (m12 + m21) / s;
  4398. result.y = 0.25 * s;
  4399. result.z = (m23 + m32) / s;
  4400. }
  4401. else {
  4402. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  4403. result.w = (m21 - m12) / s;
  4404. result.x = (m13 + m31) / s;
  4405. result.y = (m23 + m32) / s;
  4406. result.z = 0.25 * s;
  4407. }
  4408. };
  4409. /**
  4410. * Returns a new Quaternion set to (0.0, 0.0, 0.0).
  4411. */
  4412. Quaternion.Zero = function () {
  4413. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  4414. };
  4415. /**
  4416. * Returns a new Quaternion as the inverted current Quaternion.
  4417. */
  4418. Quaternion.Inverse = function (q) {
  4419. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  4420. };
  4421. /**
  4422. * Returns the identity Quaternion.
  4423. */
  4424. Quaternion.Identity = function () {
  4425. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  4426. };
  4427. Quaternion.IsIdentity = function (quaternion) {
  4428. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  4429. };
  4430. /**
  4431. * Returns a new Quaternion set from the passed axis (Vector3) and angle in radians (float).
  4432. */
  4433. Quaternion.RotationAxis = function (axis, angle) {
  4434. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  4435. };
  4436. /**
  4437. * Sets the passed quaternion "result" from the passed axis (Vector3) and angle in radians (float).
  4438. */
  4439. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  4440. var sin = Math.sin(angle / 2);
  4441. axis.normalize();
  4442. result.w = Math.cos(angle / 2);
  4443. result.x = axis.x * sin;
  4444. result.y = axis.y * sin;
  4445. result.z = axis.z * sin;
  4446. return result;
  4447. };
  4448. /**
  4449. * Retuns a new Quaternion set from the starting index of the passed array.
  4450. */
  4451. Quaternion.FromArray = function (array, offset) {
  4452. if (!offset) {
  4453. offset = 0;
  4454. }
  4455. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4456. };
  4457. /**
  4458. * Returns a new Quaternion set from the passed Euler float angles (y, x, z).
  4459. */
  4460. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4461. var q = new Quaternion();
  4462. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  4463. return q;
  4464. };
  4465. /**
  4466. * Sets the passed quaternion "result" from the passed float Euler angles (y, x, z).
  4467. */
  4468. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4469. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  4470. var halfRoll = roll * 0.5;
  4471. var halfPitch = pitch * 0.5;
  4472. var halfYaw = yaw * 0.5;
  4473. var sinRoll = Math.sin(halfRoll);
  4474. var cosRoll = Math.cos(halfRoll);
  4475. var sinPitch = Math.sin(halfPitch);
  4476. var cosPitch = Math.cos(halfPitch);
  4477. var sinYaw = Math.sin(halfYaw);
  4478. var cosYaw = Math.cos(halfYaw);
  4479. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  4480. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  4481. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  4482. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  4483. };
  4484. /**
  4485. * Returns a new Quaternion from the passed float Euler angles expressed in z-x-z orientation
  4486. */
  4487. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  4488. var result = new Quaternion();
  4489. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  4490. return result;
  4491. };
  4492. /**
  4493. * Sets the passed quaternion "result" from the passed float Euler angles expressed in z-x-z orientation
  4494. */
  4495. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  4496. // Produces a quaternion from Euler angles in the z-x-z orientation
  4497. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  4498. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  4499. var halfBeta = beta * 0.5;
  4500. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4501. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4502. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4503. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4504. };
  4505. /**
  4506. * Returns a new Quaternion as the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  4507. * cf to Vector3.RotationFromAxis() documentation.
  4508. * Note : axis1, axis2 and axis3 are normalized during this operation.
  4509. */
  4510. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3, ref) {
  4511. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  4512. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  4513. return quat;
  4514. };
  4515. /**
  4516. * Sets the passed quaternion "ref" with the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  4517. * cf to Vector3.RotationFromAxis() documentation.
  4518. * Note : axis1, axis2 and axis3 are normalized during this operation.
  4519. */
  4520. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  4521. var rotMat = MathTmp.Matrix[0];
  4522. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  4523. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  4524. };
  4525. Quaternion.Slerp = function (left, right, amount) {
  4526. var result = Quaternion.Identity();
  4527. Quaternion.SlerpToRef(left, right, amount, result);
  4528. return result;
  4529. };
  4530. Quaternion.SlerpToRef = function (left, right, amount, result) {
  4531. var num2;
  4532. var num3;
  4533. var num = amount;
  4534. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  4535. var flag = false;
  4536. if (num4 < 0) {
  4537. flag = true;
  4538. num4 = -num4;
  4539. }
  4540. if (num4 > 0.999999) {
  4541. num3 = 1 - num;
  4542. num2 = flag ? -num : num;
  4543. }
  4544. else {
  4545. var num5 = Math.acos(num4);
  4546. var num6 = (1.0 / Math.sin(num5));
  4547. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  4548. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  4549. }
  4550. result.x = (num3 * left.x) + (num2 * right.x);
  4551. result.y = (num3 * left.y) + (num2 * right.y);
  4552. result.z = (num3 * left.z) + (num2 * right.z);
  4553. result.w = (num3 * left.w) + (num2 * right.w);
  4554. };
  4555. /**
  4556. * Returns a new Quaternion located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  4557. */
  4558. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  4559. var squared = amount * amount;
  4560. var cubed = amount * squared;
  4561. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  4562. var part2 = (-2.0 * cubed) + (3.0 * squared);
  4563. var part3 = (cubed - (2.0 * squared)) + amount;
  4564. var part4 = cubed - squared;
  4565. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  4566. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  4567. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  4568. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  4569. return new Quaternion(x, y, z, w);
  4570. };
  4571. return Quaternion;
  4572. }());
  4573. BABYLON.Quaternion = Quaternion;
  4574. var Matrix = /** @class */ (function () {
  4575. function Matrix() {
  4576. this._isIdentity = false;
  4577. this._isIdentityDirty = true;
  4578. this.m = new Float32Array(16);
  4579. this._markAsUpdated();
  4580. }
  4581. Matrix.prototype._markAsUpdated = function () {
  4582. this.updateFlag = Matrix._updateFlagSeed++;
  4583. this._isIdentityDirty = true;
  4584. };
  4585. // Properties
  4586. /**
  4587. * Boolean : True is the matrix is the identity matrix
  4588. */
  4589. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  4590. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  4591. if (this._isIdentityDirty) {
  4592. this._isIdentityDirty = false;
  4593. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  4594. this._isIdentity = false;
  4595. }
  4596. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  4597. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  4598. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  4599. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  4600. this._isIdentity = false;
  4601. }
  4602. else {
  4603. this._isIdentity = true;
  4604. }
  4605. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  4606. this._isIdentity = false;
  4607. }
  4608. }
  4609. return this._isIdentity;
  4610. };
  4611. /**
  4612. * Returns the matrix determinant (float).
  4613. */
  4614. Matrix.prototype.determinant = function () {
  4615. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  4616. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  4617. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  4618. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  4619. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  4620. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  4621. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  4622. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  4623. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  4624. };
  4625. // Methods
  4626. /**
  4627. * Returns the matrix underlying array.
  4628. */
  4629. Matrix.prototype.toArray = function () {
  4630. return this.m;
  4631. };
  4632. /**
  4633. * Returns the matrix underlying array.
  4634. */
  4635. Matrix.prototype.asArray = function () {
  4636. return this.toArray();
  4637. };
  4638. /**
  4639. * Inverts in place the Matrix.
  4640. * Returns the Matrix inverted.
  4641. */
  4642. Matrix.prototype.invert = function () {
  4643. this.invertToRef(this);
  4644. return this;
  4645. };
  4646. /**
  4647. * Sets all the matrix elements to zero.
  4648. * Returns the Matrix.
  4649. */
  4650. Matrix.prototype.reset = function () {
  4651. for (var index = 0; index < 16; index++) {
  4652. this.m[index] = 0.0;
  4653. }
  4654. this._markAsUpdated();
  4655. return this;
  4656. };
  4657. /**
  4658. * Returns a new Matrix as the addition result of the current Matrix and the passed one.
  4659. */
  4660. Matrix.prototype.add = function (other) {
  4661. var result = new Matrix();
  4662. this.addToRef(other, result);
  4663. return result;
  4664. };
  4665. /**
  4666. * Sets the passed matrix "result" with the ddition result of the current Matrix and the passed one.
  4667. * Returns the Matrix.
  4668. */
  4669. Matrix.prototype.addToRef = function (other, result) {
  4670. for (var index = 0; index < 16; index++) {
  4671. result.m[index] = this.m[index] + other.m[index];
  4672. }
  4673. result._markAsUpdated();
  4674. return this;
  4675. };
  4676. /**
  4677. * Adds in place the passed matrix to the current Matrix.
  4678. * Returns the updated Matrix.
  4679. */
  4680. Matrix.prototype.addToSelf = function (other) {
  4681. for (var index = 0; index < 16; index++) {
  4682. this.m[index] += other.m[index];
  4683. }
  4684. this._markAsUpdated();
  4685. return this;
  4686. };
  4687. /**
  4688. * Sets the passed matrix with the current inverted Matrix.
  4689. * Returns the unmodified current Matrix.
  4690. */
  4691. Matrix.prototype.invertToRef = function (other) {
  4692. var l1 = this.m[0];
  4693. var l2 = this.m[1];
  4694. var l3 = this.m[2];
  4695. var l4 = this.m[3];
  4696. var l5 = this.m[4];
  4697. var l6 = this.m[5];
  4698. var l7 = this.m[6];
  4699. var l8 = this.m[7];
  4700. var l9 = this.m[8];
  4701. var l10 = this.m[9];
  4702. var l11 = this.m[10];
  4703. var l12 = this.m[11];
  4704. var l13 = this.m[12];
  4705. var l14 = this.m[13];
  4706. var l15 = this.m[14];
  4707. var l16 = this.m[15];
  4708. var l17 = (l11 * l16) - (l12 * l15);
  4709. var l18 = (l10 * l16) - (l12 * l14);
  4710. var l19 = (l10 * l15) - (l11 * l14);
  4711. var l20 = (l9 * l16) - (l12 * l13);
  4712. var l21 = (l9 * l15) - (l11 * l13);
  4713. var l22 = (l9 * l14) - (l10 * l13);
  4714. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  4715. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  4716. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  4717. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  4718. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  4719. var l28 = (l7 * l16) - (l8 * l15);
  4720. var l29 = (l6 * l16) - (l8 * l14);
  4721. var l30 = (l6 * l15) - (l7 * l14);
  4722. var l31 = (l5 * l16) - (l8 * l13);
  4723. var l32 = (l5 * l15) - (l7 * l13);
  4724. var l33 = (l5 * l14) - (l6 * l13);
  4725. var l34 = (l7 * l12) - (l8 * l11);
  4726. var l35 = (l6 * l12) - (l8 * l10);
  4727. var l36 = (l6 * l11) - (l7 * l10);
  4728. var l37 = (l5 * l12) - (l8 * l9);
  4729. var l38 = (l5 * l11) - (l7 * l9);
  4730. var l39 = (l5 * l10) - (l6 * l9);
  4731. other.m[0] = l23 * l27;
  4732. other.m[4] = l24 * l27;
  4733. other.m[8] = l25 * l27;
  4734. other.m[12] = l26 * l27;
  4735. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  4736. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  4737. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  4738. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  4739. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  4740. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  4741. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  4742. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  4743. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  4744. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  4745. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  4746. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  4747. other._markAsUpdated();
  4748. return this;
  4749. };
  4750. /**
  4751. * Inserts the translation vector (using 3 x floats) in the current Matrix.
  4752. * Returns the updated Matrix.
  4753. */
  4754. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  4755. this.m[12] = x;
  4756. this.m[13] = y;
  4757. this.m[14] = z;
  4758. this._markAsUpdated();
  4759. return this;
  4760. };
  4761. /**
  4762. * Inserts the translation vector in the current Matrix.
  4763. * Returns the updated Matrix.
  4764. */
  4765. Matrix.prototype.setTranslation = function (vector3) {
  4766. this.m[12] = vector3.x;
  4767. this.m[13] = vector3.y;
  4768. this.m[14] = vector3.z;
  4769. this._markAsUpdated();
  4770. return this;
  4771. };
  4772. /**
  4773. * Returns a new Vector3 as the extracted translation from the Matrix.
  4774. */
  4775. Matrix.prototype.getTranslation = function () {
  4776. return new Vector3(this.m[12], this.m[13], this.m[14]);
  4777. };
  4778. /**
  4779. * Fill a Vector3 with the extracted translation from the Matrix.
  4780. */
  4781. Matrix.prototype.getTranslationToRef = function (result) {
  4782. result.x = this.m[12];
  4783. result.y = this.m[13];
  4784. result.z = this.m[14];
  4785. return this;
  4786. };
  4787. /**
  4788. * Remove rotation and scaling part from the Matrix.
  4789. * Returns the updated Matrix.
  4790. */
  4791. Matrix.prototype.removeRotationAndScaling = function () {
  4792. this.setRowFromFloats(0, 1, 0, 0, 0);
  4793. this.setRowFromFloats(1, 0, 1, 0, 0);
  4794. this.setRowFromFloats(2, 0, 0, 1, 0);
  4795. return this;
  4796. };
  4797. /**
  4798. * Returns a new Matrix set with the multiplication result of the current Matrix and the passed one.
  4799. */
  4800. Matrix.prototype.multiply = function (other) {
  4801. var result = new Matrix();
  4802. this.multiplyToRef(other, result);
  4803. return result;
  4804. };
  4805. /**
  4806. * Updates the current Matrix from the passed one values.
  4807. * Returns the updated Matrix.
  4808. */
  4809. Matrix.prototype.copyFrom = function (other) {
  4810. for (var index = 0; index < 16; index++) {
  4811. this.m[index] = other.m[index];
  4812. }
  4813. this._markAsUpdated();
  4814. return this;
  4815. };
  4816. /**
  4817. * Populates the passed array from the starting index with the Matrix values.
  4818. * Returns the Matrix.
  4819. */
  4820. Matrix.prototype.copyToArray = function (array, offset) {
  4821. if (offset === void 0) { offset = 0; }
  4822. for (var index = 0; index < 16; index++) {
  4823. array[offset + index] = this.m[index];
  4824. }
  4825. return this;
  4826. };
  4827. /**
  4828. * Sets the passed matrix "result" with the multiplication result of the current Matrix and the passed one.
  4829. */
  4830. Matrix.prototype.multiplyToRef = function (other, result) {
  4831. this.multiplyToArray(other, result.m, 0);
  4832. result._markAsUpdated();
  4833. return this;
  4834. };
  4835. /**
  4836. * Sets the Float32Array "result" from the passed index "offset" with the multiplication result of the current Matrix and the passed one.
  4837. */
  4838. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  4839. var tm0 = this.m[0];
  4840. var tm1 = this.m[1];
  4841. var tm2 = this.m[2];
  4842. var tm3 = this.m[3];
  4843. var tm4 = this.m[4];
  4844. var tm5 = this.m[5];
  4845. var tm6 = this.m[6];
  4846. var tm7 = this.m[7];
  4847. var tm8 = this.m[8];
  4848. var tm9 = this.m[9];
  4849. var tm10 = this.m[10];
  4850. var tm11 = this.m[11];
  4851. var tm12 = this.m[12];
  4852. var tm13 = this.m[13];
  4853. var tm14 = this.m[14];
  4854. var tm15 = this.m[15];
  4855. var om0 = other.m[0];
  4856. var om1 = other.m[1];
  4857. var om2 = other.m[2];
  4858. var om3 = other.m[3];
  4859. var om4 = other.m[4];
  4860. var om5 = other.m[5];
  4861. var om6 = other.m[6];
  4862. var om7 = other.m[7];
  4863. var om8 = other.m[8];
  4864. var om9 = other.m[9];
  4865. var om10 = other.m[10];
  4866. var om11 = other.m[11];
  4867. var om12 = other.m[12];
  4868. var om13 = other.m[13];
  4869. var om14 = other.m[14];
  4870. var om15 = other.m[15];
  4871. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  4872. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  4873. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  4874. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  4875. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  4876. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  4877. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  4878. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  4879. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  4880. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  4881. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  4882. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  4883. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  4884. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  4885. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  4886. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  4887. return this;
  4888. };
  4889. /**
  4890. * Boolean : True is the current Matrix and the passed one values are strictly equal.
  4891. */
  4892. Matrix.prototype.equals = function (value) {
  4893. return value &&
  4894. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  4895. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  4896. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  4897. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  4898. };
  4899. /**
  4900. * Returns a new Matrix from the current Matrix.
  4901. */
  4902. Matrix.prototype.clone = function () {
  4903. 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]);
  4904. };
  4905. /**
  4906. * Returns the string "Matrix"
  4907. */
  4908. Matrix.prototype.getClassName = function () {
  4909. return "Matrix";
  4910. };
  4911. /**
  4912. * Returns the Matrix hash code.
  4913. */
  4914. Matrix.prototype.getHashCode = function () {
  4915. var hash = this.m[0] || 0;
  4916. for (var i = 1; i < 16; i++) {
  4917. hash = (hash * 397) ^ (this.m[i] || 0);
  4918. }
  4919. return hash;
  4920. };
  4921. /**
  4922. * Decomposes the current Matrix into :
  4923. * - a scale vector3 passed as a reference to update,
  4924. * - a rotation quaternion passed as a reference to update,
  4925. * - a translation vector3 passed as a reference to update.
  4926. * Returns the true if operation was successful.
  4927. */
  4928. Matrix.prototype.decompose = function (scale, rotation, translation) {
  4929. translation.x = this.m[12];
  4930. translation.y = this.m[13];
  4931. translation.z = this.m[14];
  4932. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  4933. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  4934. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  4935. if (this.determinant() <= 0) {
  4936. scale.y *= -1;
  4937. }
  4938. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  4939. rotation.x = 0;
  4940. rotation.y = 0;
  4941. rotation.z = 0;
  4942. rotation.w = 1;
  4943. return false;
  4944. }
  4945. 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]);
  4946. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  4947. return true;
  4948. };
  4949. /**
  4950. * Returns a new Matrix as the extracted rotation matrix from the current one.
  4951. */
  4952. Matrix.prototype.getRotationMatrix = function () {
  4953. var result = Matrix.Identity();
  4954. this.getRotationMatrixToRef(result);
  4955. return result;
  4956. };
  4957. /**
  4958. * Extracts the rotation matrix from the current one and sets it as the passed "result".
  4959. * Returns the current Matrix.
  4960. */
  4961. Matrix.prototype.getRotationMatrixToRef = function (result) {
  4962. var m = this.m;
  4963. var xs = m[0] * m[1] * m[2] * m[3] < 0 ? -1 : 1;
  4964. var ys = m[4] * m[5] * m[6] * m[7] < 0 ? -1 : 1;
  4965. var zs = m[8] * m[9] * m[10] * m[11] < 0 ? -1 : 1;
  4966. var sx = xs * Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  4967. var sy = ys * Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  4968. var sz = zs * Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  4969. 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);
  4970. return this;
  4971. };
  4972. // Statics
  4973. /**
  4974. * Returns a new Matrix set from the starting index of the passed array.
  4975. */
  4976. Matrix.FromArray = function (array, offset) {
  4977. var result = new Matrix();
  4978. if (!offset) {
  4979. offset = 0;
  4980. }
  4981. Matrix.FromArrayToRef(array, offset, result);
  4982. return result;
  4983. };
  4984. /**
  4985. * Sets the passed "result" matrix from the starting index of the passed array.
  4986. */
  4987. Matrix.FromArrayToRef = function (array, offset, result) {
  4988. for (var index = 0; index < 16; index++) {
  4989. result.m[index] = array[index + offset];
  4990. }
  4991. result._markAsUpdated();
  4992. };
  4993. /**
  4994. * Sets the passed "result" matrix from the starting index of the passed Float32Array by multiplying each element by the float "scale".
  4995. */
  4996. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  4997. for (var index = 0; index < 16; index++) {
  4998. result.m[index] = array[index + offset] * scale;
  4999. }
  5000. result._markAsUpdated();
  5001. };
  5002. /**
  5003. * Sets the passed matrix "result" with the 16 passed floats.
  5004. */
  5005. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5006. result.m[0] = initialM11;
  5007. result.m[1] = initialM12;
  5008. result.m[2] = initialM13;
  5009. result.m[3] = initialM14;
  5010. result.m[4] = initialM21;
  5011. result.m[5] = initialM22;
  5012. result.m[6] = initialM23;
  5013. result.m[7] = initialM24;
  5014. result.m[8] = initialM31;
  5015. result.m[9] = initialM32;
  5016. result.m[10] = initialM33;
  5017. result.m[11] = initialM34;
  5018. result.m[12] = initialM41;
  5019. result.m[13] = initialM42;
  5020. result.m[14] = initialM43;
  5021. result.m[15] = initialM44;
  5022. result._markAsUpdated();
  5023. };
  5024. /**
  5025. * Returns the index-th row of the current matrix as a new Vector4.
  5026. */
  5027. Matrix.prototype.getRow = function (index) {
  5028. if (index < 0 || index > 3) {
  5029. return null;
  5030. }
  5031. var i = index * 4;
  5032. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5033. };
  5034. /**
  5035. * Sets the index-th row of the current matrix with the passed Vector4 values.
  5036. * Returns the updated Matrix.
  5037. */
  5038. Matrix.prototype.setRow = function (index, row) {
  5039. if (index < 0 || index > 3) {
  5040. return this;
  5041. }
  5042. var i = index * 4;
  5043. this.m[i + 0] = row.x;
  5044. this.m[i + 1] = row.y;
  5045. this.m[i + 2] = row.z;
  5046. this.m[i + 3] = row.w;
  5047. this._markAsUpdated();
  5048. return this;
  5049. };
  5050. /**
  5051. * Compute the transpose of the matrix.
  5052. * Returns a new Matrix.
  5053. */
  5054. Matrix.prototype.transpose = function () {
  5055. return Matrix.Transpose(this);
  5056. };
  5057. /**
  5058. * Compute the transpose of the matrix.
  5059. * Returns the current matrix.
  5060. */
  5061. Matrix.prototype.transposeToRef = function (result) {
  5062. Matrix.TransposeToRef(this, result);
  5063. return this;
  5064. };
  5065. /**
  5066. * Sets the index-th row of the current matrix with the passed 4 x float values.
  5067. * Returns the updated Matrix.
  5068. */
  5069. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5070. if (index < 0 || index > 3) {
  5071. return this;
  5072. }
  5073. var i = index * 4;
  5074. this.m[i + 0] = x;
  5075. this.m[i + 1] = y;
  5076. this.m[i + 2] = z;
  5077. this.m[i + 3] = w;
  5078. this._markAsUpdated();
  5079. return this;
  5080. };
  5081. Object.defineProperty(Matrix, "IdentityReadOnly", {
  5082. /**
  5083. * Static identity matrix to be used as readonly matrix
  5084. * Must not be updated.
  5085. */
  5086. get: function () {
  5087. return Matrix._identityReadOnly;
  5088. },
  5089. enumerable: true,
  5090. configurable: true
  5091. });
  5092. /**
  5093. * Returns a new Matrix set from the 16 passed floats.
  5094. */
  5095. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  5096. var result = new Matrix();
  5097. result.m[0] = initialM11;
  5098. result.m[1] = initialM12;
  5099. result.m[2] = initialM13;
  5100. result.m[3] = initialM14;
  5101. result.m[4] = initialM21;
  5102. result.m[5] = initialM22;
  5103. result.m[6] = initialM23;
  5104. result.m[7] = initialM24;
  5105. result.m[8] = initialM31;
  5106. result.m[9] = initialM32;
  5107. result.m[10] = initialM33;
  5108. result.m[11] = initialM34;
  5109. result.m[12] = initialM41;
  5110. result.m[13] = initialM42;
  5111. result.m[14] = initialM43;
  5112. result.m[15] = initialM44;
  5113. return result;
  5114. };
  5115. /**
  5116. * Returns a new Matrix composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  5117. */
  5118. Matrix.Compose = function (scale, rotation, translation) {
  5119. var result = Matrix.Identity();
  5120. Matrix.ComposeToRef(scale, rotation, translation, result);
  5121. return result;
  5122. };
  5123. /**
  5124. * Update a Matrix with values composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  5125. */
  5126. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  5127. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  5128. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  5129. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  5130. result.setTranslation(translation);
  5131. };
  5132. /**
  5133. * Returns a new indentity Matrix.
  5134. */
  5135. Matrix.Identity = function () {
  5136. 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);
  5137. };
  5138. /**
  5139. * Sets the passed "result" as an identity matrix.
  5140. */
  5141. Matrix.IdentityToRef = function (result) {
  5142. 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);
  5143. };
  5144. /**
  5145. * Returns a new zero Matrix.
  5146. */
  5147. Matrix.Zero = function () {
  5148. 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);
  5149. };
  5150. /**
  5151. * Returns a new rotation matrix for "angle" radians around the X axis.
  5152. */
  5153. Matrix.RotationX = function (angle) {
  5154. var result = new Matrix();
  5155. Matrix.RotationXToRef(angle, result);
  5156. return result;
  5157. };
  5158. /**
  5159. * Returns a new Matrix as the passed inverted one.
  5160. */
  5161. Matrix.Invert = function (source) {
  5162. var result = new Matrix();
  5163. source.invertToRef(result);
  5164. return result;
  5165. };
  5166. /**
  5167. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the X axis.
  5168. */
  5169. Matrix.RotationXToRef = function (angle, result) {
  5170. var s = Math.sin(angle);
  5171. var c = Math.cos(angle);
  5172. result.m[0] = 1.0;
  5173. result.m[15] = 1.0;
  5174. result.m[5] = c;
  5175. result.m[10] = c;
  5176. result.m[9] = -s;
  5177. result.m[6] = s;
  5178. result.m[1] = 0.0;
  5179. result.m[2] = 0.0;
  5180. result.m[3] = 0.0;
  5181. result.m[4] = 0.0;
  5182. result.m[7] = 0.0;
  5183. result.m[8] = 0.0;
  5184. result.m[11] = 0.0;
  5185. result.m[12] = 0.0;
  5186. result.m[13] = 0.0;
  5187. result.m[14] = 0.0;
  5188. result._markAsUpdated();
  5189. };
  5190. /**
  5191. * Returns a new rotation matrix for "angle" radians around the Y axis.
  5192. */
  5193. Matrix.RotationY = function (angle) {
  5194. var result = new Matrix();
  5195. Matrix.RotationYToRef(angle, result);
  5196. return result;
  5197. };
  5198. /**
  5199. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Y axis.
  5200. */
  5201. Matrix.RotationYToRef = function (angle, result) {
  5202. var s = Math.sin(angle);
  5203. var c = Math.cos(angle);
  5204. result.m[5] = 1.0;
  5205. result.m[15] = 1.0;
  5206. result.m[0] = c;
  5207. result.m[2] = -s;
  5208. result.m[8] = s;
  5209. result.m[10] = c;
  5210. result.m[1] = 0.0;
  5211. result.m[3] = 0.0;
  5212. result.m[4] = 0.0;
  5213. result.m[6] = 0.0;
  5214. result.m[7] = 0.0;
  5215. result.m[9] = 0.0;
  5216. result.m[11] = 0.0;
  5217. result.m[12] = 0.0;
  5218. result.m[13] = 0.0;
  5219. result.m[14] = 0.0;
  5220. result._markAsUpdated();
  5221. };
  5222. /**
  5223. * Returns a new rotation matrix for "angle" radians around the Z axis.
  5224. */
  5225. Matrix.RotationZ = function (angle) {
  5226. var result = new Matrix();
  5227. Matrix.RotationZToRef(angle, result);
  5228. return result;
  5229. };
  5230. /**
  5231. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Z axis.
  5232. */
  5233. Matrix.RotationZToRef = function (angle, result) {
  5234. var s = Math.sin(angle);
  5235. var c = Math.cos(angle);
  5236. result.m[10] = 1.0;
  5237. result.m[15] = 1.0;
  5238. result.m[0] = c;
  5239. result.m[1] = s;
  5240. result.m[4] = -s;
  5241. result.m[5] = c;
  5242. result.m[2] = 0.0;
  5243. result.m[3] = 0.0;
  5244. result.m[6] = 0.0;
  5245. result.m[7] = 0.0;
  5246. result.m[8] = 0.0;
  5247. result.m[9] = 0.0;
  5248. result.m[11] = 0.0;
  5249. result.m[12] = 0.0;
  5250. result.m[13] = 0.0;
  5251. result.m[14] = 0.0;
  5252. result._markAsUpdated();
  5253. };
  5254. /**
  5255. * Returns a new rotation matrix for "angle" radians around the passed axis.
  5256. */
  5257. Matrix.RotationAxis = function (axis, angle) {
  5258. var result = Matrix.Zero();
  5259. Matrix.RotationAxisToRef(axis, angle, result);
  5260. return result;
  5261. };
  5262. /**
  5263. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the passed axis.
  5264. */
  5265. Matrix.RotationAxisToRef = function (axis, angle, result) {
  5266. var s = Math.sin(-angle);
  5267. var c = Math.cos(-angle);
  5268. var c1 = 1 - c;
  5269. axis.normalize();
  5270. result.m[0] = (axis.x * axis.x) * c1 + c;
  5271. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  5272. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  5273. result.m[3] = 0.0;
  5274. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  5275. result.m[5] = (axis.y * axis.y) * c1 + c;
  5276. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  5277. result.m[7] = 0.0;
  5278. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  5279. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  5280. result.m[10] = (axis.z * axis.z) * c1 + c;
  5281. result.m[11] = 0.0;
  5282. result.m[15] = 1.0;
  5283. result._markAsUpdated();
  5284. };
  5285. /**
  5286. * Returns a new Matrix as a rotation matrix from the Euler angles (y, x, z).
  5287. */
  5288. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  5289. var result = new Matrix();
  5290. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  5291. return result;
  5292. };
  5293. /**
  5294. * Sets the passed matrix "result" as a rotation matrix from the Euler angles (y, x, z).
  5295. */
  5296. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  5297. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  5298. this._tempQuaternion.toRotationMatrix(result);
  5299. };
  5300. /**
  5301. * Returns a new Matrix as a scaling matrix from the passed floats (x, y, z).
  5302. */
  5303. Matrix.Scaling = function (x, y, z) {
  5304. var result = Matrix.Zero();
  5305. Matrix.ScalingToRef(x, y, z, result);
  5306. return result;
  5307. };
  5308. /**
  5309. * Sets the passed matrix "result" as a scaling matrix from the passed floats (x, y, z).
  5310. */
  5311. Matrix.ScalingToRef = function (x, y, z, result) {
  5312. result.m[0] = x;
  5313. result.m[1] = 0.0;
  5314. result.m[2] = 0.0;
  5315. result.m[3] = 0.0;
  5316. result.m[4] = 0.0;
  5317. result.m[5] = y;
  5318. result.m[6] = 0.0;
  5319. result.m[7] = 0.0;
  5320. result.m[8] = 0.0;
  5321. result.m[9] = 0.0;
  5322. result.m[10] = z;
  5323. result.m[11] = 0.0;
  5324. result.m[12] = 0.0;
  5325. result.m[13] = 0.0;
  5326. result.m[14] = 0.0;
  5327. result.m[15] = 1.0;
  5328. result._markAsUpdated();
  5329. };
  5330. /**
  5331. * Returns a new Matrix as a translation matrix from the passed floats (x, y, z).
  5332. */
  5333. Matrix.Translation = function (x, y, z) {
  5334. var result = Matrix.Identity();
  5335. Matrix.TranslationToRef(x, y, z, result);
  5336. return result;
  5337. };
  5338. /**
  5339. * Sets the passed matrix "result" as a translation matrix from the passed floats (x, y, z).
  5340. */
  5341. Matrix.TranslationToRef = function (x, y, z, result) {
  5342. 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);
  5343. };
  5344. /**
  5345. * Returns a new Matrix whose values are the interpolated values for "gradien" (float) between the ones of the matrices "startValue" and "endValue".
  5346. */
  5347. Matrix.Lerp = function (startValue, endValue, gradient) {
  5348. var result = Matrix.Zero();
  5349. for (var index = 0; index < 16; index++) {
  5350. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  5351. }
  5352. result._markAsUpdated();
  5353. return result;
  5354. };
  5355. /**
  5356. * Returns a new Matrix whose values are computed by :
  5357. * - decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices,
  5358. * - interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end,
  5359. * - recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices.
  5360. */
  5361. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  5362. var startScale = new Vector3(0, 0, 0);
  5363. var startRotation = new Quaternion();
  5364. var startTranslation = new Vector3(0, 0, 0);
  5365. startValue.decompose(startScale, startRotation, startTranslation);
  5366. var endScale = new Vector3(0, 0, 0);
  5367. var endRotation = new Quaternion();
  5368. var endTranslation = new Vector3(0, 0, 0);
  5369. endValue.decompose(endScale, endRotation, endTranslation);
  5370. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  5371. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  5372. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  5373. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  5374. };
  5375. /**
  5376. * Returns a new rotation Matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  5377. * This methods works for a Left-Handed system.
  5378. */
  5379. Matrix.LookAtLH = function (eye, target, up) {
  5380. var result = Matrix.Zero();
  5381. Matrix.LookAtLHToRef(eye, target, up, result);
  5382. return result;
  5383. };
  5384. /**
  5385. * Sets the passed "result" Matrix as a rotation matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  5386. * This methods works for a Left-Handed system.
  5387. */
  5388. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  5389. // Z axis
  5390. target.subtractToRef(eye, this._zAxis);
  5391. this._zAxis.normalize();
  5392. // X axis
  5393. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  5394. if (this._xAxis.lengthSquared() === 0) {
  5395. this._xAxis.x = 1.0;
  5396. }
  5397. else {
  5398. this._xAxis.normalize();
  5399. }
  5400. // Y axis
  5401. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  5402. this._yAxis.normalize();
  5403. // Eye angles
  5404. var ex = -Vector3.Dot(this._xAxis, eye);
  5405. var ey = -Vector3.Dot(this._yAxis, eye);
  5406. var ez = -Vector3.Dot(this._zAxis, eye);
  5407. 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);
  5408. };
  5409. /**
  5410. * Returns a new rotation Matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  5411. * This methods works for a Right-Handed system.
  5412. */
  5413. Matrix.LookAtRH = function (eye, target, up) {
  5414. var result = Matrix.Zero();
  5415. Matrix.LookAtRHToRef(eye, target, up, result);
  5416. return result;
  5417. };
  5418. /**
  5419. * Sets the passed "result" Matrix as a rotation matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  5420. * This methods works for a Left-Handed system.
  5421. */
  5422. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  5423. // Z axis
  5424. eye.subtractToRef(target, this._zAxis);
  5425. this._zAxis.normalize();
  5426. // X axis
  5427. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  5428. if (this._xAxis.lengthSquared() === 0) {
  5429. this._xAxis.x = 1.0;
  5430. }
  5431. else {
  5432. this._xAxis.normalize();
  5433. }
  5434. // Y axis
  5435. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  5436. this._yAxis.normalize();
  5437. // Eye angles
  5438. var ex = -Vector3.Dot(this._xAxis, eye);
  5439. var ey = -Vector3.Dot(this._yAxis, eye);
  5440. var ez = -Vector3.Dot(this._zAxis, eye);
  5441. 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);
  5442. };
  5443. /**
  5444. * Returns a new Matrix as a left-handed orthographic projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
  5445. */
  5446. Matrix.OrthoLH = function (width, height, znear, zfar) {
  5447. var matrix = Matrix.Zero();
  5448. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  5449. return matrix;
  5450. };
  5451. /**
  5452. * Sets the passed matrix "result" as a left-handed orthographic projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
  5453. */
  5454. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  5455. var n = znear;
  5456. var f = zfar;
  5457. var a = 2.0 / width;
  5458. var b = 2.0 / height;
  5459. var c = 2.0 / (f - n);
  5460. var d = -(f + n) / (f - n);
  5461. 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);
  5462. };
  5463. /**
  5464. * Returns a new Matrix as a left-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  5465. */
  5466. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  5467. var matrix = Matrix.Zero();
  5468. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  5469. return matrix;
  5470. };
  5471. /**
  5472. * Sets the passed matrix "result" as a left-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  5473. */
  5474. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  5475. var n = znear;
  5476. var f = zfar;
  5477. var a = 2.0 / (right - left);
  5478. var b = 2.0 / (top - bottom);
  5479. var c = 2.0 / (f - n);
  5480. var d = -(f + n) / (f - n);
  5481. var i0 = (left + right) / (left - right);
  5482. var i1 = (top + bottom) / (bottom - top);
  5483. 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);
  5484. };
  5485. /**
  5486. * Returns a new Matrix as a right-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  5487. */
  5488. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  5489. var matrix = Matrix.Zero();
  5490. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  5491. return matrix;
  5492. };
  5493. /**
  5494. * Sets the passed matrix "result" as a right-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  5495. */
  5496. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  5497. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  5498. result.m[10] *= -1.0;
  5499. };
  5500. /**
  5501. * Returns a new Matrix as a left-handed perspective projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
  5502. */
  5503. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  5504. var matrix = Matrix.Zero();
  5505. var n = znear;
  5506. var f = zfar;
  5507. var a = 2.0 * n / width;
  5508. var b = 2.0 * n / height;
  5509. var c = (f + n) / (f - n);
  5510. var d = -2.0 * f * n / (f - n);
  5511. 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);
  5512. return matrix;
  5513. };
  5514. /**
  5515. * Returns a new Matrix as a left-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  5516. */
  5517. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  5518. var matrix = Matrix.Zero();
  5519. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  5520. return matrix;
  5521. };
  5522. /**
  5523. * Sets the passed matrix "result" as a left-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  5524. */
  5525. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  5526. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  5527. var n = znear;
  5528. var f = zfar;
  5529. var t = 1.0 / (Math.tan(fov * 0.5));
  5530. var a = isVerticalFovFixed ? (t / aspect) : t;
  5531. var b = isVerticalFovFixed ? t : (t * aspect);
  5532. var c = (f + n) / (f - n);
  5533. var d = -2.0 * f * n / (f - n);
  5534. 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);
  5535. };
  5536. /**
  5537. * Returns a new Matrix as a right-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  5538. */
  5539. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  5540. var matrix = Matrix.Zero();
  5541. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  5542. return matrix;
  5543. };
  5544. /**
  5545. * Sets the passed matrix "result" as a right-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  5546. */
  5547. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  5548. //alternatively this could be expressed as:
  5549. // m = PerspectiveFovLHToRef
  5550. // m[10] *= -1.0;
  5551. // m[11] *= -1.0;
  5552. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  5553. var n = znear;
  5554. var f = zfar;
  5555. var t = 1.0 / (Math.tan(fov * 0.5));
  5556. var a = isVerticalFovFixed ? (t / aspect) : t;
  5557. var b = isVerticalFovFixed ? t : (t * aspect);
  5558. var c = -(f + n) / (f - n);
  5559. var d = -2 * f * n / (f - n);
  5560. 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);
  5561. };
  5562. /**
  5563. * Sets the passed matrix "result" as a left-handed perspective projection matrix for WebVR computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  5564. */
  5565. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  5566. if (rightHanded === void 0) { rightHanded = false; }
  5567. var rightHandedFactor = rightHanded ? -1 : 1;
  5568. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  5569. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  5570. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  5571. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  5572. var xScale = 2.0 / (leftTan + rightTan);
  5573. var yScale = 2.0 / (upTan + downTan);
  5574. result.m[0] = xScale;
  5575. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  5576. result.m[5] = yScale;
  5577. result.m[6] = result.m[7] = 0.0;
  5578. result.m[8] = ((leftTan - rightTan) * xScale * 0.5); // * rightHandedFactor;
  5579. result.m[9] = -((upTan - downTan) * yScale * 0.5); // * rightHandedFactor;
  5580. //result.m[10] = -(znear + zfar) / (zfar - znear) * rightHandedFactor;
  5581. result.m[10] = -zfar / (znear - zfar);
  5582. result.m[11] = 1.0 * rightHandedFactor;
  5583. result.m[12] = result.m[13] = result.m[15] = 0.0;
  5584. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  5585. // result.m[14] = (znear * zfar) / (znear - zfar);
  5586. result._markAsUpdated();
  5587. };
  5588. /**
  5589. * Returns the final transformation matrix : world * view * projection * viewport
  5590. */
  5591. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  5592. var cw = viewport.width;
  5593. var ch = viewport.height;
  5594. var cx = viewport.x;
  5595. var cy = viewport.y;
  5596. 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);
  5597. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  5598. };
  5599. /**
  5600. * Returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the passed Matrix.
  5601. */
  5602. Matrix.GetAsMatrix2x2 = function (matrix) {
  5603. return new Float32Array([
  5604. matrix.m[0], matrix.m[1],
  5605. matrix.m[4], matrix.m[5]
  5606. ]);
  5607. };
  5608. /**
  5609. * Returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the passed Matrix.
  5610. */
  5611. Matrix.GetAsMatrix3x3 = function (matrix) {
  5612. return new Float32Array([
  5613. matrix.m[0], matrix.m[1], matrix.m[2],
  5614. matrix.m[4], matrix.m[5], matrix.m[6],
  5615. matrix.m[8], matrix.m[9], matrix.m[10]
  5616. ]);
  5617. };
  5618. /**
  5619. * Compute the transpose of the passed Matrix.
  5620. * Returns a new Matrix.
  5621. */
  5622. Matrix.Transpose = function (matrix) {
  5623. var result = new Matrix();
  5624. Matrix.TransposeToRef(matrix, result);
  5625. return result;
  5626. };
  5627. /**
  5628. * Compute the transpose of the passed Matrix and store it in the result matrix.
  5629. */
  5630. Matrix.TransposeToRef = function (matrix, result) {
  5631. result.m[0] = matrix.m[0];
  5632. result.m[1] = matrix.m[4];
  5633. result.m[2] = matrix.m[8];
  5634. result.m[3] = matrix.m[12];
  5635. result.m[4] = matrix.m[1];
  5636. result.m[5] = matrix.m[5];
  5637. result.m[6] = matrix.m[9];
  5638. result.m[7] = matrix.m[13];
  5639. result.m[8] = matrix.m[2];
  5640. result.m[9] = matrix.m[6];
  5641. result.m[10] = matrix.m[10];
  5642. result.m[11] = matrix.m[14];
  5643. result.m[12] = matrix.m[3];
  5644. result.m[13] = matrix.m[7];
  5645. result.m[14] = matrix.m[11];
  5646. result.m[15] = matrix.m[15];
  5647. };
  5648. /**
  5649. * Returns a new Matrix as the reflection matrix across the passed plane.
  5650. */
  5651. Matrix.Reflection = function (plane) {
  5652. var matrix = new Matrix();
  5653. Matrix.ReflectionToRef(plane, matrix);
  5654. return matrix;
  5655. };
  5656. /**
  5657. * Sets the passed matrix "result" as the reflection matrix across the passed plane.
  5658. */
  5659. Matrix.ReflectionToRef = function (plane, result) {
  5660. plane.normalize();
  5661. var x = plane.normal.x;
  5662. var y = plane.normal.y;
  5663. var z = plane.normal.z;
  5664. var temp = -2 * x;
  5665. var temp2 = -2 * y;
  5666. var temp3 = -2 * z;
  5667. result.m[0] = (temp * x) + 1;
  5668. result.m[1] = temp2 * x;
  5669. result.m[2] = temp3 * x;
  5670. result.m[3] = 0.0;
  5671. result.m[4] = temp * y;
  5672. result.m[5] = (temp2 * y) + 1;
  5673. result.m[6] = temp3 * y;
  5674. result.m[7] = 0.0;
  5675. result.m[8] = temp * z;
  5676. result.m[9] = temp2 * z;
  5677. result.m[10] = (temp3 * z) + 1;
  5678. result.m[11] = 0.0;
  5679. result.m[12] = temp * plane.d;
  5680. result.m[13] = temp2 * plane.d;
  5681. result.m[14] = temp3 * plane.d;
  5682. result.m[15] = 1.0;
  5683. result._markAsUpdated();
  5684. };
  5685. /**
  5686. * Sets the passed matrix "mat" as a rotation matrix composed from the 3 passed left handed axis.
  5687. */
  5688. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  5689. result.m[0] = xaxis.x;
  5690. result.m[1] = xaxis.y;
  5691. result.m[2] = xaxis.z;
  5692. result.m[3] = 0.0;
  5693. result.m[4] = yaxis.x;
  5694. result.m[5] = yaxis.y;
  5695. result.m[6] = yaxis.z;
  5696. result.m[7] = 0.0;
  5697. result.m[8] = zaxis.x;
  5698. result.m[9] = zaxis.y;
  5699. result.m[10] = zaxis.z;
  5700. result.m[11] = 0.0;
  5701. result.m[12] = 0.0;
  5702. result.m[13] = 0.0;
  5703. result.m[14] = 0.0;
  5704. result.m[15] = 1.0;
  5705. result._markAsUpdated();
  5706. };
  5707. /**
  5708. * Sets the passed matrix "result" as a rotation matrix according to the passed quaternion.
  5709. */
  5710. Matrix.FromQuaternionToRef = function (quat, result) {
  5711. var xx = quat.x * quat.x;
  5712. var yy = quat.y * quat.y;
  5713. var zz = quat.z * quat.z;
  5714. var xy = quat.x * quat.y;
  5715. var zw = quat.z * quat.w;
  5716. var zx = quat.z * quat.x;
  5717. var yw = quat.y * quat.w;
  5718. var yz = quat.y * quat.z;
  5719. var xw = quat.x * quat.w;
  5720. result.m[0] = 1.0 - (2.0 * (yy + zz));
  5721. result.m[1] = 2.0 * (xy + zw);
  5722. result.m[2] = 2.0 * (zx - yw);
  5723. result.m[3] = 0.0;
  5724. result.m[4] = 2.0 * (xy - zw);
  5725. result.m[5] = 1.0 - (2.0 * (zz + xx));
  5726. result.m[6] = 2.0 * (yz + xw);
  5727. result.m[7] = 0.0;
  5728. result.m[8] = 2.0 * (zx + yw);
  5729. result.m[9] = 2.0 * (yz - xw);
  5730. result.m[10] = 1.0 - (2.0 * (yy + xx));
  5731. result.m[11] = 0.0;
  5732. result.m[12] = 0.0;
  5733. result.m[13] = 0.0;
  5734. result.m[14] = 0.0;
  5735. result.m[15] = 1.0;
  5736. result._markAsUpdated();
  5737. };
  5738. Matrix._tempQuaternion = new Quaternion();
  5739. Matrix._xAxis = Vector3.Zero();
  5740. Matrix._yAxis = Vector3.Zero();
  5741. Matrix._zAxis = Vector3.Zero();
  5742. Matrix._updateFlagSeed = 0;
  5743. Matrix._identityReadOnly = Matrix.Identity();
  5744. return Matrix;
  5745. }());
  5746. BABYLON.Matrix = Matrix;
  5747. var Plane = /** @class */ (function () {
  5748. /**
  5749. * Creates a Plane object according to the passed floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  5750. */
  5751. function Plane(a, b, c, d) {
  5752. this.normal = new Vector3(a, b, c);
  5753. this.d = d;
  5754. }
  5755. /**
  5756. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  5757. */
  5758. Plane.prototype.asArray = function () {
  5759. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  5760. };
  5761. // Methods
  5762. /**
  5763. * Returns a new plane copied from the current Plane.
  5764. */
  5765. Plane.prototype.clone = function () {
  5766. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  5767. };
  5768. /**
  5769. * Returns the string "Plane".
  5770. */
  5771. Plane.prototype.getClassName = function () {
  5772. return "Plane";
  5773. };
  5774. /**
  5775. * Returns the Plane hash code.
  5776. */
  5777. Plane.prototype.getHashCode = function () {
  5778. var hash = this.normal.getHashCode();
  5779. hash = (hash * 397) ^ (this.d || 0);
  5780. return hash;
  5781. };
  5782. /**
  5783. * Normalize the current Plane in place.
  5784. * Returns the updated Plane.
  5785. */
  5786. Plane.prototype.normalize = function () {
  5787. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  5788. var magnitude = 0.0;
  5789. if (norm !== 0) {
  5790. magnitude = 1.0 / norm;
  5791. }
  5792. this.normal.x *= magnitude;
  5793. this.normal.y *= magnitude;
  5794. this.normal.z *= magnitude;
  5795. this.d *= magnitude;
  5796. return this;
  5797. };
  5798. /**
  5799. * Returns a new Plane as the result of the transformation of the current Plane by the passed matrix.
  5800. */
  5801. Plane.prototype.transform = function (transformation) {
  5802. var transposedMatrix = Matrix.Transpose(transformation);
  5803. var x = this.normal.x;
  5804. var y = this.normal.y;
  5805. var z = this.normal.z;
  5806. var d = this.d;
  5807. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  5808. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  5809. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  5810. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  5811. return new Plane(normalX, normalY, normalZ, finalD);
  5812. };
  5813. /**
  5814. * Returns the dot product (float) of the point coordinates and the plane normal.
  5815. */
  5816. Plane.prototype.dotCoordinate = function (point) {
  5817. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  5818. };
  5819. /**
  5820. * Updates the current Plane from the plane defined by the three passed points.
  5821. * Returns the updated Plane.
  5822. */
  5823. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  5824. var x1 = point2.x - point1.x;
  5825. var y1 = point2.y - point1.y;
  5826. var z1 = point2.z - point1.z;
  5827. var x2 = point3.x - point1.x;
  5828. var y2 = point3.y - point1.y;
  5829. var z2 = point3.z - point1.z;
  5830. var yz = (y1 * z2) - (z1 * y2);
  5831. var xz = (z1 * x2) - (x1 * z2);
  5832. var xy = (x1 * y2) - (y1 * x2);
  5833. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  5834. var invPyth;
  5835. if (pyth !== 0) {
  5836. invPyth = 1.0 / pyth;
  5837. }
  5838. else {
  5839. invPyth = 0.0;
  5840. }
  5841. this.normal.x = yz * invPyth;
  5842. this.normal.y = xz * invPyth;
  5843. this.normal.z = xy * invPyth;
  5844. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  5845. return this;
  5846. };
  5847. /**
  5848. * Boolean : True is the vector "direction" is the same side than the plane normal.
  5849. */
  5850. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  5851. var dot = Vector3.Dot(this.normal, direction);
  5852. return (dot <= epsilon);
  5853. };
  5854. /**
  5855. * Returns the signed distance (float) from the passed point to the Plane.
  5856. */
  5857. Plane.prototype.signedDistanceTo = function (point) {
  5858. return Vector3.Dot(point, this.normal) + this.d;
  5859. };
  5860. // Statics
  5861. /**
  5862. * Returns a new Plane from the passed array.
  5863. */
  5864. Plane.FromArray = function (array) {
  5865. return new Plane(array[0], array[1], array[2], array[3]);
  5866. };
  5867. /**
  5868. * Returns a new Plane defined by the three passed points.
  5869. */
  5870. Plane.FromPoints = function (point1, point2, point3) {
  5871. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  5872. result.copyFromPoints(point1, point2, point3);
  5873. return result;
  5874. };
  5875. /**
  5876. * Returns a new Plane the normal vector to this plane at the passed origin point.
  5877. * Note : the vector "normal" is updated because normalized.
  5878. */
  5879. Plane.FromPositionAndNormal = function (origin, normal) {
  5880. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  5881. normal.normalize();
  5882. result.normal = normal;
  5883. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  5884. return result;
  5885. };
  5886. /**
  5887. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the passed other point.
  5888. */
  5889. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  5890. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  5891. return Vector3.Dot(point, normal) + d;
  5892. };
  5893. return Plane;
  5894. }());
  5895. BABYLON.Plane = Plane;
  5896. var Viewport = /** @class */ (function () {
  5897. /**
  5898. * Creates a Viewport object located at (x, y) and sized (width, height).
  5899. */
  5900. function Viewport(x, y, width, height) {
  5901. this.x = x;
  5902. this.y = y;
  5903. this.width = width;
  5904. this.height = height;
  5905. }
  5906. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  5907. if (renderWidthOrEngine.getRenderWidth) {
  5908. var engine = renderWidthOrEngine;
  5909. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  5910. }
  5911. var renderWidth = renderWidthOrEngine;
  5912. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  5913. };
  5914. /**
  5915. * Returns a new Viewport copied from the current one.
  5916. */
  5917. Viewport.prototype.clone = function () {
  5918. return new Viewport(this.x, this.y, this.width, this.height);
  5919. };
  5920. return Viewport;
  5921. }());
  5922. BABYLON.Viewport = Viewport;
  5923. var Frustum = /** @class */ (function () {
  5924. function Frustum() {
  5925. }
  5926. /**
  5927. * Returns a new array of 6 Frustum planes computed by the passed transformation matrix.
  5928. */
  5929. Frustum.GetPlanes = function (transform) {
  5930. var frustumPlanes = [];
  5931. for (var index = 0; index < 6; index++) {
  5932. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  5933. }
  5934. Frustum.GetPlanesToRef(transform, frustumPlanes);
  5935. return frustumPlanes;
  5936. };
  5937. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  5938. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  5939. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  5940. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  5941. frustumPlane.d = transform.m[15] + transform.m[14];
  5942. frustumPlane.normalize();
  5943. };
  5944. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  5945. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  5946. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  5947. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  5948. frustumPlane.d = transform.m[15] - transform.m[14];
  5949. frustumPlane.normalize();
  5950. };
  5951. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  5952. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  5953. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  5954. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  5955. frustumPlane.d = transform.m[15] + transform.m[12];
  5956. frustumPlane.normalize();
  5957. };
  5958. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  5959. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  5960. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  5961. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  5962. frustumPlane.d = transform.m[15] - transform.m[12];
  5963. frustumPlane.normalize();
  5964. };
  5965. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  5966. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  5967. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  5968. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  5969. frustumPlane.d = transform.m[15] - transform.m[13];
  5970. frustumPlane.normalize();
  5971. };
  5972. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  5973. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  5974. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  5975. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  5976. frustumPlane.d = transform.m[15] + transform.m[13];
  5977. frustumPlane.normalize();
  5978. };
  5979. /**
  5980. * Sets the passed array "frustumPlanes" with the 6 Frustum planes computed by the passed transformation matrix.
  5981. */
  5982. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  5983. // Near
  5984. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  5985. // Far
  5986. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  5987. // Left
  5988. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  5989. // Right
  5990. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  5991. // Top
  5992. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  5993. // Bottom
  5994. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  5995. };
  5996. return Frustum;
  5997. }());
  5998. BABYLON.Frustum = Frustum;
  5999. var Space;
  6000. (function (Space) {
  6001. Space[Space["LOCAL"] = 0] = "LOCAL";
  6002. Space[Space["WORLD"] = 1] = "WORLD";
  6003. Space[Space["BONE"] = 2] = "BONE";
  6004. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  6005. var Axis = /** @class */ (function () {
  6006. function Axis() {
  6007. }
  6008. Axis.X = new Vector3(1.0, 0.0, 0.0);
  6009. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  6010. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  6011. return Axis;
  6012. }());
  6013. BABYLON.Axis = Axis;
  6014. ;
  6015. var BezierCurve = /** @class */ (function () {
  6016. function BezierCurve() {
  6017. }
  6018. /**
  6019. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the passed x1, y1, x2, y2 floats.
  6020. */
  6021. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  6022. // Extract X (which is equal to time here)
  6023. var f0 = 1 - 3 * x2 + 3 * x1;
  6024. var f1 = 3 * x2 - 6 * x1;
  6025. var f2 = 3 * x1;
  6026. var refinedT = t;
  6027. for (var i = 0; i < 5; i++) {
  6028. var refinedT2 = refinedT * refinedT;
  6029. var refinedT3 = refinedT2 * refinedT;
  6030. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  6031. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  6032. refinedT -= (x - t) * slope;
  6033. refinedT = Math.min(1, Math.max(0, refinedT));
  6034. }
  6035. // Resolve cubic bezier for the given x
  6036. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  6037. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  6038. Math.pow(refinedT, 3);
  6039. };
  6040. return BezierCurve;
  6041. }());
  6042. BABYLON.BezierCurve = BezierCurve;
  6043. var Orientation;
  6044. (function (Orientation) {
  6045. Orientation[Orientation["CW"] = 0] = "CW";
  6046. Orientation[Orientation["CCW"] = 1] = "CCW";
  6047. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  6048. var Angle = /** @class */ (function () {
  6049. /**
  6050. * Creates an Angle object of "radians" radians (float).
  6051. */
  6052. function Angle(radians) {
  6053. var _this = this;
  6054. /**
  6055. * Returns the Angle value in degrees (float).
  6056. */
  6057. this.degrees = function () { return _this._radians * 180.0 / Math.PI; };
  6058. /**
  6059. * Returns the Angle value in radians (float).
  6060. */
  6061. this.radians = function () { return _this._radians; };
  6062. this._radians = radians;
  6063. if (this._radians < 0.0)
  6064. this._radians += (2.0 * Math.PI);
  6065. }
  6066. /**
  6067. * Returns a new Angle object valued with the angle value in radians between the two passed vectors.
  6068. */
  6069. Angle.BetweenTwoPoints = function (a, b) {
  6070. var delta = b.subtract(a);
  6071. var theta = Math.atan2(delta.y, delta.x);
  6072. return new Angle(theta);
  6073. };
  6074. /**
  6075. * Returns a new Angle object from the passed float in radians.
  6076. */
  6077. Angle.FromRadians = function (radians) {
  6078. return new Angle(radians);
  6079. };
  6080. /**
  6081. * Returns a new Angle object from the passed float in degrees.
  6082. */
  6083. Angle.FromDegrees = function (degrees) {
  6084. return new Angle(degrees * Math.PI / 180.0);
  6085. };
  6086. return Angle;
  6087. }());
  6088. BABYLON.Angle = Angle;
  6089. var Arc2 = /** @class */ (function () {
  6090. /**
  6091. * Creates an Arc object from the three passed points : start, middle and end.
  6092. */
  6093. function Arc2(startPoint, midPoint, endPoint) {
  6094. this.startPoint = startPoint;
  6095. this.midPoint = midPoint;
  6096. this.endPoint = endPoint;
  6097. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  6098. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  6099. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  6100. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  6101. 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);
  6102. this.radius = this.centerPoint.subtract(this.startPoint).length();
  6103. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  6104. var a1 = this.startAngle.degrees();
  6105. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  6106. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  6107. // angles correction
  6108. if (a2 - a1 > +180.0)
  6109. a2 -= 360.0;
  6110. if (a2 - a1 < -180.0)
  6111. a2 += 360.0;
  6112. if (a3 - a2 > +180.0)
  6113. a3 -= 360.0;
  6114. if (a3 - a2 < -180.0)
  6115. a3 += 360.0;
  6116. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  6117. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  6118. }
  6119. return Arc2;
  6120. }());
  6121. BABYLON.Arc2 = Arc2;
  6122. var Path2 = /** @class */ (function () {
  6123. /**
  6124. * Creates a Path2 object from the starting 2D coordinates x and y.
  6125. */
  6126. function Path2(x, y) {
  6127. this._points = new Array();
  6128. this._length = 0.0;
  6129. this.closed = false;
  6130. this._points.push(new Vector2(x, y));
  6131. }
  6132. /**
  6133. * Adds a new segment until the passed coordinates (x, y) to the current Path2.
  6134. * Returns the updated Path2.
  6135. */
  6136. Path2.prototype.addLineTo = function (x, y) {
  6137. if (this.closed) {
  6138. //Tools.Error("cannot add lines to closed paths");
  6139. return this;
  6140. }
  6141. var newPoint = new Vector2(x, y);
  6142. var previousPoint = this._points[this._points.length - 1];
  6143. this._points.push(newPoint);
  6144. this._length += newPoint.subtract(previousPoint).length();
  6145. return this;
  6146. };
  6147. /**
  6148. * 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.
  6149. * Returns the updated Path2.
  6150. */
  6151. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  6152. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  6153. if (this.closed) {
  6154. //Tools.Error("cannot add arcs to closed paths");
  6155. return this;
  6156. }
  6157. var startPoint = this._points[this._points.length - 1];
  6158. var midPoint = new Vector2(midX, midY);
  6159. var endPoint = new Vector2(endX, endY);
  6160. var arc = new Arc2(startPoint, midPoint, endPoint);
  6161. var increment = arc.angle.radians() / numberOfSegments;
  6162. if (arc.orientation === Orientation.CW)
  6163. increment *= -1;
  6164. var currentAngle = arc.startAngle.radians() + increment;
  6165. for (var i = 0; i < numberOfSegments; i++) {
  6166. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  6167. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  6168. this.addLineTo(x, y);
  6169. currentAngle += increment;
  6170. }
  6171. return this;
  6172. };
  6173. /**
  6174. * Closes the Path2.
  6175. * Returns the Path2.
  6176. */
  6177. Path2.prototype.close = function () {
  6178. this.closed = true;
  6179. return this;
  6180. };
  6181. /**
  6182. * Returns the Path2 total length (float).
  6183. */
  6184. Path2.prototype.length = function () {
  6185. var result = this._length;
  6186. if (!this.closed) {
  6187. var lastPoint = this._points[this._points.length - 1];
  6188. var firstPoint = this._points[0];
  6189. result += (firstPoint.subtract(lastPoint).length());
  6190. }
  6191. return result;
  6192. };
  6193. /**
  6194. * Returns the Path2 internal array of points.
  6195. */
  6196. Path2.prototype.getPoints = function () {
  6197. return this._points;
  6198. };
  6199. /**
  6200. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  6201. */
  6202. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  6203. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  6204. //Tools.Error("normalized length position should be between 0 and 1.");
  6205. return Vector2.Zero();
  6206. }
  6207. var lengthPosition = normalizedLengthPosition * this.length();
  6208. var previousOffset = 0;
  6209. for (var i = 0; i < this._points.length; i++) {
  6210. var j = (i + 1) % this._points.length;
  6211. var a = this._points[i];
  6212. var b = this._points[j];
  6213. var bToA = b.subtract(a);
  6214. var nextOffset = (bToA.length() + previousOffset);
  6215. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  6216. var dir = bToA.normalize();
  6217. var localOffset = lengthPosition - previousOffset;
  6218. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  6219. }
  6220. previousOffset = nextOffset;
  6221. }
  6222. //Tools.Error("internal error");
  6223. return Vector2.Zero();
  6224. };
  6225. /**
  6226. * Returns a new Path2 starting at the coordinates (x, y).
  6227. */
  6228. Path2.StartingAt = function (x, y) {
  6229. return new Path2(x, y);
  6230. };
  6231. return Path2;
  6232. }());
  6233. BABYLON.Path2 = Path2;
  6234. var Path3D = /** @class */ (function () {
  6235. /**
  6236. * new Path3D(path, normal, raw)
  6237. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  6238. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  6239. * path : an array of Vector3, the curve axis of the Path3D
  6240. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  6241. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  6242. */
  6243. function Path3D(path, firstNormal, raw) {
  6244. if (firstNormal === void 0) { firstNormal = null; }
  6245. this.path = path;
  6246. this._curve = new Array();
  6247. this._distances = new Array();
  6248. this._tangents = new Array();
  6249. this._normals = new Array();
  6250. this._binormals = new Array();
  6251. for (var p = 0; p < path.length; p++) {
  6252. this._curve[p] = path[p].clone(); // hard copy
  6253. }
  6254. this._raw = raw || false;
  6255. this._compute(firstNormal);
  6256. }
  6257. /**
  6258. * Returns the Path3D array of successive Vector3 designing its curve.
  6259. */
  6260. Path3D.prototype.getCurve = function () {
  6261. return this._curve;
  6262. };
  6263. /**
  6264. * Returns an array populated with tangent vectors on each Path3D curve point.
  6265. */
  6266. Path3D.prototype.getTangents = function () {
  6267. return this._tangents;
  6268. };
  6269. /**
  6270. * Returns an array populated with normal vectors on each Path3D curve point.
  6271. */
  6272. Path3D.prototype.getNormals = function () {
  6273. return this._normals;
  6274. };
  6275. /**
  6276. * Returns an array populated with binormal vectors on each Path3D curve point.
  6277. */
  6278. Path3D.prototype.getBinormals = function () {
  6279. return this._binormals;
  6280. };
  6281. /**
  6282. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  6283. */
  6284. Path3D.prototype.getDistances = function () {
  6285. return this._distances;
  6286. };
  6287. /**
  6288. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  6289. * Returns the same object updated.
  6290. */
  6291. Path3D.prototype.update = function (path, firstNormal) {
  6292. if (firstNormal === void 0) { firstNormal = null; }
  6293. for (var p = 0; p < path.length; p++) {
  6294. this._curve[p].x = path[p].x;
  6295. this._curve[p].y = path[p].y;
  6296. this._curve[p].z = path[p].z;
  6297. }
  6298. this._compute(firstNormal);
  6299. return this;
  6300. };
  6301. // private function compute() : computes tangents, normals and binormals
  6302. Path3D.prototype._compute = function (firstNormal) {
  6303. var l = this._curve.length;
  6304. // first and last tangents
  6305. this._tangents[0] = this._getFirstNonNullVector(0);
  6306. if (!this._raw) {
  6307. this._tangents[0].normalize();
  6308. }
  6309. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  6310. if (!this._raw) {
  6311. this._tangents[l - 1].normalize();
  6312. }
  6313. // normals and binormals at first point : arbitrary vector with _normalVector()
  6314. var tg0 = this._tangents[0];
  6315. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  6316. this._normals[0] = pp0;
  6317. if (!this._raw) {
  6318. this._normals[0].normalize();
  6319. }
  6320. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  6321. if (!this._raw) {
  6322. this._binormals[0].normalize();
  6323. }
  6324. this._distances[0] = 0.0;
  6325. // normals and binormals : next points
  6326. var prev; // previous vector (segment)
  6327. var cur; // current vector (segment)
  6328. var curTang; // current tangent
  6329. // previous normal
  6330. var prevBinor; // previous binormal
  6331. for (var i = 1; i < l; i++) {
  6332. // tangents
  6333. prev = this._getLastNonNullVector(i);
  6334. if (i < l - 1) {
  6335. cur = this._getFirstNonNullVector(i);
  6336. this._tangents[i] = prev.add(cur);
  6337. this._tangents[i].normalize();
  6338. }
  6339. this._distances[i] = this._distances[i - 1] + prev.length();
  6340. // normals and binormals
  6341. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  6342. curTang = this._tangents[i];
  6343. prevBinor = this._binormals[i - 1];
  6344. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  6345. if (!this._raw) {
  6346. this._normals[i].normalize();
  6347. }
  6348. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  6349. if (!this._raw) {
  6350. this._binormals[i].normalize();
  6351. }
  6352. }
  6353. };
  6354. // private function getFirstNonNullVector(index)
  6355. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  6356. Path3D.prototype._getFirstNonNullVector = function (index) {
  6357. var i = 1;
  6358. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  6359. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  6360. i++;
  6361. nNVector = this._curve[index + i].subtract(this._curve[index]);
  6362. }
  6363. return nNVector;
  6364. };
  6365. // private function getLastNonNullVector(index)
  6366. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  6367. Path3D.prototype._getLastNonNullVector = function (index) {
  6368. var i = 1;
  6369. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  6370. while (nLVector.length() === 0 && index > i + 1) {
  6371. i++;
  6372. nLVector = this._curve[index].subtract(this._curve[index - i]);
  6373. }
  6374. return nLVector;
  6375. };
  6376. // private function normalVector(v0, vt, va) :
  6377. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  6378. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  6379. Path3D.prototype._normalVector = function (v0, vt, va) {
  6380. var normal0;
  6381. var tgl = vt.length();
  6382. if (tgl === 0.0) {
  6383. tgl = 1.0;
  6384. }
  6385. if (va === undefined || va === null) {
  6386. var point;
  6387. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  6388. point = new Vector3(0.0, -1.0, 0.0);
  6389. }
  6390. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  6391. point = new Vector3(1.0, 0.0, 0.0);
  6392. }
  6393. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  6394. point = new Vector3(0.0, 0.0, 1.0);
  6395. }
  6396. else {
  6397. point = Vector3.Zero();
  6398. }
  6399. normal0 = Vector3.Cross(vt, point);
  6400. }
  6401. else {
  6402. normal0 = Vector3.Cross(vt, va);
  6403. Vector3.CrossToRef(normal0, vt, normal0);
  6404. }
  6405. normal0.normalize();
  6406. return normal0;
  6407. };
  6408. return Path3D;
  6409. }());
  6410. BABYLON.Path3D = Path3D;
  6411. var Curve3 = /** @class */ (function () {
  6412. /**
  6413. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  6414. * A Curve3 is designed from a series of successive Vector3.
  6415. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  6416. */
  6417. function Curve3(points) {
  6418. this._length = 0.0;
  6419. this._points = points;
  6420. this._length = this._computeLength(points);
  6421. }
  6422. /**
  6423. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  6424. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  6425. * @param v1 (Vector3) the control point
  6426. * @param v2 (Vector3) the end point of the Quadratic Bezier
  6427. * @param nbPoints (integer) the wanted number of points in the curve
  6428. */
  6429. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  6430. nbPoints = nbPoints > 2 ? nbPoints : 3;
  6431. var bez = new Array();
  6432. var equation = function (t, val0, val1, val2) {
  6433. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  6434. return res;
  6435. };
  6436. for (var i = 0; i <= nbPoints; i++) {
  6437. 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)));
  6438. }
  6439. return new Curve3(bez);
  6440. };
  6441. /**
  6442. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  6443. * @param v0 (Vector3) the origin point of the Cubic Bezier
  6444. * @param v1 (Vector3) the first control point
  6445. * @param v2 (Vector3) the second control point
  6446. * @param v3 (Vector3) the end point of the Cubic Bezier
  6447. * @param nbPoints (integer) the wanted number of points in the curve
  6448. */
  6449. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  6450. nbPoints = nbPoints > 3 ? nbPoints : 4;
  6451. var bez = new Array();
  6452. var equation = function (t, val0, val1, val2, val3) {
  6453. 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;
  6454. return res;
  6455. };
  6456. for (var i = 0; i <= nbPoints; i++) {
  6457. 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)));
  6458. }
  6459. return new Curve3(bez);
  6460. };
  6461. /**
  6462. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  6463. * @param p1 (Vector3) the origin point of the Hermite Spline
  6464. * @param t1 (Vector3) the tangent vector at the origin point
  6465. * @param p2 (Vector3) the end point of the Hermite Spline
  6466. * @param t2 (Vector3) the tangent vector at the end point
  6467. * @param nbPoints (integer) the wanted number of points in the curve
  6468. */
  6469. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  6470. var hermite = new Array();
  6471. var step = 1.0 / nbPoints;
  6472. for (var i = 0; i <= nbPoints; i++) {
  6473. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  6474. }
  6475. return new Curve3(hermite);
  6476. };
  6477. /**
  6478. * Returns a Curve3 object along a CatmullRom Spline curve :
  6479. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  6480. * @param nbPoints (integer) the wanted number of points between each curve control points.
  6481. */
  6482. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  6483. var totalPoints = new Array();
  6484. totalPoints.push(points[0].clone());
  6485. Array.prototype.push.apply(totalPoints, points);
  6486. totalPoints.push(points[points.length - 1].clone());
  6487. var catmullRom = new Array();
  6488. var step = 1.0 / nbPoints;
  6489. var amount = 0.0;
  6490. for (var i = 0; i < totalPoints.length - 3; i++) {
  6491. amount = 0;
  6492. for (var c = 0; c < nbPoints; c++) {
  6493. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  6494. amount += step;
  6495. }
  6496. }
  6497. i--;
  6498. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  6499. return new Curve3(catmullRom);
  6500. };
  6501. /**
  6502. * Returns the Curve3 stored array of successive Vector3
  6503. */
  6504. Curve3.prototype.getPoints = function () {
  6505. return this._points;
  6506. };
  6507. /**
  6508. * Returns the computed length (float) of the curve.
  6509. */
  6510. Curve3.prototype.length = function () {
  6511. return this._length;
  6512. };
  6513. /**
  6514. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  6515. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  6516. * curveA and curveB keep unchanged.
  6517. */
  6518. Curve3.prototype.continue = function (curve) {
  6519. var lastPoint = this._points[this._points.length - 1];
  6520. var continuedPoints = this._points.slice();
  6521. var curvePoints = curve.getPoints();
  6522. for (var i = 1; i < curvePoints.length; i++) {
  6523. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  6524. }
  6525. var continuedCurve = new Curve3(continuedPoints);
  6526. return continuedCurve;
  6527. };
  6528. Curve3.prototype._computeLength = function (path) {
  6529. var l = 0;
  6530. for (var i = 1; i < path.length; i++) {
  6531. l += (path[i].subtract(path[i - 1])).length();
  6532. }
  6533. return l;
  6534. };
  6535. return Curve3;
  6536. }());
  6537. BABYLON.Curve3 = Curve3;
  6538. // Vertex formats
  6539. var PositionNormalVertex = /** @class */ (function () {
  6540. function PositionNormalVertex(position, normal) {
  6541. if (position === void 0) { position = Vector3.Zero(); }
  6542. if (normal === void 0) { normal = Vector3.Up(); }
  6543. this.position = position;
  6544. this.normal = normal;
  6545. }
  6546. PositionNormalVertex.prototype.clone = function () {
  6547. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  6548. };
  6549. return PositionNormalVertex;
  6550. }());
  6551. BABYLON.PositionNormalVertex = PositionNormalVertex;
  6552. var PositionNormalTextureVertex = /** @class */ (function () {
  6553. function PositionNormalTextureVertex(position, normal, uv) {
  6554. if (position === void 0) { position = Vector3.Zero(); }
  6555. if (normal === void 0) { normal = Vector3.Up(); }
  6556. if (uv === void 0) { uv = Vector2.Zero(); }
  6557. this.position = position;
  6558. this.normal = normal;
  6559. this.uv = uv;
  6560. }
  6561. PositionNormalTextureVertex.prototype.clone = function () {
  6562. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  6563. };
  6564. return PositionNormalTextureVertex;
  6565. }());
  6566. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  6567. // Temporary pre-allocated objects for engine internal use
  6568. // usage in any internal function :
  6569. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  6570. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  6571. var Tmp = /** @class */ (function () {
  6572. function Tmp() {
  6573. }
  6574. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  6575. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  6576. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  6577. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  6578. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  6579. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  6580. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  6581. Matrix.Zero(), Matrix.Zero(),
  6582. Matrix.Zero(), Matrix.Zero(),
  6583. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  6584. return Tmp;
  6585. }());
  6586. BABYLON.Tmp = Tmp;
  6587. // Same as Tmp but not exported to keep it onyl for math functions to avoid conflicts
  6588. var MathTmp = /** @class */ (function () {
  6589. function MathTmp() {
  6590. }
  6591. MathTmp.Vector3 = [Vector3.Zero()];
  6592. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  6593. MathTmp.Quaternion = [Quaternion.Zero()];
  6594. return MathTmp;
  6595. }());
  6596. })(BABYLON || (BABYLON = {}));
  6597. //# sourceMappingURL=babylon.math.js.map
  6598. var BABYLON;
  6599. (function (BABYLON) {
  6600. var Scalar = /** @class */ (function () {
  6601. function Scalar() {
  6602. }
  6603. /**
  6604. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  6605. */
  6606. Scalar.WithinEpsilon = function (a, b, epsilon) {
  6607. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  6608. var num = a - b;
  6609. return -epsilon <= num && num <= epsilon;
  6610. };
  6611. /**
  6612. * Returns a string : the upper case translation of the number i to hexadecimal.
  6613. */
  6614. Scalar.ToHex = function (i) {
  6615. var str = i.toString(16);
  6616. if (i <= 15) {
  6617. return ("0" + str).toUpperCase();
  6618. }
  6619. return str.toUpperCase();
  6620. };
  6621. /**
  6622. * Returns -1 if value is negative and +1 is value is positive.
  6623. * Returns the value itself if it's equal to zero.
  6624. */
  6625. Scalar.Sign = function (value) {
  6626. value = +value; // convert to a number
  6627. if (value === 0 || isNaN(value))
  6628. return value;
  6629. return value > 0 ? 1 : -1;
  6630. };
  6631. /**
  6632. * Returns the value itself if it's between min and max.
  6633. * Returns min if the value is lower than min.
  6634. * Returns max if the value is greater than max.
  6635. */
  6636. Scalar.Clamp = function (value, min, max) {
  6637. if (min === void 0) { min = 0; }
  6638. if (max === void 0) { max = 1; }
  6639. return Math.min(max, Math.max(min, value));
  6640. };
  6641. /**
  6642. * Returns the log2 of value.
  6643. */
  6644. Scalar.Log2 = function (value) {
  6645. return Math.log(value) * Math.LOG2E;
  6646. };
  6647. /**
  6648. * Loops the value, so that it is never larger than length and never smaller than 0.
  6649. *
  6650. * This is similar to the modulo operator but it works with floating point numbers.
  6651. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  6652. * With t = 5 and length = 2.5, the result would be 0.0.
  6653. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  6654. */
  6655. Scalar.Repeat = function (value, length) {
  6656. return value - Math.floor(value / length) * length;
  6657. };
  6658. /**
  6659. * Normalize the value between 0.0 and 1.0 using min and max values
  6660. */
  6661. Scalar.Normalize = function (value, min, max) {
  6662. return (value - min) / (max - min);
  6663. };
  6664. /**
  6665. * Denormalize the value from 0.0 and 1.0 using min and max values
  6666. */
  6667. Scalar.Denormalize = function (normalized, min, max) {
  6668. return (normalized * (max - min) + min);
  6669. };
  6670. /**
  6671. * Calculates the shortest difference between two given angles given in degrees.
  6672. */
  6673. Scalar.DeltaAngle = function (current, target) {
  6674. var num = Scalar.Repeat(target - current, 360.0);
  6675. if (num > 180.0) {
  6676. num -= 360.0;
  6677. }
  6678. return num;
  6679. };
  6680. /**
  6681. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  6682. *
  6683. * The returned value will move back and forth between 0 and length
  6684. */
  6685. Scalar.PingPong = function (tx, length) {
  6686. var t = Scalar.Repeat(tx, length * 2.0);
  6687. return length - Math.abs(t - length);
  6688. };
  6689. /**
  6690. * Interpolates between min and max with smoothing at the limits.
  6691. *
  6692. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  6693. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  6694. */
  6695. Scalar.SmoothStep = function (from, to, tx) {
  6696. var t = Scalar.Clamp(tx);
  6697. t = -2.0 * t * t * t + 3.0 * t * t;
  6698. return to * t + from * (1.0 - t);
  6699. };
  6700. /**
  6701. * Moves a value current towards target.
  6702. *
  6703. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  6704. * Negative values of maxDelta pushes the value away from target.
  6705. */
  6706. Scalar.MoveTowards = function (current, target, maxDelta) {
  6707. var result = 0;
  6708. if (Math.abs(target - current) <= maxDelta) {
  6709. result = target;
  6710. }
  6711. else {
  6712. result = current + Scalar.Sign(target - current) * maxDelta;
  6713. }
  6714. return result;
  6715. };
  6716. /**
  6717. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  6718. *
  6719. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  6720. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  6721. */
  6722. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  6723. var num = Scalar.DeltaAngle(current, target);
  6724. var result = 0;
  6725. if (-maxDelta < num && num < maxDelta) {
  6726. result = target;
  6727. }
  6728. else {
  6729. target = current + num;
  6730. result = Scalar.MoveTowards(current, target, maxDelta);
  6731. }
  6732. return result;
  6733. };
  6734. /**
  6735. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  6736. */
  6737. Scalar.Lerp = function (start, end, amount) {
  6738. return start + ((end - start) * amount);
  6739. };
  6740. /**
  6741. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  6742. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  6743. */
  6744. Scalar.LerpAngle = function (start, end, amount) {
  6745. var num = Scalar.Repeat(end - start, 360.0);
  6746. if (num > 180.0) {
  6747. num -= 360.0;
  6748. }
  6749. return start + num * Scalar.Clamp(amount);
  6750. };
  6751. /**
  6752. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  6753. */
  6754. Scalar.InverseLerp = function (a, b, value) {
  6755. var result = 0;
  6756. if (a != b) {
  6757. result = Scalar.Clamp((value - a) / (b - a));
  6758. }
  6759. else {
  6760. result = 0.0;
  6761. }
  6762. return result;
  6763. };
  6764. /**
  6765. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  6766. */
  6767. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  6768. var squared = amount * amount;
  6769. var cubed = amount * squared;
  6770. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  6771. var part2 = (-2.0 * cubed) + (3.0 * squared);
  6772. var part3 = (cubed - (2.0 * squared)) + amount;
  6773. var part4 = cubed - squared;
  6774. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  6775. };
  6776. /**
  6777. * Returns a random float number between and min and max values
  6778. */
  6779. Scalar.RandomRange = function (min, max) {
  6780. if (min === max)
  6781. return min;
  6782. return ((Math.random() * (max - min)) + min);
  6783. };
  6784. /**
  6785. * This function returns percentage of a number in a given range.
  6786. *
  6787. * RangeToPercent(40,20,60) will return 0.5 (50%)
  6788. * RangeToPercent(34,0,100) will return 0.34 (34%)
  6789. */
  6790. Scalar.RangeToPercent = function (number, min, max) {
  6791. return ((number - min) / (max - min));
  6792. };
  6793. /**
  6794. * This function returns number that corresponds to the percentage in a given range.
  6795. *
  6796. * PercentToRange(0.34,0,100) will return 34.
  6797. */
  6798. Scalar.PercentToRange = function (percent, min, max) {
  6799. return ((max - min) * percent + min);
  6800. };
  6801. /**
  6802. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  6803. * @param angle The angle to normalize in radian.
  6804. * @return The converted angle.
  6805. */
  6806. Scalar.NormalizeRadians = function (angle) {
  6807. // More precise but slower version kept for reference.
  6808. // angle = angle % Tools.TwoPi;
  6809. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  6810. //if (angle > Math.PI) {
  6811. // angle -= Tools.TwoPi;
  6812. //}
  6813. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  6814. return angle;
  6815. };
  6816. /**
  6817. * Two pi constants convenient for computation.
  6818. */
  6819. Scalar.TwoPi = Math.PI * 2;
  6820. return Scalar;
  6821. }());
  6822. BABYLON.Scalar = Scalar;
  6823. })(BABYLON || (BABYLON = {}));
  6824. //# sourceMappingURL=babylon.math.scalar.js.map
  6825. //# sourceMappingURL=babylon.mixins.js.map
  6826. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  6827. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  6828. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  6829. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  6830. //# sourceMappingURL=babylon.webgl2.js.map
  6831. var BABYLON;
  6832. (function (BABYLON) {
  6833. var __decoratorInitialStore = {};
  6834. var __mergedStore = {};
  6835. var _copySource = function (creationFunction, source, instanciate) {
  6836. var destination = creationFunction();
  6837. // Tags
  6838. if (BABYLON.Tags) {
  6839. BABYLON.Tags.AddTagsTo(destination, source.tags);
  6840. }
  6841. var classStore = getMergedStore(destination);
  6842. // Properties
  6843. for (var property in classStore) {
  6844. var propertyDescriptor = classStore[property];
  6845. var sourceProperty = source[property];
  6846. var propertyType = propertyDescriptor.type;
  6847. if (sourceProperty !== undefined && sourceProperty !== null) {
  6848. switch (propertyType) {
  6849. case 0: // Value
  6850. case 6:// Mesh reference
  6851. destination[property] = sourceProperty;
  6852. break;
  6853. case 1:// Texture
  6854. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  6855. break;
  6856. case 2: // Color3
  6857. case 3: // FresnelParameters
  6858. case 4: // Vector2
  6859. case 5: // Vector3
  6860. case 7: // Color Curves
  6861. case 10:// Quaternion
  6862. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  6863. break;
  6864. }
  6865. }
  6866. }
  6867. return destination;
  6868. };
  6869. function getDirectStore(target) {
  6870. var classKey = target.getClassName();
  6871. if (!__decoratorInitialStore[classKey]) {
  6872. __decoratorInitialStore[classKey] = {};
  6873. }
  6874. return __decoratorInitialStore[classKey];
  6875. }
  6876. /**
  6877. * Return the list of properties flagged as serializable
  6878. * @param target: host object
  6879. */
  6880. function getMergedStore(target) {
  6881. var classKey = target.getClassName();
  6882. if (__mergedStore[classKey]) {
  6883. return __mergedStore[classKey];
  6884. }
  6885. __mergedStore[classKey] = {};
  6886. var store = __mergedStore[classKey];
  6887. var currentTarget = target;
  6888. var currentKey = classKey;
  6889. while (currentKey) {
  6890. var initialStore = __decoratorInitialStore[currentKey];
  6891. for (var property in initialStore) {
  6892. store[property] = initialStore[property];
  6893. }
  6894. var parent_1 = void 0;
  6895. var done = false;
  6896. do {
  6897. parent_1 = Object.getPrototypeOf(currentTarget);
  6898. if (!parent_1.getClassName) {
  6899. done = true;
  6900. break;
  6901. }
  6902. if (parent_1.getClassName() !== currentKey) {
  6903. break;
  6904. }
  6905. currentTarget = parent_1;
  6906. } while (parent_1);
  6907. if (done) {
  6908. break;
  6909. }
  6910. currentKey = parent_1.getClassName();
  6911. currentTarget = parent_1;
  6912. }
  6913. return store;
  6914. }
  6915. function generateSerializableMember(type, sourceName) {
  6916. return function (target, propertyKey) {
  6917. var classStore = getDirectStore(target);
  6918. if (!classStore[propertyKey]) {
  6919. classStore[propertyKey] = { type: type, sourceName: sourceName };
  6920. }
  6921. };
  6922. }
  6923. function generateExpandMember(setCallback, targetKey) {
  6924. if (targetKey === void 0) { targetKey = null; }
  6925. return function (target, propertyKey) {
  6926. var key = targetKey || ("_" + propertyKey);
  6927. Object.defineProperty(target, propertyKey, {
  6928. get: function () {
  6929. return this[key];
  6930. },
  6931. set: function (value) {
  6932. if (this[key] === value) {
  6933. return;
  6934. }
  6935. this[key] = value;
  6936. target[setCallback].apply(this);
  6937. },
  6938. enumerable: true,
  6939. configurable: true
  6940. });
  6941. };
  6942. }
  6943. function expandToProperty(callback, targetKey) {
  6944. if (targetKey === void 0) { targetKey = null; }
  6945. return generateExpandMember(callback, targetKey);
  6946. }
  6947. BABYLON.expandToProperty = expandToProperty;
  6948. function serialize(sourceName) {
  6949. return generateSerializableMember(0, sourceName); // value member
  6950. }
  6951. BABYLON.serialize = serialize;
  6952. function serializeAsTexture(sourceName) {
  6953. return generateSerializableMember(1, sourceName); // texture member
  6954. }
  6955. BABYLON.serializeAsTexture = serializeAsTexture;
  6956. function serializeAsColor3(sourceName) {
  6957. return generateSerializableMember(2, sourceName); // color3 member
  6958. }
  6959. BABYLON.serializeAsColor3 = serializeAsColor3;
  6960. function serializeAsFresnelParameters(sourceName) {
  6961. return generateSerializableMember(3, sourceName); // fresnel parameters member
  6962. }
  6963. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  6964. function serializeAsVector2(sourceName) {
  6965. return generateSerializableMember(4, sourceName); // vector2 member
  6966. }
  6967. BABYLON.serializeAsVector2 = serializeAsVector2;
  6968. function serializeAsVector3(sourceName) {
  6969. return generateSerializableMember(5, sourceName); // vector3 member
  6970. }
  6971. BABYLON.serializeAsVector3 = serializeAsVector3;
  6972. function serializeAsMeshReference(sourceName) {
  6973. return generateSerializableMember(6, sourceName); // mesh reference member
  6974. }
  6975. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  6976. function serializeAsColorCurves(sourceName) {
  6977. return generateSerializableMember(7, sourceName); // color curves
  6978. }
  6979. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  6980. function serializeAsColor4(sourceName) {
  6981. return generateSerializableMember(8, sourceName); // color 4
  6982. }
  6983. BABYLON.serializeAsColor4 = serializeAsColor4;
  6984. function serializeAsImageProcessingConfiguration(sourceName) {
  6985. return generateSerializableMember(9, sourceName); // image processing
  6986. }
  6987. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  6988. function serializeAsQuaternion(sourceName) {
  6989. return generateSerializableMember(10, sourceName); // quaternion member
  6990. }
  6991. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  6992. var SerializationHelper = /** @class */ (function () {
  6993. function SerializationHelper() {
  6994. }
  6995. SerializationHelper.Serialize = function (entity, serializationObject) {
  6996. if (!serializationObject) {
  6997. serializationObject = {};
  6998. }
  6999. // Tags
  7000. if (BABYLON.Tags) {
  7001. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  7002. }
  7003. var serializedProperties = getMergedStore(entity);
  7004. // Properties
  7005. for (var property in serializedProperties) {
  7006. var propertyDescriptor = serializedProperties[property];
  7007. var targetPropertyName = propertyDescriptor.sourceName || property;
  7008. var propertyType = propertyDescriptor.type;
  7009. var sourceProperty = entity[property];
  7010. if (sourceProperty !== undefined && sourceProperty !== null) {
  7011. switch (propertyType) {
  7012. case 0:// Value
  7013. serializationObject[targetPropertyName] = sourceProperty;
  7014. break;
  7015. case 1:// Texture
  7016. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7017. break;
  7018. case 2:// Color3
  7019. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7020. break;
  7021. case 3:// FresnelParameters
  7022. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7023. break;
  7024. case 4:// Vector2
  7025. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7026. break;
  7027. case 5:// Vector3
  7028. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7029. break;
  7030. case 6:// Mesh reference
  7031. serializationObject[targetPropertyName] = sourceProperty.id;
  7032. break;
  7033. case 7:// Color Curves
  7034. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7035. break;
  7036. case 8:// Color 4
  7037. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7038. break;
  7039. case 9:// Image Processing
  7040. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7041. break;
  7042. }
  7043. }
  7044. }
  7045. return serializationObject;
  7046. };
  7047. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  7048. if (rootUrl === void 0) { rootUrl = null; }
  7049. var destination = creationFunction();
  7050. if (!rootUrl) {
  7051. rootUrl = "";
  7052. }
  7053. // Tags
  7054. if (BABYLON.Tags) {
  7055. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7056. }
  7057. var classStore = getMergedStore(destination);
  7058. // Properties
  7059. for (var property in classStore) {
  7060. var propertyDescriptor = classStore[property];
  7061. var sourceProperty = source[propertyDescriptor.sourceName || property];
  7062. var propertyType = propertyDescriptor.type;
  7063. if (sourceProperty !== undefined && sourceProperty !== null) {
  7064. var dest = destination;
  7065. switch (propertyType) {
  7066. case 0:// Value
  7067. dest[property] = sourceProperty;
  7068. break;
  7069. case 1:// Texture
  7070. if (scene) {
  7071. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  7072. }
  7073. break;
  7074. case 2:// Color3
  7075. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  7076. break;
  7077. case 3:// FresnelParameters
  7078. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  7079. break;
  7080. case 4:// Vector2
  7081. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  7082. break;
  7083. case 5:// Vector3
  7084. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  7085. break;
  7086. case 6:// Mesh reference
  7087. if (scene) {
  7088. dest[property] = scene.getLastMeshByID(sourceProperty);
  7089. }
  7090. break;
  7091. case 7:// Color Curves
  7092. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  7093. break;
  7094. case 8:// Color 4
  7095. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  7096. break;
  7097. case 9:// Image Processing
  7098. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  7099. break;
  7100. }
  7101. }
  7102. }
  7103. return destination;
  7104. };
  7105. SerializationHelper.Clone = function (creationFunction, source) {
  7106. return _copySource(creationFunction, source, false);
  7107. };
  7108. SerializationHelper.Instanciate = function (creationFunction, source) {
  7109. return _copySource(creationFunction, source, true);
  7110. };
  7111. return SerializationHelper;
  7112. }());
  7113. BABYLON.SerializationHelper = SerializationHelper;
  7114. })(BABYLON || (BABYLON = {}));
  7115. //# sourceMappingURL=babylon.decorators.js.map
  7116. var BABYLON;
  7117. (function (BABYLON) {
  7118. /**
  7119. * Wrapper class for promise with external resolve and reject.
  7120. */
  7121. var Deferred = /** @class */ (function () {
  7122. /**
  7123. * Constructor for this deferred object.
  7124. */
  7125. function Deferred() {
  7126. var _this = this;
  7127. this.promise = new Promise(function (resolve, reject) {
  7128. _this._resolve = resolve;
  7129. _this._reject = reject;
  7130. });
  7131. }
  7132. Object.defineProperty(Deferred.prototype, "resolve", {
  7133. /**
  7134. * The resolve method of the promise associated with this deferred object.
  7135. */
  7136. get: function () {
  7137. return this._resolve;
  7138. },
  7139. enumerable: true,
  7140. configurable: true
  7141. });
  7142. Object.defineProperty(Deferred.prototype, "reject", {
  7143. /**
  7144. * The reject method of the promise associated with this deferred object.
  7145. */
  7146. get: function () {
  7147. return this._reject;
  7148. },
  7149. enumerable: true,
  7150. configurable: true
  7151. });
  7152. return Deferred;
  7153. }());
  7154. BABYLON.Deferred = Deferred;
  7155. })(BABYLON || (BABYLON = {}));
  7156. //# sourceMappingURL=babylon.deferred.js.map
  7157. var BABYLON;
  7158. (function (BABYLON) {
  7159. /**
  7160. * A class serves as a medium between the observable and its observers
  7161. */
  7162. var EventState = /** @class */ (function () {
  7163. /**
  7164. * Create a new EventState
  7165. * @param mask defines the mask associated with this state
  7166. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  7167. * @param target defines the original target of the state
  7168. * @param currentTarget defines the current target of the state
  7169. */
  7170. function EventState(mask, skipNextObservers, target, currentTarget) {
  7171. if (skipNextObservers === void 0) { skipNextObservers = false; }
  7172. this.initalize(mask, skipNextObservers, target, currentTarget);
  7173. }
  7174. /**
  7175. * Initialize the current event state
  7176. * @param mask defines the mask associated with this state
  7177. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  7178. * @param target defines the original target of the state
  7179. * @param currentTarget defines the current target of the state
  7180. * @returns the current event state
  7181. */
  7182. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  7183. if (skipNextObservers === void 0) { skipNextObservers = false; }
  7184. this.mask = mask;
  7185. this.skipNextObservers = skipNextObservers;
  7186. this.target = target;
  7187. this.currentTarget = currentTarget;
  7188. return this;
  7189. };
  7190. return EventState;
  7191. }());
  7192. BABYLON.EventState = EventState;
  7193. /**
  7194. * Represent an Observer registered to a given Observable object.
  7195. */
  7196. var Observer = /** @class */ (function () {
  7197. /**
  7198. * Creates a new observer
  7199. * @param callback defines the callback to call when the observer is notified
  7200. * @param mask defines the mask of the observer (used to filter notifications)
  7201. * @param scope defines the current scope used to restore the JS context
  7202. */
  7203. function Observer(
  7204. /**
  7205. * Defines the callback to call when the observer is notified
  7206. */
  7207. callback,
  7208. /**
  7209. * Defines the mask of the observer (used to filter notifications)
  7210. */
  7211. mask,
  7212. /**
  7213. * Defines the current scope used to restore the JS context
  7214. */
  7215. scope) {
  7216. if (scope === void 0) { scope = null; }
  7217. this.callback = callback;
  7218. this.mask = mask;
  7219. this.scope = scope;
  7220. /** @ignore */
  7221. this._willBeUnregistered = false;
  7222. /**
  7223. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  7224. */
  7225. this.unregisterOnNextCall = false;
  7226. }
  7227. return Observer;
  7228. }());
  7229. BABYLON.Observer = Observer;
  7230. /**
  7231. * Represent a list of observers registered to multiple Observables object.
  7232. */
  7233. var MultiObserver = /** @class */ (function () {
  7234. function MultiObserver() {
  7235. }
  7236. /**
  7237. * Release associated resources
  7238. */
  7239. MultiObserver.prototype.dispose = function () {
  7240. if (this._observers && this._observables) {
  7241. for (var index = 0; index < this._observers.length; index++) {
  7242. this._observables[index].remove(this._observers[index]);
  7243. }
  7244. }
  7245. this._observers = null;
  7246. this._observables = null;
  7247. };
  7248. /**
  7249. * Raise a callback when one of the observable will notify
  7250. * @param observables defines a list of observables to watch
  7251. * @param callback defines the callback to call on notification
  7252. * @param mask defines the mask used to filter notifications
  7253. * @param scope defines the current scope used to restore the JS context
  7254. * @returns the new MultiObserver
  7255. */
  7256. MultiObserver.Watch = function (observables, callback, mask, scope) {
  7257. if (mask === void 0) { mask = -1; }
  7258. if (scope === void 0) { scope = null; }
  7259. var result = new MultiObserver();
  7260. result._observers = new Array();
  7261. result._observables = observables;
  7262. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  7263. var observable = observables_1[_i];
  7264. var observer = observable.add(callback, mask, false, scope);
  7265. if (observer) {
  7266. result._observers.push(observer);
  7267. }
  7268. }
  7269. return result;
  7270. };
  7271. return MultiObserver;
  7272. }());
  7273. BABYLON.MultiObserver = MultiObserver;
  7274. /**
  7275. * The Observable class is a simple implementation of the Observable pattern.
  7276. * 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.
  7277. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  7278. * 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).
  7279. * 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.
  7280. */
  7281. var Observable = /** @class */ (function () {
  7282. /**
  7283. * Creates a new observable
  7284. * @param onObserverAdded defines a callback to call when a new observer is added
  7285. */
  7286. function Observable(onObserverAdded) {
  7287. this._observers = new Array();
  7288. this._eventState = new EventState(0);
  7289. if (onObserverAdded) {
  7290. this._onObserverAdded = onObserverAdded;
  7291. }
  7292. }
  7293. /**
  7294. * Create a new Observer with the specified callback
  7295. * @param callback the callback that will be executed for that Observer
  7296. * @param mask the mask used to filter observers
  7297. * @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.
  7298. * @param scope optional scope for the callback to be called from
  7299. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  7300. * @returns the new observer created for the callback
  7301. */
  7302. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  7303. if (mask === void 0) { mask = -1; }
  7304. if (insertFirst === void 0) { insertFirst = false; }
  7305. if (scope === void 0) { scope = null; }
  7306. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  7307. if (!callback) {
  7308. return null;
  7309. }
  7310. var observer = new Observer(callback, mask, scope);
  7311. observer.unregisterOnNextCall = unregisterOnFirstCall;
  7312. if (insertFirst) {
  7313. this._observers.unshift(observer);
  7314. }
  7315. else {
  7316. this._observers.push(observer);
  7317. }
  7318. if (this._onObserverAdded) {
  7319. this._onObserverAdded(observer);
  7320. }
  7321. return observer;
  7322. };
  7323. /**
  7324. * Remove an Observer from the Observable object
  7325. * @param observer the instance of the Observer to remove
  7326. * @returns false if it doesn't belong to this Observable
  7327. */
  7328. Observable.prototype.remove = function (observer) {
  7329. if (!observer) {
  7330. return false;
  7331. }
  7332. var index = this._observers.indexOf(observer);
  7333. if (index !== -1) {
  7334. this._observers.splice(index, 1);
  7335. return true;
  7336. }
  7337. return false;
  7338. };
  7339. /**
  7340. * Remove a callback from the Observable object
  7341. * @param callback the callback to remove
  7342. * @param scope optional scope. If used only the callbacks with this scope will be removed
  7343. * @returns false if it doesn't belong to this Observable
  7344. */
  7345. Observable.prototype.removeCallback = function (callback, scope) {
  7346. for (var index = 0; index < this._observers.length; index++) {
  7347. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  7348. this._observers.splice(index, 1);
  7349. return true;
  7350. }
  7351. }
  7352. return false;
  7353. };
  7354. Observable.prototype._deferUnregister = function (observer) {
  7355. var _this = this;
  7356. observer.unregisterOnNextCall = false;
  7357. observer._willBeUnregistered = true;
  7358. BABYLON.Tools.SetImmediate(function () {
  7359. _this.remove(observer);
  7360. });
  7361. };
  7362. /**
  7363. * Notify all Observers by calling their respective callback with the given data
  7364. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  7365. * @param eventData defines the data to send to all observers
  7366. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  7367. * @param target defines the original target of the state
  7368. * @param currentTarget defines the current target of the state
  7369. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  7370. */
  7371. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  7372. if (mask === void 0) { mask = -1; }
  7373. if (!this._observers.length) {
  7374. return true;
  7375. }
  7376. var state = this._eventState;
  7377. state.mask = mask;
  7378. state.target = target;
  7379. state.currentTarget = currentTarget;
  7380. state.skipNextObservers = false;
  7381. state.lastReturnValue = eventData;
  7382. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  7383. var obs = _a[_i];
  7384. if (obs._willBeUnregistered) {
  7385. continue;
  7386. }
  7387. if (obs.mask & mask) {
  7388. if (obs.scope) {
  7389. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  7390. }
  7391. else {
  7392. state.lastReturnValue = obs.callback(eventData, state);
  7393. }
  7394. if (obs.unregisterOnNextCall) {
  7395. this._deferUnregister(obs);
  7396. }
  7397. }
  7398. if (state.skipNextObservers) {
  7399. return false;
  7400. }
  7401. }
  7402. return true;
  7403. };
  7404. /**
  7405. * Calling this will execute each callback, expecting it to be a promise or return a value.
  7406. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  7407. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  7408. * and it is crucial that all callbacks will be executed.
  7409. * The order of the callbacks is kept, callbacks are not executed parallel.
  7410. *
  7411. * @param eventData The data to be sent to each callback
  7412. * @param mask is used to filter observers defaults to -1
  7413. * @param target defines the callback target (see EventState)
  7414. * @param currentTarget defines he current object in the bubbling phase
  7415. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  7416. */
  7417. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  7418. var _this = this;
  7419. if (mask === void 0) { mask = -1; }
  7420. // create an empty promise
  7421. var p = Promise.resolve(eventData);
  7422. // no observers? return this promise.
  7423. if (!this._observers.length) {
  7424. return p;
  7425. }
  7426. var state = this._eventState;
  7427. state.mask = mask;
  7428. state.target = target;
  7429. state.currentTarget = currentTarget;
  7430. state.skipNextObservers = false;
  7431. // execute one callback after another (not using Promise.all, the order is important)
  7432. this._observers.forEach(function (obs) {
  7433. if (state.skipNextObservers) {
  7434. return;
  7435. }
  7436. if (obs._willBeUnregistered) {
  7437. return;
  7438. }
  7439. if (obs.mask & mask) {
  7440. if (obs.scope) {
  7441. p = p.then(function (lastReturnedValue) {
  7442. state.lastReturnValue = lastReturnedValue;
  7443. return obs.callback.apply(obs.scope, [eventData, state]);
  7444. });
  7445. }
  7446. else {
  7447. p = p.then(function (lastReturnedValue) {
  7448. state.lastReturnValue = lastReturnedValue;
  7449. return obs.callback(eventData, state);
  7450. });
  7451. }
  7452. if (obs.unregisterOnNextCall) {
  7453. _this._deferUnregister(obs);
  7454. }
  7455. }
  7456. });
  7457. // return the eventData
  7458. return p.then(function () { return eventData; });
  7459. };
  7460. /**
  7461. * Notify a specific observer
  7462. * @param observer defines the observer to notify
  7463. * @param eventData defines the data to be sent to each callback
  7464. * @param mask is used to filter observers defaults to -1
  7465. */
  7466. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  7467. if (mask === void 0) { mask = -1; }
  7468. var state = this._eventState;
  7469. state.mask = mask;
  7470. state.skipNextObservers = false;
  7471. observer.callback(eventData, state);
  7472. };
  7473. /**
  7474. * Gets a boolean indicating if the observable has at least one observer
  7475. * @returns true is the Observable has at least one Observer registered
  7476. */
  7477. Observable.prototype.hasObservers = function () {
  7478. return this._observers.length > 0;
  7479. };
  7480. /**
  7481. * Clear the list of observers
  7482. */
  7483. Observable.prototype.clear = function () {
  7484. this._observers = new Array();
  7485. this._onObserverAdded = null;
  7486. };
  7487. /**
  7488. * Clone the current observable
  7489. * @returns a new observable
  7490. */
  7491. Observable.prototype.clone = function () {
  7492. var result = new Observable();
  7493. result._observers = this._observers.slice(0);
  7494. return result;
  7495. };
  7496. /**
  7497. * Does this observable handles observer registered with a given mask
  7498. * @param mask defines the mask to be tested
  7499. * @return whether or not one observer registered with the given mask is handeled
  7500. **/
  7501. Observable.prototype.hasSpecificMask = function (mask) {
  7502. if (mask === void 0) { mask = -1; }
  7503. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  7504. var obs = _a[_i];
  7505. if (obs.mask & mask || obs.mask === mask) {
  7506. return true;
  7507. }
  7508. }
  7509. return false;
  7510. };
  7511. return Observable;
  7512. }());
  7513. BABYLON.Observable = Observable;
  7514. })(BABYLON || (BABYLON = {}));
  7515. //# sourceMappingURL=babylon.observable.js.map
  7516. var BABYLON;
  7517. (function (BABYLON) {
  7518. var SmartArray = /** @class */ (function () {
  7519. function SmartArray(capacity) {
  7520. this.length = 0;
  7521. this.data = new Array(capacity);
  7522. this._id = SmartArray._GlobalId++;
  7523. }
  7524. SmartArray.prototype.push = function (value) {
  7525. this.data[this.length++] = value;
  7526. if (this.length > this.data.length) {
  7527. this.data.length *= 2;
  7528. }
  7529. };
  7530. SmartArray.prototype.forEach = function (func) {
  7531. for (var index = 0; index < this.length; index++) {
  7532. func(this.data[index]);
  7533. }
  7534. };
  7535. SmartArray.prototype.sort = function (compareFn) {
  7536. this.data.sort(compareFn);
  7537. };
  7538. SmartArray.prototype.reset = function () {
  7539. this.length = 0;
  7540. };
  7541. SmartArray.prototype.dispose = function () {
  7542. this.reset();
  7543. if (this.data) {
  7544. this.data.length = 0;
  7545. this.data = [];
  7546. }
  7547. };
  7548. SmartArray.prototype.concat = function (array) {
  7549. if (array.length === 0) {
  7550. return;
  7551. }
  7552. if (this.length + array.length > this.data.length) {
  7553. this.data.length = (this.length + array.length) * 2;
  7554. }
  7555. for (var index = 0; index < array.length; index++) {
  7556. this.data[this.length++] = (array.data || array)[index];
  7557. }
  7558. };
  7559. SmartArray.prototype.indexOf = function (value) {
  7560. var position = this.data.indexOf(value);
  7561. if (position >= this.length) {
  7562. return -1;
  7563. }
  7564. return position;
  7565. };
  7566. SmartArray.prototype.contains = function (value) {
  7567. return this.data.indexOf(value) !== -1;
  7568. };
  7569. // Statics
  7570. SmartArray._GlobalId = 0;
  7571. return SmartArray;
  7572. }());
  7573. BABYLON.SmartArray = SmartArray;
  7574. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  7575. __extends(SmartArrayNoDuplicate, _super);
  7576. function SmartArrayNoDuplicate() {
  7577. var _this = _super !== null && _super.apply(this, arguments) || this;
  7578. _this._duplicateId = 0;
  7579. return _this;
  7580. }
  7581. SmartArrayNoDuplicate.prototype.push = function (value) {
  7582. _super.prototype.push.call(this, value);
  7583. if (!value.__smartArrayFlags) {
  7584. value.__smartArrayFlags = {};
  7585. }
  7586. value.__smartArrayFlags[this._id] = this._duplicateId;
  7587. };
  7588. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  7589. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  7590. return false;
  7591. }
  7592. this.push(value);
  7593. return true;
  7594. };
  7595. SmartArrayNoDuplicate.prototype.reset = function () {
  7596. _super.prototype.reset.call(this);
  7597. this._duplicateId++;
  7598. };
  7599. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  7600. if (array.length === 0) {
  7601. return;
  7602. }
  7603. if (this.length + array.length > this.data.length) {
  7604. this.data.length = (this.length + array.length) * 2;
  7605. }
  7606. for (var index = 0; index < array.length; index++) {
  7607. var item = (array.data || array)[index];
  7608. this.pushNoDuplicate(item);
  7609. }
  7610. };
  7611. return SmartArrayNoDuplicate;
  7612. }(SmartArray));
  7613. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  7614. })(BABYLON || (BABYLON = {}));
  7615. //# sourceMappingURL=babylon.smartArray.js.map
  7616. var BABYLON;
  7617. (function (BABYLON) {
  7618. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  7619. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  7620. var LoadFileError = /** @class */ (function (_super) {
  7621. __extends(LoadFileError, _super);
  7622. function LoadFileError(message, request) {
  7623. var _this = _super.call(this, message) || this;
  7624. _this.request = request;
  7625. _this.name = "LoadFileError";
  7626. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  7627. return _this;
  7628. }
  7629. // Polyfill for Object.setPrototypeOf if necessary.
  7630. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  7631. return LoadFileError;
  7632. }(Error));
  7633. BABYLON.LoadFileError = LoadFileError;
  7634. var RetryStrategy = /** @class */ (function () {
  7635. function RetryStrategy() {
  7636. }
  7637. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  7638. if (maxRetries === void 0) { maxRetries = 3; }
  7639. if (baseInterval === void 0) { baseInterval = 500; }
  7640. return function (url, request, retryIndex) {
  7641. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  7642. return -1;
  7643. }
  7644. return Math.pow(2, retryIndex) * baseInterval;
  7645. };
  7646. };
  7647. return RetryStrategy;
  7648. }());
  7649. BABYLON.RetryStrategy = RetryStrategy;
  7650. // Screenshots
  7651. var screenshotCanvas;
  7652. var cloneValue = function (source, destinationObject) {
  7653. if (!source)
  7654. return null;
  7655. if (source instanceof BABYLON.Mesh) {
  7656. return null;
  7657. }
  7658. if (source instanceof BABYLON.SubMesh) {
  7659. return source.clone(destinationObject);
  7660. }
  7661. else if (source.clone) {
  7662. return source.clone();
  7663. }
  7664. return null;
  7665. };
  7666. var Tools = /** @class */ (function () {
  7667. function Tools() {
  7668. }
  7669. /**
  7670. * Interpolates between a and b via alpha
  7671. * @param a The lower value (returned when alpha = 0)
  7672. * @param b The upper value (returned when alpha = 1)
  7673. * @param alpha The interpolation-factor
  7674. * @return The mixed value
  7675. */
  7676. Tools.Mix = function (a, b, alpha) {
  7677. return a * (1 - alpha) + b * alpha;
  7678. };
  7679. Tools.Instantiate = function (className) {
  7680. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  7681. return Tools.RegisteredExternalClasses[className];
  7682. }
  7683. var arr = className.split(".");
  7684. var fn = (window || this);
  7685. for (var i = 0, len = arr.length; i < len; i++) {
  7686. fn = fn[arr[i]];
  7687. }
  7688. if (typeof fn !== "function") {
  7689. return null;
  7690. }
  7691. return fn;
  7692. };
  7693. /**
  7694. * Provides a slice function that will work even on IE
  7695. * @param data defines the array to slice
  7696. * @returns the new sliced array
  7697. */
  7698. Tools.Slice = function (data) {
  7699. if (data.slice) {
  7700. return data.slice();
  7701. }
  7702. return Array.prototype.slice.call(data);
  7703. };
  7704. Tools.SetImmediate = function (action) {
  7705. if (window.setImmediate) {
  7706. window.setImmediate(action);
  7707. }
  7708. else {
  7709. setTimeout(action, 1);
  7710. }
  7711. };
  7712. Tools.IsExponentOfTwo = function (value) {
  7713. var count = 1;
  7714. do {
  7715. count *= 2;
  7716. } while (count < value);
  7717. return count === value;
  7718. };
  7719. /**
  7720. * Find the next highest power of two.
  7721. * @param x Number to start search from.
  7722. * @return Next highest power of two.
  7723. */
  7724. Tools.CeilingPOT = function (x) {
  7725. x--;
  7726. x |= x >> 1;
  7727. x |= x >> 2;
  7728. x |= x >> 4;
  7729. x |= x >> 8;
  7730. x |= x >> 16;
  7731. x++;
  7732. return x;
  7733. };
  7734. /**
  7735. * Find the next lowest power of two.
  7736. * @param x Number to start search from.
  7737. * @return Next lowest power of two.
  7738. */
  7739. Tools.FloorPOT = function (x) {
  7740. x = x | (x >> 1);
  7741. x = x | (x >> 2);
  7742. x = x | (x >> 4);
  7743. x = x | (x >> 8);
  7744. x = x | (x >> 16);
  7745. return x - (x >> 1);
  7746. };
  7747. /**
  7748. * Find the nearest power of two.
  7749. * @param x Number to start search from.
  7750. * @return Next nearest power of two.
  7751. */
  7752. Tools.NearestPOT = function (x) {
  7753. var c = Tools.CeilingPOT(x);
  7754. var f = Tools.FloorPOT(x);
  7755. return (c - x) > (x - f) ? f : c;
  7756. };
  7757. Tools.GetExponentOfTwo = function (value, max, mode) {
  7758. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  7759. var pot;
  7760. switch (mode) {
  7761. case BABYLON.Engine.SCALEMODE_FLOOR:
  7762. pot = Tools.FloorPOT(value);
  7763. break;
  7764. case BABYLON.Engine.SCALEMODE_NEAREST:
  7765. pot = Tools.NearestPOT(value);
  7766. break;
  7767. case BABYLON.Engine.SCALEMODE_CEILING:
  7768. default:
  7769. pot = Tools.CeilingPOT(value);
  7770. break;
  7771. }
  7772. return Math.min(pot, max);
  7773. };
  7774. Tools.GetFilename = function (path) {
  7775. var index = path.lastIndexOf("/");
  7776. if (index < 0)
  7777. return path;
  7778. return path.substring(index + 1);
  7779. };
  7780. /**
  7781. * Extracts the "folder" part of a path (everything before the filename).
  7782. * @param uri The URI to extract the info from
  7783. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  7784. * @returns The "folder" part of the path
  7785. */
  7786. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  7787. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  7788. var index = uri.lastIndexOf("/");
  7789. if (index < 0) {
  7790. if (returnUnchangedIfNoSlash) {
  7791. return uri;
  7792. }
  7793. return "";
  7794. }
  7795. return uri.substring(0, index + 1);
  7796. };
  7797. Tools.GetDOMTextContent = function (element) {
  7798. var result = "";
  7799. var child = element.firstChild;
  7800. while (child) {
  7801. if (child.nodeType === 3) {
  7802. result += child.textContent;
  7803. }
  7804. child = child.nextSibling;
  7805. }
  7806. return result;
  7807. };
  7808. Tools.ToDegrees = function (angle) {
  7809. return angle * 180 / Math.PI;
  7810. };
  7811. Tools.ToRadians = function (angle) {
  7812. return angle * Math.PI / 180;
  7813. };
  7814. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  7815. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  7816. var output = "";
  7817. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  7818. var i = 0;
  7819. var bytes = new Uint8Array(buffer);
  7820. while (i < bytes.length) {
  7821. chr1 = bytes[i++];
  7822. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  7823. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  7824. enc1 = chr1 >> 2;
  7825. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  7826. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  7827. enc4 = chr3 & 63;
  7828. if (isNaN(chr2)) {
  7829. enc3 = enc4 = 64;
  7830. }
  7831. else if (isNaN(chr3)) {
  7832. enc4 = 64;
  7833. }
  7834. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  7835. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  7836. }
  7837. return "data:image/png;base64," + output;
  7838. };
  7839. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  7840. if (bias === void 0) { bias = null; }
  7841. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  7842. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  7843. for (var index = indexStart; index < indexStart + indexCount; index++) {
  7844. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  7845. minimum = BABYLON.Vector3.Minimize(current, minimum);
  7846. maximum = BABYLON.Vector3.Maximize(current, maximum);
  7847. }
  7848. if (bias) {
  7849. minimum.x -= minimum.x * bias.x + bias.y;
  7850. minimum.y -= minimum.y * bias.x + bias.y;
  7851. minimum.z -= minimum.z * bias.x + bias.y;
  7852. maximum.x += maximum.x * bias.x + bias.y;
  7853. maximum.y += maximum.y * bias.x + bias.y;
  7854. maximum.z += maximum.z * bias.x + bias.y;
  7855. }
  7856. return {
  7857. minimum: minimum,
  7858. maximum: maximum
  7859. };
  7860. };
  7861. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  7862. if (bias === void 0) { bias = null; }
  7863. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  7864. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  7865. if (!stride) {
  7866. stride = 3;
  7867. }
  7868. for (var index = start; index < start + count; index++) {
  7869. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  7870. minimum = BABYLON.Vector3.Minimize(current, minimum);
  7871. maximum = BABYLON.Vector3.Maximize(current, maximum);
  7872. }
  7873. if (bias) {
  7874. minimum.x -= minimum.x * bias.x + bias.y;
  7875. minimum.y -= minimum.y * bias.x + bias.y;
  7876. minimum.z -= minimum.z * bias.x + bias.y;
  7877. maximum.x += maximum.x * bias.x + bias.y;
  7878. maximum.y += maximum.y * bias.x + bias.y;
  7879. maximum.z += maximum.z * bias.x + bias.y;
  7880. }
  7881. return {
  7882. minimum: minimum,
  7883. maximum: maximum
  7884. };
  7885. };
  7886. Tools.Vector2ArrayFeeder = function (array) {
  7887. return function (index) {
  7888. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  7889. var length = isFloatArray ? array.length / 2 : array.length;
  7890. if (index >= length) {
  7891. return null;
  7892. }
  7893. if (isFloatArray) {
  7894. var fa = array;
  7895. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  7896. }
  7897. var a = array;
  7898. return a[index];
  7899. };
  7900. };
  7901. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  7902. if (bias === void 0) { bias = null; }
  7903. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  7904. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  7905. var i = 0;
  7906. var cur = feeder(i++);
  7907. while (cur) {
  7908. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  7909. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  7910. cur = feeder(i++);
  7911. }
  7912. if (bias) {
  7913. minimum.x -= minimum.x * bias.x + bias.y;
  7914. minimum.y -= minimum.y * bias.x + bias.y;
  7915. maximum.x += maximum.x * bias.x + bias.y;
  7916. maximum.y += maximum.y * bias.x + bias.y;
  7917. }
  7918. return {
  7919. minimum: minimum,
  7920. maximum: maximum
  7921. };
  7922. };
  7923. Tools.MakeArray = function (obj, allowsNullUndefined) {
  7924. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  7925. return null;
  7926. return Array.isArray(obj) ? obj : [obj];
  7927. };
  7928. // Misc.
  7929. Tools.GetPointerPrefix = function () {
  7930. var eventPrefix = "pointer";
  7931. // Check if pointer events are supported
  7932. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  7933. eventPrefix = "mouse";
  7934. }
  7935. return eventPrefix;
  7936. };
  7937. /**
  7938. * @param func - the function to be called
  7939. * @param requester - the object that will request the next frame. Falls back to window.
  7940. */
  7941. Tools.QueueNewFrame = function (func, requester) {
  7942. if (!Tools.IsWindowObjectExist()) {
  7943. return setTimeout(func, 16);
  7944. }
  7945. if (!requester) {
  7946. requester = window;
  7947. }
  7948. if (requester.requestAnimationFrame) {
  7949. return requester.requestAnimationFrame(func);
  7950. }
  7951. else if (requester.msRequestAnimationFrame) {
  7952. return requester.msRequestAnimationFrame(func);
  7953. }
  7954. else if (requester.webkitRequestAnimationFrame) {
  7955. return requester.webkitRequestAnimationFrame(func);
  7956. }
  7957. else if (requester.mozRequestAnimationFrame) {
  7958. return requester.mozRequestAnimationFrame(func);
  7959. }
  7960. else if (requester.oRequestAnimationFrame) {
  7961. return requester.oRequestAnimationFrame(func);
  7962. }
  7963. else {
  7964. return window.setTimeout(func, 16);
  7965. }
  7966. };
  7967. Tools.RequestFullscreen = function (element) {
  7968. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  7969. if (!requestFunction)
  7970. return;
  7971. requestFunction.call(element);
  7972. };
  7973. Tools.ExitFullscreen = function () {
  7974. if (document.exitFullscreen) {
  7975. document.exitFullscreen();
  7976. }
  7977. else if (document.mozCancelFullScreen) {
  7978. document.mozCancelFullScreen();
  7979. }
  7980. else if (document.webkitCancelFullScreen) {
  7981. document.webkitCancelFullScreen();
  7982. }
  7983. else if (document.msCancelFullScreen) {
  7984. document.msCancelFullScreen();
  7985. }
  7986. };
  7987. Tools.SetCorsBehavior = function (url, element) {
  7988. if (url && url.indexOf("data:") === 0) {
  7989. return;
  7990. }
  7991. if (Tools.CorsBehavior) {
  7992. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  7993. element.crossOrigin = Tools.CorsBehavior;
  7994. }
  7995. else {
  7996. var result = Tools.CorsBehavior(url);
  7997. if (result) {
  7998. element.crossOrigin = result;
  7999. }
  8000. }
  8001. }
  8002. };
  8003. // External files
  8004. Tools.CleanUrl = function (url) {
  8005. url = url.replace(/#/mg, "%23");
  8006. return url;
  8007. };
  8008. Tools.LoadImage = function (url, onLoad, onError, database) {
  8009. if (url instanceof ArrayBuffer) {
  8010. url = Tools.EncodeArrayBufferTobase64(url);
  8011. }
  8012. url = Tools.CleanUrl(url);
  8013. url = Tools.PreprocessUrl(url);
  8014. var img = new Image();
  8015. Tools.SetCorsBehavior(url, img);
  8016. img.onload = function () {
  8017. onLoad(img);
  8018. };
  8019. img.onerror = function (err) {
  8020. Tools.Error("Error while trying to load image: " + url);
  8021. if (onError) {
  8022. onError("Error while trying to load image: " + url, err);
  8023. }
  8024. };
  8025. var noIndexedDB = function () {
  8026. img.src = url;
  8027. };
  8028. var loadFromIndexedDB = function () {
  8029. if (database) {
  8030. database.loadImageFromDB(url, img);
  8031. }
  8032. };
  8033. //ANY database to do!
  8034. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  8035. database.openAsync(loadFromIndexedDB, noIndexedDB);
  8036. }
  8037. else {
  8038. if (url.indexOf("file:") !== -1) {
  8039. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  8040. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  8041. try {
  8042. var blobURL;
  8043. try {
  8044. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  8045. }
  8046. catch (ex) {
  8047. // Chrome doesn't support oneTimeOnly parameter
  8048. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  8049. }
  8050. img.src = blobURL;
  8051. }
  8052. catch (e) {
  8053. img.src = "";
  8054. }
  8055. return img;
  8056. }
  8057. }
  8058. noIndexedDB();
  8059. }
  8060. return img;
  8061. };
  8062. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  8063. url = Tools.CleanUrl(url);
  8064. url = Tools.PreprocessUrl(url);
  8065. // If file and file input are set
  8066. if (url.indexOf("file:") !== -1) {
  8067. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  8068. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  8069. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  8070. }
  8071. }
  8072. var loadUrl = Tools.BaseUrl + url;
  8073. var aborted = false;
  8074. var fileRequest = {
  8075. onCompleteObservable: new BABYLON.Observable(),
  8076. abort: function () { return aborted = true; },
  8077. };
  8078. var requestFile = function () {
  8079. var request = new XMLHttpRequest();
  8080. var retryHandle = null;
  8081. fileRequest.abort = function () {
  8082. aborted = true;
  8083. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  8084. request.abort();
  8085. }
  8086. if (retryHandle !== null) {
  8087. clearTimeout(retryHandle);
  8088. retryHandle = null;
  8089. }
  8090. };
  8091. var retryLoop = function (retryIndex) {
  8092. request.open('GET', loadUrl, true);
  8093. if (useArrayBuffer) {
  8094. request.responseType = "arraybuffer";
  8095. }
  8096. if (onProgress) {
  8097. request.addEventListener("progress", onProgress);
  8098. }
  8099. var onLoadEnd = function () {
  8100. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8101. };
  8102. request.addEventListener("loadend", onLoadEnd);
  8103. var onReadyStateChange = function () {
  8104. if (aborted) {
  8105. return;
  8106. }
  8107. // In case of undefined state in some browsers.
  8108. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  8109. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  8110. request.removeEventListener("readystatechange", onReadyStateChange);
  8111. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  8112. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  8113. return;
  8114. }
  8115. var retryStrategy = Tools.DefaultRetryStrategy;
  8116. if (retryStrategy) {
  8117. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  8118. if (waitTime !== -1) {
  8119. // Prevent the request from completing for retry.
  8120. request.removeEventListener("loadend", onLoadEnd);
  8121. request = new XMLHttpRequest();
  8122. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  8123. return;
  8124. }
  8125. }
  8126. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  8127. if (onError) {
  8128. onError(request, e);
  8129. }
  8130. else {
  8131. throw e;
  8132. }
  8133. }
  8134. };
  8135. request.addEventListener("readystatechange", onReadyStateChange);
  8136. request.send();
  8137. };
  8138. retryLoop(0);
  8139. };
  8140. // Caching all files
  8141. if (database && database.enableSceneOffline) {
  8142. var noIndexedDB_1 = function () {
  8143. if (!aborted) {
  8144. requestFile();
  8145. }
  8146. };
  8147. var loadFromIndexedDB = function () {
  8148. // TODO: database needs to support aborting and should return a IFileRequest
  8149. if (aborted) {
  8150. return;
  8151. }
  8152. if (database) {
  8153. database.loadFileFromDB(url, function (data) {
  8154. if (!aborted) {
  8155. onSuccess(data);
  8156. }
  8157. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8158. }, onProgress ? function (event) {
  8159. if (!aborted) {
  8160. onProgress(event);
  8161. }
  8162. } : undefined, noIndexedDB_1, useArrayBuffer);
  8163. }
  8164. };
  8165. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  8166. }
  8167. else {
  8168. requestFile();
  8169. }
  8170. return fileRequest;
  8171. };
  8172. /**
  8173. * Load a script (identified by an url). When the url returns, the
  8174. * content of this file is added into a new script element, attached to the DOM (body element)
  8175. */
  8176. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  8177. var head = document.getElementsByTagName('head')[0];
  8178. var script = document.createElement('script');
  8179. script.type = 'text/javascript';
  8180. script.src = scriptUrl;
  8181. script.onload = function () {
  8182. if (onSuccess) {
  8183. onSuccess();
  8184. }
  8185. };
  8186. script.onerror = function (e) {
  8187. if (onError) {
  8188. onError("Unable to load script", e);
  8189. }
  8190. };
  8191. head.appendChild(script);
  8192. };
  8193. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  8194. var reader = new FileReader();
  8195. var request = {
  8196. onCompleteObservable: new BABYLON.Observable(),
  8197. abort: function () { return reader.abort(); },
  8198. };
  8199. reader.onloadend = function (e) {
  8200. request.onCompleteObservable.notifyObservers(request);
  8201. };
  8202. reader.onload = function (e) {
  8203. //target doesn't have result from ts 1.3
  8204. callback(e.target['result']);
  8205. };
  8206. reader.onprogress = progressCallback;
  8207. reader.readAsDataURL(fileToLoad);
  8208. return request;
  8209. };
  8210. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  8211. var reader = new FileReader();
  8212. var request = {
  8213. onCompleteObservable: new BABYLON.Observable(),
  8214. abort: function () { return reader.abort(); },
  8215. };
  8216. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  8217. reader.onerror = function (e) {
  8218. Tools.Log("Error while reading file: " + fileToLoad.name);
  8219. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  8220. };
  8221. reader.onload = function (e) {
  8222. //target doesn't have result from ts 1.3
  8223. callback(e.target['result']);
  8224. };
  8225. if (progressCallBack) {
  8226. reader.onprogress = progressCallBack;
  8227. }
  8228. if (!useArrayBuffer) {
  8229. // Asynchronous read
  8230. reader.readAsText(fileToLoad);
  8231. }
  8232. else {
  8233. reader.readAsArrayBuffer(fileToLoad);
  8234. }
  8235. return request;
  8236. };
  8237. //returns a downloadable url to a file content.
  8238. Tools.FileAsURL = function (content) {
  8239. var fileBlob = new Blob([content]);
  8240. var url = window.URL || window.webkitURL;
  8241. var link = url.createObjectURL(fileBlob);
  8242. return link;
  8243. };
  8244. // Misc.
  8245. Tools.Format = function (value, decimals) {
  8246. if (decimals === void 0) { decimals = 2; }
  8247. return value.toFixed(decimals);
  8248. };
  8249. Tools.CheckExtends = function (v, min, max) {
  8250. if (v.x < min.x)
  8251. min.x = v.x;
  8252. if (v.y < min.y)
  8253. min.y = v.y;
  8254. if (v.z < min.z)
  8255. min.z = v.z;
  8256. if (v.x > max.x)
  8257. max.x = v.x;
  8258. if (v.y > max.y)
  8259. max.y = v.y;
  8260. if (v.z > max.z)
  8261. max.z = v.z;
  8262. };
  8263. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  8264. for (var prop in source) {
  8265. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  8266. continue;
  8267. }
  8268. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  8269. continue;
  8270. }
  8271. var sourceValue = source[prop];
  8272. var typeOfSourceValue = typeof sourceValue;
  8273. if (typeOfSourceValue === "function") {
  8274. continue;
  8275. }
  8276. if (typeOfSourceValue === "object") {
  8277. if (sourceValue instanceof Array) {
  8278. destination[prop] = [];
  8279. if (sourceValue.length > 0) {
  8280. if (typeof sourceValue[0] == "object") {
  8281. for (var index = 0; index < sourceValue.length; index++) {
  8282. var clonedValue = cloneValue(sourceValue[index], destination);
  8283. if (destination[prop].indexOf(clonedValue) === -1) {
  8284. destination[prop].push(clonedValue);
  8285. }
  8286. }
  8287. }
  8288. else {
  8289. destination[prop] = sourceValue.slice(0);
  8290. }
  8291. }
  8292. }
  8293. else {
  8294. destination[prop] = cloneValue(sourceValue, destination);
  8295. }
  8296. }
  8297. else {
  8298. destination[prop] = sourceValue;
  8299. }
  8300. }
  8301. };
  8302. Tools.IsEmpty = function (obj) {
  8303. for (var i in obj) {
  8304. if (obj.hasOwnProperty(i)) {
  8305. return false;
  8306. }
  8307. }
  8308. return true;
  8309. };
  8310. Tools.RegisterTopRootEvents = function (events) {
  8311. for (var index = 0; index < events.length; index++) {
  8312. var event = events[index];
  8313. window.addEventListener(event.name, event.handler, false);
  8314. try {
  8315. if (window.parent) {
  8316. window.parent.addEventListener(event.name, event.handler, false);
  8317. }
  8318. }
  8319. catch (e) {
  8320. // Silently fails...
  8321. }
  8322. }
  8323. };
  8324. Tools.UnregisterTopRootEvents = function (events) {
  8325. for (var index = 0; index < events.length; index++) {
  8326. var event = events[index];
  8327. window.removeEventListener(event.name, event.handler);
  8328. try {
  8329. if (window.parent) {
  8330. window.parent.removeEventListener(event.name, event.handler);
  8331. }
  8332. }
  8333. catch (e) {
  8334. // Silently fails...
  8335. }
  8336. }
  8337. };
  8338. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  8339. if (mimeType === void 0) { mimeType = "image/png"; }
  8340. // Read the contents of the framebuffer
  8341. var numberOfChannelsByLine = width * 4;
  8342. var halfHeight = height / 2;
  8343. //Reading datas from WebGL
  8344. var data = engine.readPixels(0, 0, width, height);
  8345. //To flip image on Y axis.
  8346. for (var i = 0; i < halfHeight; i++) {
  8347. for (var j = 0; j < numberOfChannelsByLine; j++) {
  8348. var currentCell = j + i * numberOfChannelsByLine;
  8349. var targetLine = height - i - 1;
  8350. var targetCell = j + targetLine * numberOfChannelsByLine;
  8351. var temp = data[currentCell];
  8352. data[currentCell] = data[targetCell];
  8353. data[targetCell] = temp;
  8354. }
  8355. }
  8356. // Create a 2D canvas to store the result
  8357. if (!screenshotCanvas) {
  8358. screenshotCanvas = document.createElement('canvas');
  8359. }
  8360. screenshotCanvas.width = width;
  8361. screenshotCanvas.height = height;
  8362. var context = screenshotCanvas.getContext('2d');
  8363. if (context) {
  8364. // Copy the pixels to a 2D canvas
  8365. var imageData = context.createImageData(width, height);
  8366. var castData = (imageData.data);
  8367. castData.set(data);
  8368. context.putImageData(imageData, 0, 0);
  8369. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  8370. }
  8371. };
  8372. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  8373. if (mimeType === void 0) { mimeType = "image/png"; }
  8374. var base64Image = screenshotCanvas.toDataURL(mimeType);
  8375. if (successCallback) {
  8376. successCallback(base64Image);
  8377. }
  8378. else {
  8379. // We need HTMLCanvasElement.toBlob for HD screenshots
  8380. if (!screenshotCanvas.toBlob) {
  8381. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  8382. screenshotCanvas.toBlob = function (callback, type, quality) {
  8383. var _this = this;
  8384. setTimeout(function () {
  8385. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  8386. for (var i = 0; i < len; i++) {
  8387. arr[i] = binStr.charCodeAt(i);
  8388. }
  8389. callback(new Blob([arr], { type: type || 'image/png' }));
  8390. });
  8391. };
  8392. }
  8393. screenshotCanvas.toBlob(function (blob) {
  8394. var url = URL.createObjectURL(blob);
  8395. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  8396. if (("download" in document.createElement("a"))) {
  8397. var a = window.document.createElement("a");
  8398. a.href = url;
  8399. if (fileName) {
  8400. a.setAttribute("download", fileName);
  8401. }
  8402. else {
  8403. var date = new Date();
  8404. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  8405. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  8406. }
  8407. window.document.body.appendChild(a);
  8408. a.addEventListener("click", function () {
  8409. if (a.parentElement) {
  8410. a.parentElement.removeChild(a);
  8411. }
  8412. });
  8413. a.click();
  8414. }
  8415. else {
  8416. var newWindow = window.open("");
  8417. if (!newWindow)
  8418. return;
  8419. var img = newWindow.document.createElement("img");
  8420. img.onload = function () {
  8421. // no longer need to read the blob so it's revoked
  8422. URL.revokeObjectURL(url);
  8423. };
  8424. img.src = url;
  8425. newWindow.document.body.appendChild(img);
  8426. }
  8427. });
  8428. }
  8429. };
  8430. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  8431. if (mimeType === void 0) { mimeType = "image/png"; }
  8432. var width;
  8433. var height;
  8434. // If a precision value is specified
  8435. if (size.precision) {
  8436. width = Math.round(engine.getRenderWidth() * size.precision);
  8437. height = Math.round(width / engine.getAspectRatio(camera));
  8438. }
  8439. else if (size.width && size.height) {
  8440. width = size.width;
  8441. height = size.height;
  8442. }
  8443. else if (size.width && !size.height) {
  8444. width = size.width;
  8445. height = Math.round(width / engine.getAspectRatio(camera));
  8446. }
  8447. else if (size.height && !size.width) {
  8448. height = size.height;
  8449. width = Math.round(height * engine.getAspectRatio(camera));
  8450. }
  8451. else if (!isNaN(size)) {
  8452. height = size;
  8453. width = size;
  8454. }
  8455. else {
  8456. Tools.Error("Invalid 'size' parameter !");
  8457. return;
  8458. }
  8459. if (!screenshotCanvas) {
  8460. screenshotCanvas = document.createElement('canvas');
  8461. }
  8462. screenshotCanvas.width = width;
  8463. screenshotCanvas.height = height;
  8464. var renderContext = screenshotCanvas.getContext("2d");
  8465. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  8466. var newWidth = width;
  8467. var newHeight = newWidth / ratio;
  8468. if (newHeight > height) {
  8469. newHeight = height;
  8470. newWidth = newHeight * ratio;
  8471. }
  8472. var offsetX = Math.max(0, width - newWidth) / 2;
  8473. var offsetY = Math.max(0, height - newHeight) / 2;
  8474. var renderingCanvas = engine.getRenderingCanvas();
  8475. if (renderContext && renderingCanvas) {
  8476. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  8477. }
  8478. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  8479. };
  8480. /**
  8481. * Generates an image screenshot from the specified camera.
  8482. *
  8483. * @param engine The engine to use for rendering
  8484. * @param camera The camera to use for rendering
  8485. * @param size This parameter can be set to a single number or to an object with the
  8486. * following (optional) properties: precision, width, height. If a single number is passed,
  8487. * it will be used for both width and height. If an object is passed, the screenshot size
  8488. * will be derived from the parameters. The precision property is a multiplier allowing
  8489. * rendering at a higher or lower resolution.
  8490. * @param successCallback The callback receives a single parameter which contains the
  8491. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  8492. * src parameter of an <img> to display it.
  8493. * @param mimeType The MIME type of the screenshot image (default: image/png).
  8494. * Check your browser for supported MIME types.
  8495. * @param samples Texture samples (default: 1)
  8496. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  8497. * @param fileName A name for for the downloaded file.
  8498. * @constructor
  8499. */
  8500. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  8501. if (mimeType === void 0) { mimeType = "image/png"; }
  8502. if (samples === void 0) { samples = 1; }
  8503. if (antialiasing === void 0) { antialiasing = false; }
  8504. var width;
  8505. var height;
  8506. //If a precision value is specified
  8507. if (size.precision) {
  8508. width = Math.round(engine.getRenderWidth() * size.precision);
  8509. height = Math.round(width / engine.getAspectRatio(camera));
  8510. size = { width: width, height: height };
  8511. }
  8512. else if (size.width && size.height) {
  8513. width = size.width;
  8514. height = size.height;
  8515. }
  8516. else if (size.width && !size.height) {
  8517. width = size.width;
  8518. height = Math.round(width / engine.getAspectRatio(camera));
  8519. size = { width: width, height: height };
  8520. }
  8521. else if (size.height && !size.width) {
  8522. height = size.height;
  8523. width = Math.round(height * engine.getAspectRatio(camera));
  8524. size = { width: width, height: height };
  8525. }
  8526. else if (!isNaN(size)) {
  8527. height = size;
  8528. width = size;
  8529. }
  8530. else {
  8531. Tools.Error("Invalid 'size' parameter !");
  8532. return;
  8533. }
  8534. var scene = camera.getScene();
  8535. var previousCamera = null;
  8536. if (scene.activeCamera !== camera) {
  8537. previousCamera = scene.activeCamera;
  8538. scene.activeCamera = camera;
  8539. }
  8540. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  8541. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8542. texture.renderList = null;
  8543. texture.samples = samples;
  8544. if (antialiasing) {
  8545. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  8546. }
  8547. texture.onAfterRenderObservable.add(function () {
  8548. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  8549. });
  8550. scene.incrementRenderId();
  8551. scene.resetCachedMaterial();
  8552. texture.render(true);
  8553. texture.dispose();
  8554. if (previousCamera) {
  8555. scene.activeCamera = previousCamera;
  8556. }
  8557. camera.getProjectionMatrix(true); // Force cache refresh;
  8558. };
  8559. // XHR response validator for local file scenario
  8560. Tools.ValidateXHRData = function (xhr, dataType) {
  8561. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  8562. if (dataType === void 0) { dataType = 7; }
  8563. try {
  8564. if (dataType & 1) {
  8565. if (xhr.responseText && xhr.responseText.length > 0) {
  8566. return true;
  8567. }
  8568. else if (dataType === 1) {
  8569. return false;
  8570. }
  8571. }
  8572. if (dataType & 2) {
  8573. // Check header width and height since there is no "TGA" magic number
  8574. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  8575. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  8576. return true;
  8577. }
  8578. else if (dataType === 2) {
  8579. return false;
  8580. }
  8581. }
  8582. if (dataType & 4) {
  8583. // Check for the "DDS" magic number
  8584. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  8585. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  8586. return true;
  8587. }
  8588. else {
  8589. return false;
  8590. }
  8591. }
  8592. }
  8593. catch (e) {
  8594. // Global protection
  8595. }
  8596. return false;
  8597. };
  8598. /**
  8599. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  8600. * Be aware Math.random() could cause collisions, but:
  8601. * "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"
  8602. */
  8603. Tools.RandomId = function () {
  8604. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  8605. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  8606. return v.toString(16);
  8607. });
  8608. };
  8609. /**
  8610. * Test if the given uri is a base64 string.
  8611. * @param uri The uri to test
  8612. * @return True if the uri is a base64 string or false otherwise.
  8613. */
  8614. Tools.IsBase64 = function (uri) {
  8615. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  8616. };
  8617. /**
  8618. * Decode the given base64 uri.
  8619. * @param uri The uri to decode
  8620. * @return The decoded base64 data.
  8621. */
  8622. Tools.DecodeBase64 = function (uri) {
  8623. var decodedString = atob(uri.split(",")[1]);
  8624. var bufferLength = decodedString.length;
  8625. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  8626. for (var i = 0; i < bufferLength; i++) {
  8627. bufferView[i] = decodedString.charCodeAt(i);
  8628. }
  8629. return bufferView.buffer;
  8630. };
  8631. Object.defineProperty(Tools, "NoneLogLevel", {
  8632. get: function () {
  8633. return Tools._NoneLogLevel;
  8634. },
  8635. enumerable: true,
  8636. configurable: true
  8637. });
  8638. Object.defineProperty(Tools, "MessageLogLevel", {
  8639. get: function () {
  8640. return Tools._MessageLogLevel;
  8641. },
  8642. enumerable: true,
  8643. configurable: true
  8644. });
  8645. Object.defineProperty(Tools, "WarningLogLevel", {
  8646. get: function () {
  8647. return Tools._WarningLogLevel;
  8648. },
  8649. enumerable: true,
  8650. configurable: true
  8651. });
  8652. Object.defineProperty(Tools, "ErrorLogLevel", {
  8653. get: function () {
  8654. return Tools._ErrorLogLevel;
  8655. },
  8656. enumerable: true,
  8657. configurable: true
  8658. });
  8659. Object.defineProperty(Tools, "AllLogLevel", {
  8660. get: function () {
  8661. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  8662. },
  8663. enumerable: true,
  8664. configurable: true
  8665. });
  8666. Tools._AddLogEntry = function (entry) {
  8667. Tools._LogCache = entry + Tools._LogCache;
  8668. if (Tools.OnNewCacheEntry) {
  8669. Tools.OnNewCacheEntry(entry);
  8670. }
  8671. };
  8672. Tools._FormatMessage = function (message) {
  8673. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  8674. var date = new Date();
  8675. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  8676. };
  8677. Tools._LogDisabled = function (message) {
  8678. // nothing to do
  8679. };
  8680. Tools._LogEnabled = function (message) {
  8681. var formattedMessage = Tools._FormatMessage(message);
  8682. console.log("BJS - " + formattedMessage);
  8683. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  8684. Tools._AddLogEntry(entry);
  8685. };
  8686. Tools._WarnDisabled = function (message) {
  8687. // nothing to do
  8688. };
  8689. Tools._WarnEnabled = function (message) {
  8690. var formattedMessage = Tools._FormatMessage(message);
  8691. console.warn("BJS - " + formattedMessage);
  8692. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  8693. Tools._AddLogEntry(entry);
  8694. };
  8695. Tools._ErrorDisabled = function (message) {
  8696. // nothing to do
  8697. };
  8698. Tools._ErrorEnabled = function (message) {
  8699. Tools.errorsCount++;
  8700. var formattedMessage = Tools._FormatMessage(message);
  8701. console.error("BJS - " + formattedMessage);
  8702. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  8703. Tools._AddLogEntry(entry);
  8704. };
  8705. Object.defineProperty(Tools, "LogCache", {
  8706. get: function () {
  8707. return Tools._LogCache;
  8708. },
  8709. enumerable: true,
  8710. configurable: true
  8711. });
  8712. Tools.ClearLogCache = function () {
  8713. Tools._LogCache = "";
  8714. Tools.errorsCount = 0;
  8715. };
  8716. Object.defineProperty(Tools, "LogLevels", {
  8717. set: function (level) {
  8718. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  8719. Tools.Log = Tools._LogEnabled;
  8720. }
  8721. else {
  8722. Tools.Log = Tools._LogDisabled;
  8723. }
  8724. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  8725. Tools.Warn = Tools._WarnEnabled;
  8726. }
  8727. else {
  8728. Tools.Warn = Tools._WarnDisabled;
  8729. }
  8730. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  8731. Tools.Error = Tools._ErrorEnabled;
  8732. }
  8733. else {
  8734. Tools.Error = Tools._ErrorDisabled;
  8735. }
  8736. },
  8737. enumerable: true,
  8738. configurable: true
  8739. });
  8740. Tools.IsWindowObjectExist = function () {
  8741. return (typeof window) !== "undefined";
  8742. };
  8743. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  8744. get: function () {
  8745. return Tools._PerformanceNoneLogLevel;
  8746. },
  8747. enumerable: true,
  8748. configurable: true
  8749. });
  8750. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  8751. get: function () {
  8752. return Tools._PerformanceUserMarkLogLevel;
  8753. },
  8754. enumerable: true,
  8755. configurable: true
  8756. });
  8757. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  8758. get: function () {
  8759. return Tools._PerformanceConsoleLogLevel;
  8760. },
  8761. enumerable: true,
  8762. configurable: true
  8763. });
  8764. Object.defineProperty(Tools, "PerformanceLogLevel", {
  8765. set: function (level) {
  8766. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  8767. Tools.StartPerformanceCounter = Tools._StartUserMark;
  8768. Tools.EndPerformanceCounter = Tools._EndUserMark;
  8769. return;
  8770. }
  8771. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  8772. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  8773. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  8774. return;
  8775. }
  8776. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  8777. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  8778. },
  8779. enumerable: true,
  8780. configurable: true
  8781. });
  8782. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  8783. };
  8784. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  8785. };
  8786. Tools._StartUserMark = function (counterName, condition) {
  8787. if (condition === void 0) { condition = true; }
  8788. if (!Tools._performance) {
  8789. if (!Tools.IsWindowObjectExist()) {
  8790. return;
  8791. }
  8792. Tools._performance = window.performance;
  8793. }
  8794. if (!condition || !Tools._performance.mark) {
  8795. return;
  8796. }
  8797. Tools._performance.mark(counterName + "-Begin");
  8798. };
  8799. Tools._EndUserMark = function (counterName, condition) {
  8800. if (condition === void 0) { condition = true; }
  8801. if (!condition || !Tools._performance.mark) {
  8802. return;
  8803. }
  8804. Tools._performance.mark(counterName + "-End");
  8805. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  8806. };
  8807. Tools._StartPerformanceConsole = function (counterName, condition) {
  8808. if (condition === void 0) { condition = true; }
  8809. if (!condition) {
  8810. return;
  8811. }
  8812. Tools._StartUserMark(counterName, condition);
  8813. if (console.time) {
  8814. console.time(counterName);
  8815. }
  8816. };
  8817. Tools._EndPerformanceConsole = function (counterName, condition) {
  8818. if (condition === void 0) { condition = true; }
  8819. if (!condition) {
  8820. return;
  8821. }
  8822. Tools._EndUserMark(counterName, condition);
  8823. if (console.time) {
  8824. console.timeEnd(counterName);
  8825. }
  8826. };
  8827. Object.defineProperty(Tools, "Now", {
  8828. get: function () {
  8829. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  8830. return window.performance.now();
  8831. }
  8832. return new Date().getTime();
  8833. },
  8834. enumerable: true,
  8835. configurable: true
  8836. });
  8837. /**
  8838. * This method will return the name of the class used to create the instance of the given object.
  8839. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  8840. * @param object the object to get the class name from
  8841. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  8842. */
  8843. Tools.GetClassName = function (object, isType) {
  8844. if (isType === void 0) { isType = false; }
  8845. var name = null;
  8846. if (!isType && object.getClassName) {
  8847. name = object.getClassName();
  8848. }
  8849. else {
  8850. if (object instanceof Object) {
  8851. var classObj = isType ? object : Object.getPrototypeOf(object);
  8852. name = classObj.constructor["__bjsclassName__"];
  8853. }
  8854. if (!name) {
  8855. name = typeof object;
  8856. }
  8857. }
  8858. return name;
  8859. };
  8860. Tools.First = function (array, predicate) {
  8861. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  8862. var el = array_1[_i];
  8863. if (predicate(el)) {
  8864. return el;
  8865. }
  8866. }
  8867. return null;
  8868. };
  8869. /**
  8870. * This method will return the name of the full name of the class, including its owning module (if any).
  8871. * 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).
  8872. * @param object the object to get the class name from
  8873. * @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.
  8874. */
  8875. Tools.getFullClassName = function (object, isType) {
  8876. if (isType === void 0) { isType = false; }
  8877. var className = null;
  8878. var moduleName = null;
  8879. if (!isType && object.getClassName) {
  8880. className = object.getClassName();
  8881. }
  8882. else {
  8883. if (object instanceof Object) {
  8884. var classObj = isType ? object : Object.getPrototypeOf(object);
  8885. className = classObj.constructor["__bjsclassName__"];
  8886. moduleName = classObj.constructor["__bjsmoduleName__"];
  8887. }
  8888. if (!className) {
  8889. className = typeof object;
  8890. }
  8891. }
  8892. if (!className) {
  8893. return null;
  8894. }
  8895. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  8896. };
  8897. /**
  8898. * 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.
  8899. * @param array
  8900. */
  8901. Tools.arrayOrStringFeeder = function (array) {
  8902. return function (index) {
  8903. if (index >= array.length) {
  8904. return null;
  8905. }
  8906. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  8907. if (val && val.getHashCode) {
  8908. val = val.getHashCode();
  8909. }
  8910. if (typeof val === "string") {
  8911. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  8912. }
  8913. return val;
  8914. };
  8915. };
  8916. /**
  8917. * Compute the hashCode of a stream of number
  8918. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  8919. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  8920. * @return the hash code computed
  8921. */
  8922. Tools.hashCodeFromStream = function (feeder) {
  8923. // Based from here: http://stackoverflow.com/a/7616484/802124
  8924. var hash = 0;
  8925. var index = 0;
  8926. var chr = feeder(index++);
  8927. while (chr != null) {
  8928. hash = ((hash << 5) - hash) + chr;
  8929. hash |= 0; // Convert to 32bit integer
  8930. chr = feeder(index++);
  8931. }
  8932. return hash;
  8933. };
  8934. /**
  8935. * Returns a promise that resolves after the given amount of time.
  8936. * @param delay Number of milliseconds to delay
  8937. * @returns Promise that resolves after the given amount of time
  8938. */
  8939. Tools.DelayAsync = function (delay) {
  8940. return new Promise(function (resolve) {
  8941. setTimeout(function () {
  8942. resolve();
  8943. }, delay);
  8944. });
  8945. };
  8946. Tools.BaseUrl = "";
  8947. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  8948. /**
  8949. * Default behaviour for cors in the application.
  8950. * It can be a string if the expected behavior is identical in the entire app.
  8951. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  8952. */
  8953. Tools.CorsBehavior = "anonymous";
  8954. Tools.UseFallbackTexture = true;
  8955. /**
  8956. * Use this object to register external classes like custom textures or material
  8957. * to allow the laoders to instantiate them
  8958. */
  8959. Tools.RegisteredExternalClasses = {};
  8960. // Used in case of a texture loading problem
  8961. 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";
  8962. Tools.PreprocessUrl = function (url) {
  8963. return url;
  8964. };
  8965. // Logs
  8966. Tools._NoneLogLevel = 0;
  8967. Tools._MessageLogLevel = 1;
  8968. Tools._WarningLogLevel = 2;
  8969. Tools._ErrorLogLevel = 4;
  8970. Tools._LogCache = "";
  8971. Tools.errorsCount = 0;
  8972. Tools.Log = Tools._LogEnabled;
  8973. Tools.Warn = Tools._WarnEnabled;
  8974. Tools.Error = Tools._ErrorEnabled;
  8975. // Performances
  8976. Tools._PerformanceNoneLogLevel = 0;
  8977. Tools._PerformanceUserMarkLogLevel = 1;
  8978. Tools._PerformanceConsoleLogLevel = 2;
  8979. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  8980. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  8981. return Tools;
  8982. }());
  8983. BABYLON.Tools = Tools;
  8984. /**
  8985. * This class is used to track a performance counter which is number based.
  8986. * The user has access to many properties which give statistics of different nature
  8987. *
  8988. * The implementer can track two kinds of Performance Counter: time and count
  8989. * 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.
  8990. * 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.
  8991. */
  8992. var PerfCounter = /** @class */ (function () {
  8993. function PerfCounter() {
  8994. this._startMonitoringTime = 0;
  8995. this._min = 0;
  8996. this._max = 0;
  8997. this._average = 0;
  8998. this._lastSecAverage = 0;
  8999. this._current = 0;
  9000. this._totalValueCount = 0;
  9001. this._totalAccumulated = 0;
  9002. this._lastSecAccumulated = 0;
  9003. this._lastSecTime = 0;
  9004. this._lastSecValueCount = 0;
  9005. }
  9006. Object.defineProperty(PerfCounter.prototype, "min", {
  9007. /**
  9008. * Returns the smallest value ever
  9009. */
  9010. get: function () {
  9011. return this._min;
  9012. },
  9013. enumerable: true,
  9014. configurable: true
  9015. });
  9016. Object.defineProperty(PerfCounter.prototype, "max", {
  9017. /**
  9018. * Returns the biggest value ever
  9019. */
  9020. get: function () {
  9021. return this._max;
  9022. },
  9023. enumerable: true,
  9024. configurable: true
  9025. });
  9026. Object.defineProperty(PerfCounter.prototype, "average", {
  9027. /**
  9028. * Returns the average value since the performance counter is running
  9029. */
  9030. get: function () {
  9031. return this._average;
  9032. },
  9033. enumerable: true,
  9034. configurable: true
  9035. });
  9036. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  9037. /**
  9038. * Returns the average value of the last second the counter was monitored
  9039. */
  9040. get: function () {
  9041. return this._lastSecAverage;
  9042. },
  9043. enumerable: true,
  9044. configurable: true
  9045. });
  9046. Object.defineProperty(PerfCounter.prototype, "current", {
  9047. /**
  9048. * Returns the current value
  9049. */
  9050. get: function () {
  9051. return this._current;
  9052. },
  9053. enumerable: true,
  9054. configurable: true
  9055. });
  9056. Object.defineProperty(PerfCounter.prototype, "total", {
  9057. get: function () {
  9058. return this._totalAccumulated;
  9059. },
  9060. enumerable: true,
  9061. configurable: true
  9062. });
  9063. Object.defineProperty(PerfCounter.prototype, "count", {
  9064. get: function () {
  9065. return this._totalValueCount;
  9066. },
  9067. enumerable: true,
  9068. configurable: true
  9069. });
  9070. /**
  9071. * Call this method to start monitoring a new frame.
  9072. * 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.
  9073. */
  9074. PerfCounter.prototype.fetchNewFrame = function () {
  9075. this._totalValueCount++;
  9076. this._current = 0;
  9077. this._lastSecValueCount++;
  9078. };
  9079. /**
  9080. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  9081. * @param newCount the count value to add to the monitored count
  9082. * @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.
  9083. */
  9084. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  9085. if (!PerfCounter.Enabled) {
  9086. return;
  9087. }
  9088. this._current += newCount;
  9089. if (fetchResult) {
  9090. this._fetchResult();
  9091. }
  9092. };
  9093. /**
  9094. * Start monitoring this performance counter
  9095. */
  9096. PerfCounter.prototype.beginMonitoring = function () {
  9097. if (!PerfCounter.Enabled) {
  9098. return;
  9099. }
  9100. this._startMonitoringTime = Tools.Now;
  9101. };
  9102. /**
  9103. * Compute the time lapsed since the previous beginMonitoring() call.
  9104. * @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
  9105. */
  9106. PerfCounter.prototype.endMonitoring = function (newFrame) {
  9107. if (newFrame === void 0) { newFrame = true; }
  9108. if (!PerfCounter.Enabled) {
  9109. return;
  9110. }
  9111. if (newFrame) {
  9112. this.fetchNewFrame();
  9113. }
  9114. var currentTime = Tools.Now;
  9115. this._current = currentTime - this._startMonitoringTime;
  9116. if (newFrame) {
  9117. this._fetchResult();
  9118. }
  9119. };
  9120. PerfCounter.prototype._fetchResult = function () {
  9121. this._totalAccumulated += this._current;
  9122. this._lastSecAccumulated += this._current;
  9123. // Min/Max update
  9124. this._min = Math.min(this._min, this._current);
  9125. this._max = Math.max(this._max, this._current);
  9126. this._average = this._totalAccumulated / this._totalValueCount;
  9127. // Reset last sec?
  9128. var now = Tools.Now;
  9129. if ((now - this._lastSecTime) > 1000) {
  9130. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  9131. this._lastSecTime = now;
  9132. this._lastSecAccumulated = 0;
  9133. this._lastSecValueCount = 0;
  9134. }
  9135. };
  9136. PerfCounter.Enabled = true;
  9137. return PerfCounter;
  9138. }());
  9139. BABYLON.PerfCounter = PerfCounter;
  9140. /**
  9141. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  9142. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  9143. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  9144. * @param name The name of the class, case should be preserved
  9145. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  9146. */
  9147. function className(name, module) {
  9148. return function (target) {
  9149. target["__bjsclassName__"] = name;
  9150. target["__bjsmoduleName__"] = (module != null) ? module : null;
  9151. };
  9152. }
  9153. BABYLON.className = className;
  9154. /**
  9155. * An implementation of a loop for asynchronous functions.
  9156. */
  9157. var AsyncLoop = /** @class */ (function () {
  9158. /**
  9159. * Constroctor.
  9160. * @param iterations the number of iterations.
  9161. * @param _fn the function to run each iteration
  9162. * @param _successCallback the callback that will be called upon succesful execution
  9163. * @param offset starting offset.
  9164. */
  9165. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  9166. if (offset === void 0) { offset = 0; }
  9167. this.iterations = iterations;
  9168. this._fn = _fn;
  9169. this._successCallback = _successCallback;
  9170. this.index = offset - 1;
  9171. this._done = false;
  9172. }
  9173. /**
  9174. * Execute the next iteration. Must be called after the last iteration was finished.
  9175. */
  9176. AsyncLoop.prototype.executeNext = function () {
  9177. if (!this._done) {
  9178. if (this.index + 1 < this.iterations) {
  9179. ++this.index;
  9180. this._fn(this);
  9181. }
  9182. else {
  9183. this.breakLoop();
  9184. }
  9185. }
  9186. };
  9187. /**
  9188. * Break the loop and run the success callback.
  9189. */
  9190. AsyncLoop.prototype.breakLoop = function () {
  9191. this._done = true;
  9192. this._successCallback();
  9193. };
  9194. /**
  9195. * Helper function
  9196. */
  9197. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  9198. if (offset === void 0) { offset = 0; }
  9199. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  9200. loop.executeNext();
  9201. return loop;
  9202. };
  9203. /**
  9204. * A for-loop that will run a given number of iterations synchronous and the rest async.
  9205. * @param iterations total number of iterations
  9206. * @param syncedIterations number of synchronous iterations in each async iteration.
  9207. * @param fn the function to call each iteration.
  9208. * @param callback a success call back that will be called when iterating stops.
  9209. * @param breakFunction a break condition (optional)
  9210. * @param timeout timeout settings for the setTimeout function. default - 0.
  9211. * @constructor
  9212. */
  9213. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  9214. if (timeout === void 0) { timeout = 0; }
  9215. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  9216. if (breakFunction && breakFunction())
  9217. loop.breakLoop();
  9218. else {
  9219. setTimeout(function () {
  9220. for (var i = 0; i < syncedIterations; ++i) {
  9221. var iteration = (loop.index * syncedIterations) + i;
  9222. if (iteration >= iterations)
  9223. break;
  9224. fn(iteration);
  9225. if (breakFunction && breakFunction()) {
  9226. loop.breakLoop();
  9227. break;
  9228. }
  9229. }
  9230. loop.executeNext();
  9231. }, timeout);
  9232. }
  9233. }, callback);
  9234. };
  9235. return AsyncLoop;
  9236. }());
  9237. BABYLON.AsyncLoop = AsyncLoop;
  9238. })(BABYLON || (BABYLON = {}));
  9239. //# sourceMappingURL=babylon.tools.js.map
  9240. var BABYLON;
  9241. (function (BABYLON) {
  9242. var PromiseStates;
  9243. (function (PromiseStates) {
  9244. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  9245. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  9246. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  9247. })(PromiseStates || (PromiseStates = {}));
  9248. var FulFillmentAgregator = /** @class */ (function () {
  9249. function FulFillmentAgregator() {
  9250. this.count = 0;
  9251. this.target = 0;
  9252. this.results = [];
  9253. }
  9254. return FulFillmentAgregator;
  9255. }());
  9256. var InternalPromise = /** @class */ (function () {
  9257. function InternalPromise(resolver) {
  9258. var _this = this;
  9259. this._state = PromiseStates.Pending;
  9260. this._children = new Array();
  9261. this._rejectWasConsumed = false;
  9262. if (!resolver) {
  9263. return;
  9264. }
  9265. try {
  9266. resolver(function (value) {
  9267. _this._resolve(value);
  9268. }, function (reason) {
  9269. _this._reject(reason);
  9270. });
  9271. }
  9272. catch (e) {
  9273. this._reject(e);
  9274. }
  9275. }
  9276. Object.defineProperty(InternalPromise.prototype, "state", {
  9277. get: function () {
  9278. return this._state;
  9279. },
  9280. enumerable: true,
  9281. configurable: true
  9282. });
  9283. Object.defineProperty(InternalPromise.prototype, "isFulfilled", {
  9284. get: function () {
  9285. return this._state === PromiseStates.Fulfilled;
  9286. },
  9287. enumerable: true,
  9288. configurable: true
  9289. });
  9290. Object.defineProperty(InternalPromise.prototype, "isRejected", {
  9291. get: function () {
  9292. return this._state === PromiseStates.Rejected;
  9293. },
  9294. enumerable: true,
  9295. configurable: true
  9296. });
  9297. Object.defineProperty(InternalPromise.prototype, "isPending", {
  9298. get: function () {
  9299. return this._state === PromiseStates.Pending;
  9300. },
  9301. enumerable: true,
  9302. configurable: true
  9303. });
  9304. InternalPromise.prototype.value = function () {
  9305. if (!this.isFulfilled) {
  9306. throw new Error("Promise is not fulfilled");
  9307. }
  9308. return this._result;
  9309. };
  9310. InternalPromise.prototype.reason = function () {
  9311. if (!this.isRejected) {
  9312. throw new Error("Promise is not rejected");
  9313. }
  9314. return this._reason;
  9315. };
  9316. InternalPromise.prototype.catch = function (onRejected) {
  9317. return this.then(undefined, onRejected);
  9318. };
  9319. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  9320. var newPromise = new InternalPromise();
  9321. newPromise._onFulfilled = onFulfilled;
  9322. newPromise._onRejected = onRejected;
  9323. // Composition
  9324. this._children.push(newPromise);
  9325. if (this._state !== PromiseStates.Pending) {
  9326. if (this._state === PromiseStates.Fulfilled || this._rejectWasConsumed) {
  9327. var returnedValue = newPromise._resolve(this._result);
  9328. if (returnedValue !== undefined && returnedValue !== null) {
  9329. if (returnedValue._state !== undefined) {
  9330. var returnedPromise = returnedValue;
  9331. newPromise._children.push(returnedPromise);
  9332. newPromise = returnedPromise;
  9333. }
  9334. else {
  9335. newPromise._result = returnedValue;
  9336. }
  9337. }
  9338. }
  9339. else {
  9340. newPromise._reject(this._reason);
  9341. }
  9342. }
  9343. return newPromise;
  9344. };
  9345. InternalPromise.prototype._moveChildren = function (children) {
  9346. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  9347. if (this.isFulfilled) {
  9348. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  9349. var child = _b[_i];
  9350. child._resolve(this._result);
  9351. }
  9352. }
  9353. else if (this.isRejected) {
  9354. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  9355. var child = _d[_c];
  9356. child._reject(this._reason);
  9357. }
  9358. }
  9359. var _a;
  9360. };
  9361. InternalPromise.prototype._resolve = function (value) {
  9362. try {
  9363. this._state = PromiseStates.Fulfilled;
  9364. this._result = value;
  9365. var returnedValue = null;
  9366. if (this._onFulfilled) {
  9367. returnedValue = this._onFulfilled(value);
  9368. }
  9369. if (returnedValue !== undefined && returnedValue !== null) {
  9370. if (returnedValue._state !== undefined) {
  9371. // Transmit children
  9372. var returnedPromise = returnedValue;
  9373. returnedPromise._moveChildren(this._children);
  9374. }
  9375. else {
  9376. value = returnedValue;
  9377. }
  9378. }
  9379. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  9380. var child = _a[_i];
  9381. child._resolve(value);
  9382. }
  9383. return returnedValue;
  9384. }
  9385. catch (e) {
  9386. this._reject(e);
  9387. }
  9388. return null;
  9389. };
  9390. InternalPromise.prototype._reject = function (reason) {
  9391. this._state = PromiseStates.Rejected;
  9392. this._reason = reason;
  9393. if (this._onRejected) {
  9394. this._onRejected(reason);
  9395. this._rejectWasConsumed = true;
  9396. }
  9397. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  9398. var child = _a[_i];
  9399. if (this._rejectWasConsumed) {
  9400. child._resolve(null);
  9401. }
  9402. else {
  9403. child._reject(reason);
  9404. }
  9405. }
  9406. };
  9407. InternalPromise.resolve = function (value) {
  9408. var newPromise = new InternalPromise();
  9409. newPromise._resolve(value);
  9410. return newPromise;
  9411. };
  9412. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  9413. promise.then(function (value) {
  9414. agregator.results[index] = value;
  9415. agregator.count++;
  9416. if (agregator.count === agregator.target) {
  9417. agregator.rootPromise._resolve(agregator.results);
  9418. }
  9419. return null;
  9420. }, function (reason) {
  9421. if (!agregator.rootPromise.isRejected) {
  9422. agregator.rootPromise._reject(reason);
  9423. }
  9424. });
  9425. };
  9426. InternalPromise.all = function (promises) {
  9427. var newPromise = new InternalPromise();
  9428. var agregator = new FulFillmentAgregator();
  9429. agregator.target = promises.length;
  9430. agregator.rootPromise = newPromise;
  9431. if (promises.length) {
  9432. for (var index = 0; index < promises.length; index++) {
  9433. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  9434. }
  9435. }
  9436. else {
  9437. newPromise._resolve([]);
  9438. }
  9439. return newPromise;
  9440. };
  9441. return InternalPromise;
  9442. }());
  9443. /**
  9444. * Helper class that provides a small promise polyfill
  9445. */
  9446. var PromisePolyfill = /** @class */ (function () {
  9447. function PromisePolyfill() {
  9448. }
  9449. /**
  9450. * Static function used to check if the polyfill is required
  9451. * If this is the case then the function will inject the polyfill to window.Promise
  9452. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  9453. */
  9454. PromisePolyfill.Apply = function (force) {
  9455. if (force === void 0) { force = false; }
  9456. if (force || typeof Promise === 'undefined') {
  9457. var root = window;
  9458. root.Promise = InternalPromise;
  9459. }
  9460. };
  9461. return PromisePolyfill;
  9462. }());
  9463. BABYLON.PromisePolyfill = PromisePolyfill;
  9464. })(BABYLON || (BABYLON = {}));
  9465. //# sourceMappingURL=babylon.promise.js.map
  9466. var BABYLON;
  9467. (function (BABYLON) {
  9468. var _AlphaState = /** @class */ (function () {
  9469. /**
  9470. * Initializes the state.
  9471. */
  9472. function _AlphaState() {
  9473. this._isAlphaBlendDirty = false;
  9474. this._isBlendFunctionParametersDirty = false;
  9475. this._isBlendEquationParametersDirty = false;
  9476. this._isBlendConstantsDirty = false;
  9477. this._alphaBlend = false;
  9478. this._blendFunctionParameters = new Array(4);
  9479. this._blendEquationParameters = new Array(2);
  9480. this._blendConstants = new Array(4);
  9481. this.reset();
  9482. }
  9483. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  9484. get: function () {
  9485. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  9486. },
  9487. enumerable: true,
  9488. configurable: true
  9489. });
  9490. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  9491. get: function () {
  9492. return this._alphaBlend;
  9493. },
  9494. set: function (value) {
  9495. if (this._alphaBlend === value) {
  9496. return;
  9497. }
  9498. this._alphaBlend = value;
  9499. this._isAlphaBlendDirty = true;
  9500. },
  9501. enumerable: true,
  9502. configurable: true
  9503. });
  9504. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  9505. if (this._blendConstants[0] === r &&
  9506. this._blendConstants[1] === g &&
  9507. this._blendConstants[2] === b &&
  9508. this._blendConstants[3] === a) {
  9509. return;
  9510. }
  9511. this._blendConstants[0] = r;
  9512. this._blendConstants[1] = g;
  9513. this._blendConstants[2] = b;
  9514. this._blendConstants[3] = a;
  9515. this._isBlendConstantsDirty = true;
  9516. };
  9517. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  9518. if (this._blendFunctionParameters[0] === value0 &&
  9519. this._blendFunctionParameters[1] === value1 &&
  9520. this._blendFunctionParameters[2] === value2 &&
  9521. this._blendFunctionParameters[3] === value3) {
  9522. return;
  9523. }
  9524. this._blendFunctionParameters[0] = value0;
  9525. this._blendFunctionParameters[1] = value1;
  9526. this._blendFunctionParameters[2] = value2;
  9527. this._blendFunctionParameters[3] = value3;
  9528. this._isBlendFunctionParametersDirty = true;
  9529. };
  9530. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  9531. if (this._blendEquationParameters[0] === rgb &&
  9532. this._blendEquationParameters[1] === alpha) {
  9533. return;
  9534. }
  9535. this._blendEquationParameters[0] = rgb;
  9536. this._blendEquationParameters[1] = alpha;
  9537. this._isBlendEquationParametersDirty = true;
  9538. };
  9539. _AlphaState.prototype.reset = function () {
  9540. this._alphaBlend = false;
  9541. this._blendFunctionParameters[0] = null;
  9542. this._blendFunctionParameters[1] = null;
  9543. this._blendFunctionParameters[2] = null;
  9544. this._blendFunctionParameters[3] = null;
  9545. this._blendEquationParameters[0] = null;
  9546. this._blendEquationParameters[1] = null;
  9547. this._blendConstants[0] = null;
  9548. this._blendConstants[1] = null;
  9549. this._blendConstants[2] = null;
  9550. this._blendConstants[3] = null;
  9551. this._isAlphaBlendDirty = true;
  9552. this._isBlendFunctionParametersDirty = false;
  9553. this._isBlendEquationParametersDirty = false;
  9554. this._isBlendConstantsDirty = false;
  9555. };
  9556. _AlphaState.prototype.apply = function (gl) {
  9557. if (!this.isDirty) {
  9558. return;
  9559. }
  9560. // Alpha blend
  9561. if (this._isAlphaBlendDirty) {
  9562. if (this._alphaBlend) {
  9563. gl.enable(gl.BLEND);
  9564. }
  9565. else {
  9566. gl.disable(gl.BLEND);
  9567. }
  9568. this._isAlphaBlendDirty = false;
  9569. }
  9570. // Alpha function
  9571. if (this._isBlendFunctionParametersDirty) {
  9572. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  9573. this._isBlendFunctionParametersDirty = false;
  9574. }
  9575. // Alpha equation
  9576. if (this._isBlendEquationParametersDirty) {
  9577. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  9578. this._isBlendEquationParametersDirty = false;
  9579. }
  9580. // Constants
  9581. if (this._isBlendConstantsDirty) {
  9582. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  9583. this._isBlendConstantsDirty = false;
  9584. }
  9585. };
  9586. return _AlphaState;
  9587. }());
  9588. BABYLON._AlphaState = _AlphaState;
  9589. })(BABYLON || (BABYLON = {}));
  9590. //# sourceMappingURL=babylon.alphaCullingState.js.map
  9591. var BABYLON;
  9592. (function (BABYLON) {
  9593. var _DepthCullingState = /** @class */ (function () {
  9594. /**
  9595. * Initializes the state.
  9596. */
  9597. function _DepthCullingState() {
  9598. this._isDepthTestDirty = false;
  9599. this._isDepthMaskDirty = false;
  9600. this._isDepthFuncDirty = false;
  9601. this._isCullFaceDirty = false;
  9602. this._isCullDirty = false;
  9603. this._isZOffsetDirty = false;
  9604. this._isFrontFaceDirty = false;
  9605. this.reset();
  9606. }
  9607. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  9608. get: function () {
  9609. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  9610. },
  9611. enumerable: true,
  9612. configurable: true
  9613. });
  9614. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  9615. get: function () {
  9616. return this._zOffset;
  9617. },
  9618. set: function (value) {
  9619. if (this._zOffset === value) {
  9620. return;
  9621. }
  9622. this._zOffset = value;
  9623. this._isZOffsetDirty = true;
  9624. },
  9625. enumerable: true,
  9626. configurable: true
  9627. });
  9628. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  9629. get: function () {
  9630. return this._cullFace;
  9631. },
  9632. set: function (value) {
  9633. if (this._cullFace === value) {
  9634. return;
  9635. }
  9636. this._cullFace = value;
  9637. this._isCullFaceDirty = true;
  9638. },
  9639. enumerable: true,
  9640. configurable: true
  9641. });
  9642. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  9643. get: function () {
  9644. return this._cull;
  9645. },
  9646. set: function (value) {
  9647. if (this._cull === value) {
  9648. return;
  9649. }
  9650. this._cull = value;
  9651. this._isCullDirty = true;
  9652. },
  9653. enumerable: true,
  9654. configurable: true
  9655. });
  9656. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  9657. get: function () {
  9658. return this._depthFunc;
  9659. },
  9660. set: function (value) {
  9661. if (this._depthFunc === value) {
  9662. return;
  9663. }
  9664. this._depthFunc = value;
  9665. this._isDepthFuncDirty = true;
  9666. },
  9667. enumerable: true,
  9668. configurable: true
  9669. });
  9670. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  9671. get: function () {
  9672. return this._depthMask;
  9673. },
  9674. set: function (value) {
  9675. if (this._depthMask === value) {
  9676. return;
  9677. }
  9678. this._depthMask = value;
  9679. this._isDepthMaskDirty = true;
  9680. },
  9681. enumerable: true,
  9682. configurable: true
  9683. });
  9684. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  9685. get: function () {
  9686. return this._depthTest;
  9687. },
  9688. set: function (value) {
  9689. if (this._depthTest === value) {
  9690. return;
  9691. }
  9692. this._depthTest = value;
  9693. this._isDepthTestDirty = true;
  9694. },
  9695. enumerable: true,
  9696. configurable: true
  9697. });
  9698. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  9699. get: function () {
  9700. return this._frontFace;
  9701. },
  9702. set: function (value) {
  9703. if (this._frontFace === value) {
  9704. return;
  9705. }
  9706. this._frontFace = value;
  9707. this._isFrontFaceDirty = true;
  9708. },
  9709. enumerable: true,
  9710. configurable: true
  9711. });
  9712. _DepthCullingState.prototype.reset = function () {
  9713. this._depthMask = true;
  9714. this._depthTest = true;
  9715. this._depthFunc = null;
  9716. this._cullFace = null;
  9717. this._cull = null;
  9718. this._zOffset = 0;
  9719. this._frontFace = null;
  9720. this._isDepthTestDirty = true;
  9721. this._isDepthMaskDirty = true;
  9722. this._isDepthFuncDirty = false;
  9723. this._isCullFaceDirty = false;
  9724. this._isCullDirty = false;
  9725. this._isZOffsetDirty = false;
  9726. this._isFrontFaceDirty = false;
  9727. };
  9728. _DepthCullingState.prototype.apply = function (gl) {
  9729. if (!this.isDirty) {
  9730. return;
  9731. }
  9732. // Cull
  9733. if (this._isCullDirty) {
  9734. if (this.cull) {
  9735. gl.enable(gl.CULL_FACE);
  9736. }
  9737. else {
  9738. gl.disable(gl.CULL_FACE);
  9739. }
  9740. this._isCullDirty = false;
  9741. }
  9742. // Cull face
  9743. if (this._isCullFaceDirty) {
  9744. gl.cullFace(this.cullFace);
  9745. this._isCullFaceDirty = false;
  9746. }
  9747. // Depth mask
  9748. if (this._isDepthMaskDirty) {
  9749. gl.depthMask(this.depthMask);
  9750. this._isDepthMaskDirty = false;
  9751. }
  9752. // Depth test
  9753. if (this._isDepthTestDirty) {
  9754. if (this.depthTest) {
  9755. gl.enable(gl.DEPTH_TEST);
  9756. }
  9757. else {
  9758. gl.disable(gl.DEPTH_TEST);
  9759. }
  9760. this._isDepthTestDirty = false;
  9761. }
  9762. // Depth func
  9763. if (this._isDepthFuncDirty) {
  9764. gl.depthFunc(this.depthFunc);
  9765. this._isDepthFuncDirty = false;
  9766. }
  9767. // zOffset
  9768. if (this._isZOffsetDirty) {
  9769. if (this.zOffset) {
  9770. gl.enable(gl.POLYGON_OFFSET_FILL);
  9771. gl.polygonOffset(this.zOffset, 0);
  9772. }
  9773. else {
  9774. gl.disable(gl.POLYGON_OFFSET_FILL);
  9775. }
  9776. this._isZOffsetDirty = false;
  9777. }
  9778. // Front face
  9779. if (this._isFrontFaceDirty) {
  9780. gl.frontFace(this.frontFace);
  9781. this._isFrontFaceDirty = false;
  9782. }
  9783. };
  9784. return _DepthCullingState;
  9785. }());
  9786. BABYLON._DepthCullingState = _DepthCullingState;
  9787. })(BABYLON || (BABYLON = {}));
  9788. //# sourceMappingURL=babylon.depthCullingState.js.map
  9789. var BABYLON;
  9790. (function (BABYLON) {
  9791. var _StencilState = /** @class */ (function () {
  9792. function _StencilState() {
  9793. this._isStencilTestDirty = false;
  9794. this._isStencilMaskDirty = false;
  9795. this._isStencilFuncDirty = false;
  9796. this._isStencilOpDirty = false;
  9797. this.reset();
  9798. }
  9799. Object.defineProperty(_StencilState.prototype, "isDirty", {
  9800. get: function () {
  9801. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  9802. },
  9803. enumerable: true,
  9804. configurable: true
  9805. });
  9806. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  9807. get: function () {
  9808. return this._stencilFunc;
  9809. },
  9810. set: function (value) {
  9811. if (this._stencilFunc === value) {
  9812. return;
  9813. }
  9814. this._stencilFunc = value;
  9815. this._isStencilFuncDirty = true;
  9816. },
  9817. enumerable: true,
  9818. configurable: true
  9819. });
  9820. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  9821. get: function () {
  9822. return this._stencilFuncRef;
  9823. },
  9824. set: function (value) {
  9825. if (this._stencilFuncRef === value) {
  9826. return;
  9827. }
  9828. this._stencilFuncRef = value;
  9829. this._isStencilFuncDirty = true;
  9830. },
  9831. enumerable: true,
  9832. configurable: true
  9833. });
  9834. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  9835. get: function () {
  9836. return this._stencilFuncMask;
  9837. },
  9838. set: function (value) {
  9839. if (this._stencilFuncMask === value) {
  9840. return;
  9841. }
  9842. this._stencilFuncMask = value;
  9843. this._isStencilFuncDirty = true;
  9844. },
  9845. enumerable: true,
  9846. configurable: true
  9847. });
  9848. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  9849. get: function () {
  9850. return this._stencilOpStencilFail;
  9851. },
  9852. set: function (value) {
  9853. if (this._stencilOpStencilFail === value) {
  9854. return;
  9855. }
  9856. this._stencilOpStencilFail = value;
  9857. this._isStencilOpDirty = true;
  9858. },
  9859. enumerable: true,
  9860. configurable: true
  9861. });
  9862. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  9863. get: function () {
  9864. return this._stencilOpDepthFail;
  9865. },
  9866. set: function (value) {
  9867. if (this._stencilOpDepthFail === value) {
  9868. return;
  9869. }
  9870. this._stencilOpDepthFail = value;
  9871. this._isStencilOpDirty = true;
  9872. },
  9873. enumerable: true,
  9874. configurable: true
  9875. });
  9876. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  9877. get: function () {
  9878. return this._stencilOpStencilDepthPass;
  9879. },
  9880. set: function (value) {
  9881. if (this._stencilOpStencilDepthPass === value) {
  9882. return;
  9883. }
  9884. this._stencilOpStencilDepthPass = value;
  9885. this._isStencilOpDirty = true;
  9886. },
  9887. enumerable: true,
  9888. configurable: true
  9889. });
  9890. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  9891. get: function () {
  9892. return this._stencilMask;
  9893. },
  9894. set: function (value) {
  9895. if (this._stencilMask === value) {
  9896. return;
  9897. }
  9898. this._stencilMask = value;
  9899. this._isStencilMaskDirty = true;
  9900. },
  9901. enumerable: true,
  9902. configurable: true
  9903. });
  9904. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  9905. get: function () {
  9906. return this._stencilTest;
  9907. },
  9908. set: function (value) {
  9909. if (this._stencilTest === value) {
  9910. return;
  9911. }
  9912. this._stencilTest = value;
  9913. this._isStencilTestDirty = true;
  9914. },
  9915. enumerable: true,
  9916. configurable: true
  9917. });
  9918. _StencilState.prototype.reset = function () {
  9919. this._stencilTest = false;
  9920. this._stencilMask = 0xFF;
  9921. this._stencilFunc = BABYLON.Engine.ALWAYS;
  9922. this._stencilFuncRef = 1;
  9923. this._stencilFuncMask = 0xFF;
  9924. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  9925. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  9926. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  9927. this._isStencilTestDirty = true;
  9928. this._isStencilMaskDirty = true;
  9929. this._isStencilFuncDirty = true;
  9930. this._isStencilOpDirty = true;
  9931. };
  9932. _StencilState.prototype.apply = function (gl) {
  9933. if (!this.isDirty) {
  9934. return;
  9935. }
  9936. // Stencil test
  9937. if (this._isStencilTestDirty) {
  9938. if (this.stencilTest) {
  9939. gl.enable(gl.STENCIL_TEST);
  9940. }
  9941. else {
  9942. gl.disable(gl.STENCIL_TEST);
  9943. }
  9944. this._isStencilTestDirty = false;
  9945. }
  9946. // Stencil mask
  9947. if (this._isStencilMaskDirty) {
  9948. gl.stencilMask(this.stencilMask);
  9949. this._isStencilMaskDirty = false;
  9950. }
  9951. // Stencil func
  9952. if (this._isStencilFuncDirty) {
  9953. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  9954. this._isStencilFuncDirty = false;
  9955. }
  9956. // Stencil op
  9957. if (this._isStencilOpDirty) {
  9958. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  9959. this._isStencilOpDirty = false;
  9960. }
  9961. };
  9962. return _StencilState;
  9963. }());
  9964. BABYLON._StencilState = _StencilState;
  9965. })(BABYLON || (BABYLON = {}));
  9966. //# sourceMappingURL=babylon.stencilState.js.map
  9967. var BABYLON;
  9968. (function (BABYLON) {
  9969. var compileShader = function (gl, source, type, defines, shaderVersion) {
  9970. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  9971. };
  9972. var compileRawShader = function (gl, source, type) {
  9973. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  9974. gl.shaderSource(shader, source);
  9975. gl.compileShader(shader);
  9976. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  9977. var log = gl.getShaderInfoLog(shader);
  9978. if (log) {
  9979. throw new Error(log);
  9980. }
  9981. }
  9982. if (!shader) {
  9983. throw new Error("Something went wrong while compile the shader.");
  9984. }
  9985. return shader;
  9986. };
  9987. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  9988. var magFilter = gl.NEAREST;
  9989. var minFilter = gl.NEAREST;
  9990. switch (samplingMode) {
  9991. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  9992. magFilter = gl.LINEAR;
  9993. if (generateMipMaps) {
  9994. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  9995. }
  9996. else {
  9997. minFilter = gl.LINEAR;
  9998. }
  9999. break;
  10000. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  10001. magFilter = gl.LINEAR;
  10002. if (generateMipMaps) {
  10003. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  10004. }
  10005. else {
  10006. minFilter = gl.LINEAR;
  10007. }
  10008. break;
  10009. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  10010. magFilter = gl.NEAREST;
  10011. if (generateMipMaps) {
  10012. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  10013. }
  10014. else {
  10015. minFilter = gl.NEAREST;
  10016. }
  10017. break;
  10018. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  10019. magFilter = gl.NEAREST;
  10020. if (generateMipMaps) {
  10021. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  10022. }
  10023. else {
  10024. minFilter = gl.NEAREST;
  10025. }
  10026. break;
  10027. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  10028. magFilter = gl.NEAREST;
  10029. if (generateMipMaps) {
  10030. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  10031. }
  10032. else {
  10033. minFilter = gl.LINEAR;
  10034. }
  10035. break;
  10036. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  10037. magFilter = gl.NEAREST;
  10038. if (generateMipMaps) {
  10039. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  10040. }
  10041. else {
  10042. minFilter = gl.LINEAR;
  10043. }
  10044. break;
  10045. case BABYLON.Texture.NEAREST_LINEAR:
  10046. magFilter = gl.NEAREST;
  10047. minFilter = gl.LINEAR;
  10048. break;
  10049. case BABYLON.Texture.NEAREST_NEAREST:
  10050. magFilter = gl.NEAREST;
  10051. minFilter = gl.NEAREST;
  10052. break;
  10053. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  10054. magFilter = gl.LINEAR;
  10055. if (generateMipMaps) {
  10056. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  10057. }
  10058. else {
  10059. minFilter = gl.NEAREST;
  10060. }
  10061. break;
  10062. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  10063. magFilter = gl.LINEAR;
  10064. if (generateMipMaps) {
  10065. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  10066. }
  10067. else {
  10068. minFilter = gl.NEAREST;
  10069. }
  10070. break;
  10071. case BABYLON.Texture.LINEAR_LINEAR:
  10072. magFilter = gl.LINEAR;
  10073. minFilter = gl.LINEAR;
  10074. break;
  10075. case BABYLON.Texture.LINEAR_NEAREST:
  10076. magFilter = gl.LINEAR;
  10077. minFilter = gl.NEAREST;
  10078. break;
  10079. }
  10080. return {
  10081. min: minFilter,
  10082. mag: magFilter
  10083. };
  10084. };
  10085. var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  10086. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  10087. var img;
  10088. var onload = function () {
  10089. loadedImages[index] = img;
  10090. loadedImages._internalCount++;
  10091. if (scene) {
  10092. scene._removePendingData(img);
  10093. }
  10094. if (loadedImages._internalCount === 6) {
  10095. onfinish(loadedImages);
  10096. }
  10097. };
  10098. var onerror = function (message, exception) {
  10099. if (scene) {
  10100. scene._removePendingData(img);
  10101. }
  10102. if (onErrorCallBack) {
  10103. onErrorCallBack(message, exception);
  10104. }
  10105. };
  10106. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  10107. if (scene) {
  10108. scene._addPendingData(img);
  10109. }
  10110. };
  10111. var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  10112. if (onError === void 0) { onError = null; }
  10113. var loadedImages = [];
  10114. loadedImages._internalCount = 0;
  10115. for (var index = 0; index < 6; index++) {
  10116. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  10117. }
  10118. };
  10119. var BufferPointer = /** @class */ (function () {
  10120. function BufferPointer() {
  10121. }
  10122. return BufferPointer;
  10123. }());
  10124. var InstancingAttributeInfo = /** @class */ (function () {
  10125. function InstancingAttributeInfo() {
  10126. }
  10127. return InstancingAttributeInfo;
  10128. }());
  10129. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  10130. /**
  10131. * Define options used to create a render target texture
  10132. */
  10133. var RenderTargetCreationOptions = /** @class */ (function () {
  10134. function RenderTargetCreationOptions() {
  10135. }
  10136. return RenderTargetCreationOptions;
  10137. }());
  10138. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  10139. /**
  10140. * Regroup several parameters relative to the browser in use
  10141. */
  10142. var EngineCapabilities = /** @class */ (function () {
  10143. function EngineCapabilities() {
  10144. }
  10145. return EngineCapabilities;
  10146. }());
  10147. BABYLON.EngineCapabilities = EngineCapabilities;
  10148. /**
  10149. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  10150. */
  10151. var Engine = /** @class */ (function () {
  10152. /**
  10153. * @constructor
  10154. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  10155. * @param antialias defines enable antialiasing (default: false)
  10156. * @param options defines further options to be sent to the getContext() function
  10157. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  10158. */
  10159. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  10160. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  10161. var _this = this;
  10162. // Public members
  10163. this.forcePOTTextures = false;
  10164. this.isFullscreen = false;
  10165. this.isPointerLock = false;
  10166. this.cullBackFaces = true;
  10167. this.renderEvenInBackground = true;
  10168. this.preventCacheWipeBetweenFrames = false;
  10169. // To enable/disable IDB support and avoid XHR on .manifest
  10170. this.enableOfflineSupport = false;
  10171. this.scenes = new Array();
  10172. this.postProcesses = new Array();
  10173. // Observables
  10174. /**
  10175. * Observable event triggered each time the rendering canvas is resized
  10176. */
  10177. this.onResizeObservable = new BABYLON.Observable();
  10178. /**
  10179. * Observable event triggered each time the canvas loses focus
  10180. */
  10181. this.onCanvasBlurObservable = new BABYLON.Observable();
  10182. /**
  10183. * Observable event triggered each time the canvas gains focus
  10184. */
  10185. this.onCanvasFocusObservable = new BABYLON.Observable();
  10186. /**
  10187. * Observable event triggered each time the canvas receives pointerout event
  10188. */
  10189. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  10190. /**
  10191. * Observable event triggered before each texture is initialized
  10192. */
  10193. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  10194. //WebVR
  10195. this._vrDisplay = undefined;
  10196. this._vrSupported = false;
  10197. this._vrExclusivePointerMode = false;
  10198. // Uniform buffers list
  10199. this.disableUniformBuffers = false;
  10200. this._uniformBuffers = new Array();
  10201. // Observables
  10202. /**
  10203. * Observable raised when the engine begins a new frame
  10204. */
  10205. this.onBeginFrameObservable = new BABYLON.Observable();
  10206. /**
  10207. * Observable raised when the engine ends the current frame
  10208. */
  10209. this.onEndFrameObservable = new BABYLON.Observable();
  10210. /**
  10211. * Observable raised when the engine is about to compile a shader
  10212. */
  10213. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  10214. /**
  10215. * Observable raised when the engine has jsut compiled a shader
  10216. */
  10217. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  10218. this._windowIsBackground = false;
  10219. this._webGLVersion = 1.0;
  10220. this._badOS = false;
  10221. this._badDesktopOS = false;
  10222. /**
  10223. * Gets or sets a value indicating if we want to disable texture binding optmization.
  10224. * This could be required on some buggy drivers which wants to have textures bound in a progressive order
  10225. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is.
  10226. */
  10227. this.disableTextureBindingOptimization = false;
  10228. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  10229. this.onVRRequestPresentComplete = new BABYLON.Observable();
  10230. this.onVRRequestPresentStart = new BABYLON.Observable();
  10231. this._colorWrite = true;
  10232. this._drawCalls = new BABYLON.PerfCounter();
  10233. this._textureCollisions = new BABYLON.PerfCounter();
  10234. this._renderingQueueLaunched = false;
  10235. this._activeRenderLoops = new Array();
  10236. // Deterministic lockstepMaxSteps
  10237. this._deterministicLockstep = false;
  10238. this._lockstepMaxSteps = 4;
  10239. // Lost context
  10240. this.onContextLostObservable = new BABYLON.Observable();
  10241. this.onContextRestoredObservable = new BABYLON.Observable();
  10242. this._contextWasLost = false;
  10243. this._doNotHandleContextLost = false;
  10244. // FPS
  10245. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  10246. this._fps = 60;
  10247. this._deltaTime = 0;
  10248. /**
  10249. * Turn this value on if you want to pause FPS computation when in background
  10250. */
  10251. this.disablePerformanceMonitorInBackground = false;
  10252. // States
  10253. this._depthCullingState = new BABYLON._DepthCullingState();
  10254. this._stencilState = new BABYLON._StencilState();
  10255. this._alphaState = new BABYLON._AlphaState();
  10256. this._alphaMode = Engine.ALPHA_DISABLE;
  10257. // Cache
  10258. this._internalTexturesCache = new Array();
  10259. this._activeChannel = 0;
  10260. this._currentTextureChannel = -1;
  10261. this._boundTexturesCache = {};
  10262. this._compiledEffects = {};
  10263. this._vertexAttribArraysEnabled = [];
  10264. this._uintIndicesCurrentlySet = false;
  10265. this._currentBoundBuffer = new Array();
  10266. this._currentBufferPointers = new Array();
  10267. this._currentInstanceLocations = new Array();
  10268. this._currentInstanceBuffers = new Array();
  10269. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  10270. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  10271. this._vaoRecordInProgress = false;
  10272. this._mustWipeVertexAttributes = false;
  10273. this._nextFreeTextureSlots = new Array();
  10274. this._maxSimultaneousTextures = 0;
  10275. this._activeRequests = new Array();
  10276. // Hardware supported Compressed Textures
  10277. this._texturesSupported = new Array();
  10278. this._onVRFullScreenTriggered = function () {
  10279. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  10280. //get the old size before we change
  10281. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  10282. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  10283. //get the width and height, change the render size
  10284. var leftEye = _this._vrDisplay.getEyeParameters('left');
  10285. _this.setHardwareScalingLevel(1);
  10286. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  10287. }
  10288. else {
  10289. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  10290. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  10291. }
  10292. };
  10293. this._boundUniforms = {};
  10294. // Register promises
  10295. BABYLON.PromisePolyfill.Apply();
  10296. var canvas = null;
  10297. Engine.Instances.push(this);
  10298. if (!canvasOrContext) {
  10299. return;
  10300. }
  10301. options = options || {};
  10302. if (canvasOrContext.getContext) {
  10303. canvas = canvasOrContext;
  10304. this._renderingCanvas = canvas;
  10305. if (antialias != null) {
  10306. options.antialias = antialias;
  10307. }
  10308. if (options.deterministicLockstep === undefined) {
  10309. options.deterministicLockstep = false;
  10310. }
  10311. if (options.lockstepMaxSteps === undefined) {
  10312. options.lockstepMaxSteps = 4;
  10313. }
  10314. if (options.preserveDrawingBuffer === undefined) {
  10315. options.preserveDrawingBuffer = false;
  10316. }
  10317. if (options.audioEngine === undefined) {
  10318. options.audioEngine = true;
  10319. }
  10320. if (options.stencil === undefined) {
  10321. options.stencil = true;
  10322. }
  10323. this._deterministicLockstep = options.deterministicLockstep;
  10324. this._lockstepMaxSteps = options.lockstepMaxSteps;
  10325. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  10326. // Exceptions
  10327. if (navigator && navigator.userAgent) {
  10328. var ua = navigator.userAgent;
  10329. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  10330. var exception = _a[_i];
  10331. var key = exception.key;
  10332. var targets = exception.targets;
  10333. if (ua.indexOf(key) > -1) {
  10334. if (exception.capture && exception.captureConstraint) {
  10335. var capture = exception.capture;
  10336. var constraint = exception.captureConstraint;
  10337. var regex = new RegExp(capture);
  10338. var matches = regex.exec(ua);
  10339. if (matches && matches.length > 0) {
  10340. var capturedValue = parseInt(matches[matches.length - 1]);
  10341. if (capturedValue >= constraint) {
  10342. continue;
  10343. }
  10344. }
  10345. }
  10346. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  10347. var target = targets_1[_b];
  10348. switch (target) {
  10349. case "uniformBuffer":
  10350. this.disableUniformBuffers = true;
  10351. break;
  10352. case "textureBindingOptimization":
  10353. this.disableTextureBindingOptimization = true;
  10354. break;
  10355. }
  10356. }
  10357. break;
  10358. }
  10359. }
  10360. }
  10361. // GL
  10362. if (!options.disableWebGL2Support) {
  10363. try {
  10364. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  10365. if (this._gl) {
  10366. this._webGLVersion = 2.0;
  10367. }
  10368. }
  10369. catch (e) {
  10370. // Do nothing
  10371. }
  10372. }
  10373. if (!this._gl) {
  10374. if (!canvas) {
  10375. throw new Error("The provided canvas is null or undefined.");
  10376. }
  10377. try {
  10378. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  10379. }
  10380. catch (e) {
  10381. throw new Error("WebGL not supported");
  10382. }
  10383. }
  10384. if (!this._gl) {
  10385. throw new Error("WebGL not supported");
  10386. }
  10387. this._onCanvasFocus = function () {
  10388. _this.onCanvasFocusObservable.notifyObservers(_this);
  10389. };
  10390. this._onCanvasBlur = function () {
  10391. _this.onCanvasBlurObservable.notifyObservers(_this);
  10392. };
  10393. canvas.addEventListener("focus", this._onCanvasFocus);
  10394. canvas.addEventListener("blur", this._onCanvasBlur);
  10395. this._onBlur = function () {
  10396. if (_this.disablePerformanceMonitorInBackground) {
  10397. _this._performanceMonitor.disable();
  10398. }
  10399. _this._windowIsBackground = true;
  10400. };
  10401. this._onFocus = function () {
  10402. if (_this.disablePerformanceMonitorInBackground) {
  10403. _this._performanceMonitor.enable();
  10404. }
  10405. _this._windowIsBackground = false;
  10406. };
  10407. this._onCanvasPointerOut = function () {
  10408. _this.onCanvasPointerOutObservable.notifyObservers(_this);
  10409. };
  10410. window.addEventListener("blur", this._onBlur);
  10411. window.addEventListener("focus", this._onFocus);
  10412. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  10413. // Context lost
  10414. if (!this._doNotHandleContextLost) {
  10415. this._onContextLost = function (evt) {
  10416. evt.preventDefault();
  10417. _this._contextWasLost = true;
  10418. BABYLON.Tools.Warn("WebGL context lost.");
  10419. _this.onContextLostObservable.notifyObservers(_this);
  10420. };
  10421. this._onContextRestored = function (evt) {
  10422. // Adding a timeout to avoid race condition at browser level
  10423. setTimeout(function () {
  10424. // Rebuild gl context
  10425. _this._initGLContext();
  10426. // Rebuild effects
  10427. _this._rebuildEffects();
  10428. // Rebuild textures
  10429. _this._rebuildInternalTextures();
  10430. // Rebuild buffers
  10431. _this._rebuildBuffers();
  10432. // Cache
  10433. _this.wipeCaches(true);
  10434. BABYLON.Tools.Warn("WebGL context successfully restored.");
  10435. _this.onContextRestoredObservable.notifyObservers(_this);
  10436. _this._contextWasLost = false;
  10437. }, 0);
  10438. };
  10439. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  10440. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  10441. }
  10442. }
  10443. else {
  10444. this._gl = canvasOrContext;
  10445. this._renderingCanvas = this._gl.canvas;
  10446. if (this._gl.renderbufferStorageMultisample) {
  10447. this._webGLVersion = 2.0;
  10448. }
  10449. options.stencil = this._gl.getContextAttributes().stencil;
  10450. }
  10451. // Viewport
  10452. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  10453. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  10454. this.resize();
  10455. this._isStencilEnable = options.stencil ? true : false;
  10456. this._initGLContext();
  10457. if (canvas) {
  10458. // Fullscreen
  10459. this._onFullscreenChange = function () {
  10460. if (document.fullscreen !== undefined) {
  10461. _this.isFullscreen = document.fullscreen;
  10462. }
  10463. else if (document.mozFullScreen !== undefined) {
  10464. _this.isFullscreen = document.mozFullScreen;
  10465. }
  10466. else if (document.webkitIsFullScreen !== undefined) {
  10467. _this.isFullscreen = document.webkitIsFullScreen;
  10468. }
  10469. else if (document.msIsFullScreen !== undefined) {
  10470. _this.isFullscreen = document.msIsFullScreen;
  10471. }
  10472. // Pointer lock
  10473. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  10474. canvas.requestPointerLock = canvas.requestPointerLock ||
  10475. canvas.msRequestPointerLock ||
  10476. canvas.mozRequestPointerLock ||
  10477. canvas.webkitRequestPointerLock;
  10478. if (canvas.requestPointerLock) {
  10479. canvas.requestPointerLock();
  10480. }
  10481. }
  10482. };
  10483. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  10484. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  10485. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  10486. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  10487. // Pointer lock
  10488. this._onPointerLockChange = function () {
  10489. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  10490. document.webkitPointerLockElement === canvas ||
  10491. document.msPointerLockElement === canvas ||
  10492. document.pointerLockElement === canvas);
  10493. };
  10494. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  10495. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  10496. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  10497. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  10498. this._onVRDisplayPointerRestricted = function () {
  10499. if (canvas) {
  10500. canvas.requestPointerLock();
  10501. }
  10502. };
  10503. this._onVRDisplayPointerUnrestricted = function () {
  10504. document.exitPointerLock();
  10505. };
  10506. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  10507. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  10508. }
  10509. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  10510. Engine.audioEngine = new BABYLON.AudioEngine();
  10511. }
  10512. // Prepare buffer pointers
  10513. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  10514. this._currentBufferPointers[i] = new BufferPointer();
  10515. }
  10516. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  10517. // Load WebVR Devices
  10518. if (options.autoEnableWebVR) {
  10519. this.initWebVR();
  10520. }
  10521. // Detect if we are running on a faulty buggy OS.
  10522. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  10523. // Detect if we are running on a faulty buggy desktop OS.
  10524. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  10525. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  10526. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  10527. }
  10528. Object.defineProperty(Engine, "LastCreatedEngine", {
  10529. get: function () {
  10530. if (Engine.Instances.length === 0) {
  10531. return null;
  10532. }
  10533. return Engine.Instances[Engine.Instances.length - 1];
  10534. },
  10535. enumerable: true,
  10536. configurable: true
  10537. });
  10538. Object.defineProperty(Engine, "LastCreatedScene", {
  10539. get: function () {
  10540. var lastCreatedEngine = Engine.LastCreatedEngine;
  10541. if (!lastCreatedEngine) {
  10542. return null;
  10543. }
  10544. if (lastCreatedEngine.scenes.length === 0) {
  10545. return null;
  10546. }
  10547. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  10548. },
  10549. enumerable: true,
  10550. configurable: true
  10551. });
  10552. /**
  10553. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  10554. */
  10555. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  10556. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  10557. var engine = Engine.Instances[engineIndex];
  10558. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  10559. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  10560. }
  10561. }
  10562. };
  10563. Object.defineProperty(Engine, "NEVER", {
  10564. get: function () {
  10565. return Engine._NEVER;
  10566. },
  10567. enumerable: true,
  10568. configurable: true
  10569. });
  10570. Object.defineProperty(Engine, "ALWAYS", {
  10571. get: function () {
  10572. return Engine._ALWAYS;
  10573. },
  10574. enumerable: true,
  10575. configurable: true
  10576. });
  10577. Object.defineProperty(Engine, "LESS", {
  10578. get: function () {
  10579. return Engine._LESS;
  10580. },
  10581. enumerable: true,
  10582. configurable: true
  10583. });
  10584. Object.defineProperty(Engine, "EQUAL", {
  10585. get: function () {
  10586. return Engine._EQUAL;
  10587. },
  10588. enumerable: true,
  10589. configurable: true
  10590. });
  10591. Object.defineProperty(Engine, "LEQUAL", {
  10592. get: function () {
  10593. return Engine._LEQUAL;
  10594. },
  10595. enumerable: true,
  10596. configurable: true
  10597. });
  10598. Object.defineProperty(Engine, "GREATER", {
  10599. get: function () {
  10600. return Engine._GREATER;
  10601. },
  10602. enumerable: true,
  10603. configurable: true
  10604. });
  10605. Object.defineProperty(Engine, "GEQUAL", {
  10606. get: function () {
  10607. return Engine._GEQUAL;
  10608. },
  10609. enumerable: true,
  10610. configurable: true
  10611. });
  10612. Object.defineProperty(Engine, "NOTEQUAL", {
  10613. get: function () {
  10614. return Engine._NOTEQUAL;
  10615. },
  10616. enumerable: true,
  10617. configurable: true
  10618. });
  10619. Object.defineProperty(Engine, "KEEP", {
  10620. get: function () {
  10621. return Engine._KEEP;
  10622. },
  10623. enumerable: true,
  10624. configurable: true
  10625. });
  10626. Object.defineProperty(Engine, "REPLACE", {
  10627. get: function () {
  10628. return Engine._REPLACE;
  10629. },
  10630. enumerable: true,
  10631. configurable: true
  10632. });
  10633. Object.defineProperty(Engine, "INCR", {
  10634. get: function () {
  10635. return Engine._INCR;
  10636. },
  10637. enumerable: true,
  10638. configurable: true
  10639. });
  10640. Object.defineProperty(Engine, "DECR", {
  10641. get: function () {
  10642. return Engine._DECR;
  10643. },
  10644. enumerable: true,
  10645. configurable: true
  10646. });
  10647. Object.defineProperty(Engine, "INVERT", {
  10648. get: function () {
  10649. return Engine._INVERT;
  10650. },
  10651. enumerable: true,
  10652. configurable: true
  10653. });
  10654. Object.defineProperty(Engine, "INCR_WRAP", {
  10655. get: function () {
  10656. return Engine._INCR_WRAP;
  10657. },
  10658. enumerable: true,
  10659. configurable: true
  10660. });
  10661. Object.defineProperty(Engine, "DECR_WRAP", {
  10662. get: function () {
  10663. return Engine._DECR_WRAP;
  10664. },
  10665. enumerable: true,
  10666. configurable: true
  10667. });
  10668. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  10669. get: function () {
  10670. return Engine._ALPHA_DISABLE;
  10671. },
  10672. enumerable: true,
  10673. configurable: true
  10674. });
  10675. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  10676. get: function () {
  10677. return Engine._ALPHA_ONEONE;
  10678. },
  10679. enumerable: true,
  10680. configurable: true
  10681. });
  10682. Object.defineProperty(Engine, "ALPHA_ADD", {
  10683. get: function () {
  10684. return Engine._ALPHA_ADD;
  10685. },
  10686. enumerable: true,
  10687. configurable: true
  10688. });
  10689. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  10690. get: function () {
  10691. return Engine._ALPHA_COMBINE;
  10692. },
  10693. enumerable: true,
  10694. configurable: true
  10695. });
  10696. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  10697. get: function () {
  10698. return Engine._ALPHA_SUBTRACT;
  10699. },
  10700. enumerable: true,
  10701. configurable: true
  10702. });
  10703. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  10704. get: function () {
  10705. return Engine._ALPHA_MULTIPLY;
  10706. },
  10707. enumerable: true,
  10708. configurable: true
  10709. });
  10710. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  10711. get: function () {
  10712. return Engine._ALPHA_MAXIMIZED;
  10713. },
  10714. enumerable: true,
  10715. configurable: true
  10716. });
  10717. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  10718. get: function () {
  10719. return Engine._ALPHA_PREMULTIPLIED;
  10720. },
  10721. enumerable: true,
  10722. configurable: true
  10723. });
  10724. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  10725. get: function () {
  10726. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  10727. },
  10728. enumerable: true,
  10729. configurable: true
  10730. });
  10731. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  10732. get: function () {
  10733. return Engine._ALPHA_INTERPOLATE;
  10734. },
  10735. enumerable: true,
  10736. configurable: true
  10737. });
  10738. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  10739. get: function () {
  10740. return Engine._ALPHA_SCREENMODE;
  10741. },
  10742. enumerable: true,
  10743. configurable: true
  10744. });
  10745. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  10746. get: function () {
  10747. return Engine._DELAYLOADSTATE_NONE;
  10748. },
  10749. enumerable: true,
  10750. configurable: true
  10751. });
  10752. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  10753. get: function () {
  10754. return Engine._DELAYLOADSTATE_LOADED;
  10755. },
  10756. enumerable: true,
  10757. configurable: true
  10758. });
  10759. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  10760. get: function () {
  10761. return Engine._DELAYLOADSTATE_LOADING;
  10762. },
  10763. enumerable: true,
  10764. configurable: true
  10765. });
  10766. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  10767. get: function () {
  10768. return Engine._DELAYLOADSTATE_NOTLOADED;
  10769. },
  10770. enumerable: true,
  10771. configurable: true
  10772. });
  10773. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  10774. get: function () {
  10775. return Engine._TEXTUREFORMAT_ALPHA;
  10776. },
  10777. enumerable: true,
  10778. configurable: true
  10779. });
  10780. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  10781. get: function () {
  10782. return Engine._TEXTUREFORMAT_LUMINANCE;
  10783. },
  10784. enumerable: true,
  10785. configurable: true
  10786. });
  10787. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  10788. get: function () {
  10789. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  10790. },
  10791. enumerable: true,
  10792. configurable: true
  10793. });
  10794. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  10795. get: function () {
  10796. return Engine._TEXTUREFORMAT_RGB;
  10797. },
  10798. enumerable: true,
  10799. configurable: true
  10800. });
  10801. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  10802. get: function () {
  10803. return Engine._TEXTUREFORMAT_RGBA;
  10804. },
  10805. enumerable: true,
  10806. configurable: true
  10807. });
  10808. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  10809. get: function () {
  10810. return Engine._TEXTURETYPE_UNSIGNED_INT;
  10811. },
  10812. enumerable: true,
  10813. configurable: true
  10814. });
  10815. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  10816. get: function () {
  10817. return Engine._TEXTURETYPE_FLOAT;
  10818. },
  10819. enumerable: true,
  10820. configurable: true
  10821. });
  10822. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  10823. get: function () {
  10824. return Engine._TEXTURETYPE_HALF_FLOAT;
  10825. },
  10826. enumerable: true,
  10827. configurable: true
  10828. });
  10829. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  10830. get: function () {
  10831. return Engine._SCALEMODE_FLOOR;
  10832. },
  10833. enumerable: true,
  10834. configurable: true
  10835. });
  10836. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  10837. get: function () {
  10838. return Engine._SCALEMODE_NEAREST;
  10839. },
  10840. enumerable: true,
  10841. configurable: true
  10842. });
  10843. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  10844. get: function () {
  10845. return Engine._SCALEMODE_CEILING;
  10846. },
  10847. enumerable: true,
  10848. configurable: true
  10849. });
  10850. Object.defineProperty(Engine, "Version", {
  10851. get: function () {
  10852. return "3.2.0-alpha7";
  10853. },
  10854. enumerable: true,
  10855. configurable: true
  10856. });
  10857. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  10858. get: function () {
  10859. return this._vrExclusivePointerMode;
  10860. },
  10861. enumerable: true,
  10862. configurable: true
  10863. });
  10864. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  10865. get: function () {
  10866. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  10867. },
  10868. enumerable: true,
  10869. configurable: true
  10870. });
  10871. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  10872. get: function () {
  10873. return this._webGLVersion < 2 || this.forcePOTTextures;
  10874. },
  10875. enumerable: true,
  10876. configurable: true
  10877. });
  10878. Object.defineProperty(Engine.prototype, "badOS", {
  10879. get: function () {
  10880. return this._badOS;
  10881. },
  10882. enumerable: true,
  10883. configurable: true
  10884. });
  10885. Object.defineProperty(Engine.prototype, "badDesktopOS", {
  10886. get: function () {
  10887. return this._badDesktopOS;
  10888. },
  10889. enumerable: true,
  10890. configurable: true
  10891. });
  10892. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  10893. get: function () {
  10894. return this._performanceMonitor;
  10895. },
  10896. enumerable: true,
  10897. configurable: true
  10898. });
  10899. Object.defineProperty(Engine.prototype, "texturesSupported", {
  10900. get: function () {
  10901. return this._texturesSupported;
  10902. },
  10903. enumerable: true,
  10904. configurable: true
  10905. });
  10906. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  10907. get: function () {
  10908. return this._textureFormatInUse;
  10909. },
  10910. enumerable: true,
  10911. configurable: true
  10912. });
  10913. Object.defineProperty(Engine.prototype, "currentViewport", {
  10914. get: function () {
  10915. return this._cachedViewport;
  10916. },
  10917. enumerable: true,
  10918. configurable: true
  10919. });
  10920. Object.defineProperty(Engine.prototype, "emptyTexture", {
  10921. // Empty texture
  10922. get: function () {
  10923. if (!this._emptyTexture) {
  10924. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  10925. }
  10926. return this._emptyTexture;
  10927. },
  10928. enumerable: true,
  10929. configurable: true
  10930. });
  10931. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  10932. get: function () {
  10933. if (!this._emptyTexture3D) {
  10934. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  10935. }
  10936. return this._emptyTexture3D;
  10937. },
  10938. enumerable: true,
  10939. configurable: true
  10940. });
  10941. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  10942. get: function () {
  10943. if (!this._emptyCubeTexture) {
  10944. var faceData = new Uint8Array(4);
  10945. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  10946. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  10947. }
  10948. return this._emptyCubeTexture;
  10949. },
  10950. enumerable: true,
  10951. configurable: true
  10952. });
  10953. Engine.prototype._rebuildInternalTextures = function () {
  10954. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  10955. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  10956. var internalTexture = currentState_1[_i];
  10957. internalTexture._rebuild();
  10958. }
  10959. };
  10960. Engine.prototype._rebuildEffects = function () {
  10961. for (var key in this._compiledEffects) {
  10962. var effect = this._compiledEffects[key];
  10963. effect._prepareEffect();
  10964. }
  10965. BABYLON.Effect.ResetCache();
  10966. };
  10967. Engine.prototype._rebuildBuffers = function () {
  10968. // Index / Vertex
  10969. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  10970. var scene = _a[_i];
  10971. scene.resetCachedMaterial();
  10972. scene._rebuildGeometries();
  10973. scene._rebuildTextures();
  10974. }
  10975. // Uniforms
  10976. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  10977. var uniformBuffer = _c[_b];
  10978. uniformBuffer._rebuild();
  10979. }
  10980. };
  10981. Engine.prototype._initGLContext = function () {
  10982. // Caps
  10983. this._caps = new EngineCapabilities();
  10984. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  10985. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  10986. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  10987. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  10988. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  10989. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  10990. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  10991. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  10992. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  10993. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  10994. // Infos
  10995. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  10996. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  10997. if (rendererInfo != null) {
  10998. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  10999. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  11000. }
  11001. if (!this._glVendor) {
  11002. this._glVendor = "Unknown vendor";
  11003. }
  11004. if (!this._glRenderer) {
  11005. this._glRenderer = "Unknown renderer";
  11006. }
  11007. // Constants
  11008. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  11009. if (this._gl.RGBA16F !== 0x881A) {
  11010. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  11011. }
  11012. if (this._gl.RGBA32F !== 0x8814) {
  11013. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  11014. }
  11015. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  11016. this._gl.DEPTH24_STENCIL8 = 35056;
  11017. }
  11018. // Extensions
  11019. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  11020. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  11021. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  11022. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  11023. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  11024. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  11025. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  11026. 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');
  11027. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  11028. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  11029. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  11030. this._caps.highPrecisionShaderSupported = true;
  11031. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  11032. if (this._caps.timerQuery) {
  11033. if (this._webGLVersion === 1) {
  11034. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  11035. }
  11036. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  11037. }
  11038. // Checks if some of the format renders first to allow the use of webgl inspector.
  11039. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  11040. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  11041. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  11042. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  11043. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  11044. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  11045. if (this._webGLVersion > 1) {
  11046. this._gl.HALF_FLOAT_OES = 0x140B;
  11047. }
  11048. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  11049. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  11050. // Draw buffers
  11051. if (this._webGLVersion > 1) {
  11052. this._caps.drawBuffersExtension = true;
  11053. }
  11054. else {
  11055. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  11056. if (drawBuffersExtension !== null) {
  11057. this._caps.drawBuffersExtension = true;
  11058. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  11059. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  11060. for (var i = 0; i < 16; i++) {
  11061. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  11062. }
  11063. }
  11064. else {
  11065. this._caps.drawBuffersExtension = false;
  11066. }
  11067. }
  11068. // Depth Texture
  11069. if (this._webGLVersion > 1) {
  11070. this._caps.depthTextureExtension = true;
  11071. }
  11072. else {
  11073. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  11074. if (depthTextureExtension != null) {
  11075. this._caps.depthTextureExtension = true;
  11076. }
  11077. }
  11078. // Vertex array object
  11079. if (this._webGLVersion > 1) {
  11080. this._caps.vertexArrayObject = true;
  11081. }
  11082. else {
  11083. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  11084. if (vertexArrayObjectExtension != null) {
  11085. this._caps.vertexArrayObject = true;
  11086. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  11087. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  11088. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  11089. }
  11090. else {
  11091. this._caps.vertexArrayObject = false;
  11092. }
  11093. }
  11094. // Instances count
  11095. if (this._webGLVersion > 1) {
  11096. this._caps.instancedArrays = true;
  11097. }
  11098. else {
  11099. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  11100. if (instanceExtension != null) {
  11101. this._caps.instancedArrays = true;
  11102. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  11103. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  11104. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  11105. }
  11106. else {
  11107. this._caps.instancedArrays = false;
  11108. }
  11109. }
  11110. // Intelligently add supported compressed formats in order to check for.
  11111. // Check for ASTC support first as it is most powerful and to be very cross platform.
  11112. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  11113. // Likely no hardware which supports both PVR & DXT, so order matters little.
  11114. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  11115. if (this._caps.astc)
  11116. this.texturesSupported.push('-astc.ktx');
  11117. if (this._caps.s3tc)
  11118. this.texturesSupported.push('-dxt.ktx');
  11119. if (this._caps.pvrtc)
  11120. this.texturesSupported.push('-pvrtc.ktx');
  11121. if (this._caps.etc2)
  11122. this.texturesSupported.push('-etc2.ktx');
  11123. if (this._caps.etc1)
  11124. this.texturesSupported.push('-etc1.ktx');
  11125. if (this._gl.getShaderPrecisionFormat) {
  11126. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  11127. if (highp) {
  11128. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  11129. }
  11130. }
  11131. // Depth buffer
  11132. this.setDepthBuffer(true);
  11133. this.setDepthFunctionToLessOrEqual();
  11134. this.setDepthWrite(true);
  11135. // Texture maps
  11136. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  11137. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  11138. this._nextFreeTextureSlots.push(slot);
  11139. }
  11140. };
  11141. Object.defineProperty(Engine.prototype, "webGLVersion", {
  11142. get: function () {
  11143. return this._webGLVersion;
  11144. },
  11145. enumerable: true,
  11146. configurable: true
  11147. });
  11148. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  11149. /**
  11150. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  11151. */
  11152. get: function () {
  11153. return this._isStencilEnable;
  11154. },
  11155. enumerable: true,
  11156. configurable: true
  11157. });
  11158. Engine.prototype._prepareWorkingCanvas = function () {
  11159. if (this._workingCanvas) {
  11160. return;
  11161. }
  11162. this._workingCanvas = document.createElement("canvas");
  11163. var context = this._workingCanvas.getContext("2d");
  11164. if (context) {
  11165. this._workingContext = context;
  11166. }
  11167. };
  11168. Engine.prototype.resetTextureCache = function () {
  11169. for (var key in this._boundTexturesCache) {
  11170. var boundTexture = this._boundTexturesCache[key];
  11171. if (boundTexture) {
  11172. this._removeDesignatedSlot(boundTexture);
  11173. }
  11174. this._boundTexturesCache[key] = null;
  11175. }
  11176. if (!this.disableTextureBindingOptimization) {
  11177. this._nextFreeTextureSlots = [];
  11178. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  11179. this._nextFreeTextureSlots.push(slot);
  11180. }
  11181. }
  11182. this._currentTextureChannel = -1;
  11183. };
  11184. Engine.prototype.isDeterministicLockStep = function () {
  11185. return this._deterministicLockstep;
  11186. };
  11187. Engine.prototype.getLockstepMaxSteps = function () {
  11188. return this._lockstepMaxSteps;
  11189. };
  11190. Engine.prototype.getGlInfo = function () {
  11191. return {
  11192. vendor: this._glVendor,
  11193. renderer: this._glRenderer,
  11194. version: this._glVersion
  11195. };
  11196. };
  11197. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  11198. if (useScreen === void 0) { useScreen = false; }
  11199. var viewport = camera.viewport;
  11200. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  11201. };
  11202. Engine.prototype.getRenderWidth = function (useScreen) {
  11203. if (useScreen === void 0) { useScreen = false; }
  11204. if (!useScreen && this._currentRenderTarget) {
  11205. return this._currentRenderTarget.width;
  11206. }
  11207. return this._gl.drawingBufferWidth;
  11208. };
  11209. Engine.prototype.getRenderHeight = function (useScreen) {
  11210. if (useScreen === void 0) { useScreen = false; }
  11211. if (!useScreen && this._currentRenderTarget) {
  11212. return this._currentRenderTarget.height;
  11213. }
  11214. return this._gl.drawingBufferHeight;
  11215. };
  11216. Engine.prototype.getRenderingCanvas = function () {
  11217. return this._renderingCanvas;
  11218. };
  11219. Engine.prototype.getRenderingCanvasClientRect = function () {
  11220. if (!this._renderingCanvas) {
  11221. return null;
  11222. }
  11223. return this._renderingCanvas.getBoundingClientRect();
  11224. };
  11225. Engine.prototype.setHardwareScalingLevel = function (level) {
  11226. this._hardwareScalingLevel = level;
  11227. this.resize();
  11228. };
  11229. Engine.prototype.getHardwareScalingLevel = function () {
  11230. return this._hardwareScalingLevel;
  11231. };
  11232. Engine.prototype.getLoadedTexturesCache = function () {
  11233. return this._internalTexturesCache;
  11234. };
  11235. Engine.prototype.getCaps = function () {
  11236. return this._caps;
  11237. };
  11238. Object.defineProperty(Engine.prototype, "drawCalls", {
  11239. /** The number of draw calls submitted last frame */
  11240. get: function () {
  11241. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  11242. return 0;
  11243. },
  11244. enumerable: true,
  11245. configurable: true
  11246. });
  11247. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  11248. get: function () {
  11249. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  11250. return null;
  11251. },
  11252. enumerable: true,
  11253. configurable: true
  11254. });
  11255. Engine.prototype.getDepthFunction = function () {
  11256. return this._depthCullingState.depthFunc;
  11257. };
  11258. Engine.prototype.setDepthFunction = function (depthFunc) {
  11259. this._depthCullingState.depthFunc = depthFunc;
  11260. };
  11261. Engine.prototype.setDepthFunctionToGreater = function () {
  11262. this._depthCullingState.depthFunc = this._gl.GREATER;
  11263. };
  11264. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  11265. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  11266. };
  11267. Engine.prototype.setDepthFunctionToLess = function () {
  11268. this._depthCullingState.depthFunc = this._gl.LESS;
  11269. };
  11270. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  11271. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  11272. };
  11273. Engine.prototype.getStencilBuffer = function () {
  11274. return this._stencilState.stencilTest;
  11275. };
  11276. Engine.prototype.setStencilBuffer = function (enable) {
  11277. this._stencilState.stencilTest = enable;
  11278. };
  11279. Engine.prototype.getStencilMask = function () {
  11280. return this._stencilState.stencilMask;
  11281. };
  11282. Engine.prototype.setStencilMask = function (mask) {
  11283. this._stencilState.stencilMask = mask;
  11284. };
  11285. Engine.prototype.getStencilFunction = function () {
  11286. return this._stencilState.stencilFunc;
  11287. };
  11288. Engine.prototype.getStencilFunctionReference = function () {
  11289. return this._stencilState.stencilFuncRef;
  11290. };
  11291. Engine.prototype.getStencilFunctionMask = function () {
  11292. return this._stencilState.stencilFuncMask;
  11293. };
  11294. Engine.prototype.setStencilFunction = function (stencilFunc) {
  11295. this._stencilState.stencilFunc = stencilFunc;
  11296. };
  11297. Engine.prototype.setStencilFunctionReference = function (reference) {
  11298. this._stencilState.stencilFuncRef = reference;
  11299. };
  11300. Engine.prototype.setStencilFunctionMask = function (mask) {
  11301. this._stencilState.stencilFuncMask = mask;
  11302. };
  11303. Engine.prototype.getStencilOperationFail = function () {
  11304. return this._stencilState.stencilOpStencilFail;
  11305. };
  11306. Engine.prototype.getStencilOperationDepthFail = function () {
  11307. return this._stencilState.stencilOpDepthFail;
  11308. };
  11309. Engine.prototype.getStencilOperationPass = function () {
  11310. return this._stencilState.stencilOpStencilDepthPass;
  11311. };
  11312. Engine.prototype.setStencilOperationFail = function (operation) {
  11313. this._stencilState.stencilOpStencilFail = operation;
  11314. };
  11315. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  11316. this._stencilState.stencilOpDepthFail = operation;
  11317. };
  11318. Engine.prototype.setStencilOperationPass = function (operation) {
  11319. this._stencilState.stencilOpStencilDepthPass = operation;
  11320. };
  11321. Engine.prototype.setDitheringState = function (value) {
  11322. if (value) {
  11323. this._gl.enable(this._gl.DITHER);
  11324. }
  11325. else {
  11326. this._gl.disable(this._gl.DITHER);
  11327. }
  11328. };
  11329. Engine.prototype.setRasterizerState = function (value) {
  11330. if (value) {
  11331. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  11332. }
  11333. else {
  11334. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  11335. }
  11336. };
  11337. /**
  11338. * stop executing a render loop function and remove it from the execution array
  11339. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  11340. */
  11341. Engine.prototype.stopRenderLoop = function (renderFunction) {
  11342. if (!renderFunction) {
  11343. this._activeRenderLoops = [];
  11344. return;
  11345. }
  11346. var index = this._activeRenderLoops.indexOf(renderFunction);
  11347. if (index >= 0) {
  11348. this._activeRenderLoops.splice(index, 1);
  11349. }
  11350. };
  11351. Engine.prototype._renderLoop = function () {
  11352. if (!this._contextWasLost) {
  11353. var shouldRender = true;
  11354. if (!this.renderEvenInBackground && this._windowIsBackground) {
  11355. shouldRender = false;
  11356. }
  11357. if (shouldRender) {
  11358. // Start new frame
  11359. this.beginFrame();
  11360. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  11361. var renderFunction = this._activeRenderLoops[index];
  11362. renderFunction();
  11363. }
  11364. // Present
  11365. this.endFrame();
  11366. }
  11367. }
  11368. if (this._activeRenderLoops.length > 0) {
  11369. // Register new frame
  11370. var requester = null;
  11371. if (this._vrDisplay && this._vrDisplay.isPresenting)
  11372. requester = this._vrDisplay;
  11373. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  11374. }
  11375. else {
  11376. this._renderingQueueLaunched = false;
  11377. }
  11378. };
  11379. /**
  11380. * Register and execute a render loop. The engine can have more than one render function.
  11381. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  11382. * @example
  11383. * engine.runRenderLoop(function () {
  11384. * scene.render()
  11385. * })
  11386. */
  11387. Engine.prototype.runRenderLoop = function (renderFunction) {
  11388. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  11389. return;
  11390. }
  11391. this._activeRenderLoops.push(renderFunction);
  11392. if (!this._renderingQueueLaunched) {
  11393. this._renderingQueueLaunched = true;
  11394. this._bindedRenderFunction = this._renderLoop.bind(this);
  11395. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  11396. }
  11397. };
  11398. /**
  11399. * Toggle full screen mode.
  11400. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  11401. * @param {any} options - an options object to be sent to the requestFullscreen function
  11402. */
  11403. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  11404. if (this.isFullscreen) {
  11405. BABYLON.Tools.ExitFullscreen();
  11406. }
  11407. else {
  11408. this._pointerLockRequested = requestPointerLock;
  11409. if (this._renderingCanvas) {
  11410. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  11411. }
  11412. }
  11413. };
  11414. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  11415. if (stencil === void 0) { stencil = false; }
  11416. this.applyStates();
  11417. var mode = 0;
  11418. if (backBuffer && color) {
  11419. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  11420. mode |= this._gl.COLOR_BUFFER_BIT;
  11421. }
  11422. if (depth) {
  11423. this._gl.clearDepth(1.0);
  11424. mode |= this._gl.DEPTH_BUFFER_BIT;
  11425. }
  11426. if (stencil) {
  11427. this._gl.clearStencil(0);
  11428. mode |= this._gl.STENCIL_BUFFER_BIT;
  11429. }
  11430. this._gl.clear(mode);
  11431. };
  11432. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  11433. var gl = this._gl;
  11434. // Save state
  11435. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  11436. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  11437. // Change state
  11438. gl.enable(gl.SCISSOR_TEST);
  11439. gl.scissor(x, y, width, height);
  11440. // Clear
  11441. this.clear(clearColor, true, true, true);
  11442. // Restore state
  11443. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  11444. if (curScissor === true) {
  11445. gl.enable(gl.SCISSOR_TEST);
  11446. }
  11447. else {
  11448. gl.disable(gl.SCISSOR_TEST);
  11449. }
  11450. };
  11451. /**
  11452. * Set the WebGL's viewport
  11453. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  11454. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  11455. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  11456. */
  11457. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  11458. var width = requiredWidth || this.getRenderWidth();
  11459. var height = requiredHeight || this.getRenderHeight();
  11460. var x = viewport.x || 0;
  11461. var y = viewport.y || 0;
  11462. this._cachedViewport = viewport;
  11463. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  11464. };
  11465. /**
  11466. * Directly set the WebGL Viewport
  11467. * The x, y, width & height are directly passed to the WebGL call
  11468. * @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.
  11469. */
  11470. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  11471. var currentViewport = this._cachedViewport;
  11472. this._cachedViewport = null;
  11473. this._gl.viewport(x, y, width, height);
  11474. return currentViewport;
  11475. };
  11476. Engine.prototype.beginFrame = function () {
  11477. this.onBeginFrameObservable.notifyObservers(this);
  11478. this._measureFps();
  11479. };
  11480. Engine.prototype.endFrame = function () {
  11481. //force a flush in case we are using a bad OS.
  11482. if (this._badOS) {
  11483. this.flushFramebuffer();
  11484. }
  11485. //submit frame to the vr device, if enabled
  11486. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  11487. // TODO: We should only submit the frame if we read frameData successfully.
  11488. this._vrDisplay.submitFrame();
  11489. }
  11490. this.onEndFrameObservable.notifyObservers(this);
  11491. };
  11492. /**
  11493. * resize the view according to the canvas' size.
  11494. * @example
  11495. * window.addEventListener("resize", function () {
  11496. * engine.resize();
  11497. * });
  11498. */
  11499. Engine.prototype.resize = function () {
  11500. // We're not resizing the size of the canvas while in VR mode & presenting
  11501. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  11502. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  11503. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  11504. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  11505. }
  11506. };
  11507. /**
  11508. * force a specific size of the canvas
  11509. * @param {number} width - the new canvas' width
  11510. * @param {number} height - the new canvas' height
  11511. */
  11512. Engine.prototype.setSize = function (width, height) {
  11513. if (!this._renderingCanvas) {
  11514. return;
  11515. }
  11516. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  11517. return;
  11518. }
  11519. this._renderingCanvas.width = width;
  11520. this._renderingCanvas.height = height;
  11521. for (var index = 0; index < this.scenes.length; index++) {
  11522. var scene = this.scenes[index];
  11523. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  11524. var cam = scene.cameras[camIndex];
  11525. cam._currentRenderId = 0;
  11526. }
  11527. }
  11528. if (this.onResizeObservable.hasObservers) {
  11529. this.onResizeObservable.notifyObservers(this);
  11530. }
  11531. };
  11532. // WebVR functions
  11533. Engine.prototype.isVRDevicePresent = function () {
  11534. return !!this._vrDisplay;
  11535. };
  11536. Engine.prototype.getVRDevice = function () {
  11537. return this._vrDisplay;
  11538. };
  11539. Engine.prototype.initWebVR = function () {
  11540. var _this = this;
  11541. var notifyObservers = function () {
  11542. var eventArgs = {
  11543. vrDisplay: _this._vrDisplay,
  11544. vrSupported: _this._vrSupported
  11545. };
  11546. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  11547. };
  11548. if (!this._onVrDisplayConnect) {
  11549. this._onVrDisplayConnect = function (event) {
  11550. _this._vrDisplay = event.display;
  11551. notifyObservers();
  11552. };
  11553. this._onVrDisplayDisconnect = function () {
  11554. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  11555. _this._vrDisplay = undefined;
  11556. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  11557. notifyObservers();
  11558. };
  11559. this._onVrDisplayPresentChange = function () {
  11560. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  11561. };
  11562. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  11563. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  11564. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  11565. }
  11566. this._getVRDisplays(notifyObservers);
  11567. return this.onVRDisplayChangedObservable;
  11568. };
  11569. Engine.prototype.enableVR = function () {
  11570. var _this = this;
  11571. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  11572. var onResolved = function () {
  11573. _this.onVRRequestPresentComplete.notifyObservers(true);
  11574. _this._onVRFullScreenTriggered();
  11575. };
  11576. var onRejected = function () {
  11577. _this.onVRRequestPresentComplete.notifyObservers(false);
  11578. };
  11579. this.onVRRequestPresentStart.notifyObservers(this);
  11580. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  11581. }
  11582. };
  11583. Engine.prototype.disableVR = function () {
  11584. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  11585. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  11586. }
  11587. };
  11588. Engine.prototype._getVRDisplays = function (callback) {
  11589. var _this = this;
  11590. var getWebVRDevices = function (devices) {
  11591. _this._vrSupported = true;
  11592. // note that devices may actually be an empty array. This is fine;
  11593. // we expect this._vrDisplay to be undefined in this case.
  11594. return _this._vrDisplay = devices[0];
  11595. };
  11596. if (navigator.getVRDisplays) {
  11597. navigator.getVRDisplays().then(getWebVRDevices).then(callback).catch(function (error) {
  11598. // TODO: System CANNOT support WebVR, despite API presence.
  11599. _this._vrSupported = false;
  11600. callback();
  11601. });
  11602. }
  11603. else {
  11604. // TODO: Browser does not support WebVR
  11605. this._vrDisplay = undefined;
  11606. this._vrSupported = false;
  11607. callback();
  11608. }
  11609. };
  11610. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  11611. if (this._currentRenderTarget) {
  11612. this.unBindFramebuffer(this._currentRenderTarget);
  11613. }
  11614. this._currentRenderTarget = texture;
  11615. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  11616. var gl = this._gl;
  11617. if (texture.isCube) {
  11618. if (faceIndex === undefined) {
  11619. faceIndex = 0;
  11620. }
  11621. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  11622. }
  11623. if (this._cachedViewport && !forceFullscreenViewport) {
  11624. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  11625. }
  11626. else {
  11627. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  11628. }
  11629. this.wipeCaches();
  11630. };
  11631. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  11632. if (this._currentFramebuffer !== framebuffer) {
  11633. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  11634. this._currentFramebuffer = framebuffer;
  11635. }
  11636. };
  11637. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  11638. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  11639. this._currentRenderTarget = null;
  11640. // If MSAA, we need to bitblt back to main texture
  11641. var gl = this._gl;
  11642. if (texture._MSAAFramebuffer) {
  11643. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  11644. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  11645. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  11646. }
  11647. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  11648. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  11649. gl.generateMipmap(gl.TEXTURE_2D);
  11650. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  11651. }
  11652. if (onBeforeUnbind) {
  11653. if (texture._MSAAFramebuffer) {
  11654. // Bind the correct framebuffer
  11655. this.bindUnboundFramebuffer(texture._framebuffer);
  11656. }
  11657. onBeforeUnbind();
  11658. }
  11659. this.bindUnboundFramebuffer(null);
  11660. };
  11661. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  11662. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  11663. this._currentRenderTarget = null;
  11664. // If MSAA, we need to bitblt back to main texture
  11665. var gl = this._gl;
  11666. if (textures[0]._MSAAFramebuffer) {
  11667. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  11668. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  11669. var attachments = textures[0]._attachments;
  11670. if (!attachments) {
  11671. attachments = new Array(textures.length);
  11672. textures[0]._attachments = attachments;
  11673. }
  11674. for (var i = 0; i < textures.length; i++) {
  11675. var texture = textures[i];
  11676. for (var j = 0; j < attachments.length; j++) {
  11677. attachments[j] = gl.NONE;
  11678. }
  11679. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  11680. gl.readBuffer(attachments[i]);
  11681. gl.drawBuffers(attachments);
  11682. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  11683. }
  11684. for (var i = 0; i < attachments.length; i++) {
  11685. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  11686. }
  11687. gl.drawBuffers(attachments);
  11688. }
  11689. for (var i = 0; i < textures.length; i++) {
  11690. var texture = textures[i];
  11691. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  11692. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  11693. gl.generateMipmap(gl.TEXTURE_2D);
  11694. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  11695. }
  11696. }
  11697. if (onBeforeUnbind) {
  11698. if (textures[0]._MSAAFramebuffer) {
  11699. // Bind the correct framebuffer
  11700. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  11701. }
  11702. onBeforeUnbind();
  11703. }
  11704. this.bindUnboundFramebuffer(null);
  11705. };
  11706. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  11707. if (texture.generateMipMaps) {
  11708. var gl = this._gl;
  11709. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  11710. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  11711. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  11712. }
  11713. };
  11714. Engine.prototype.flushFramebuffer = function () {
  11715. this._gl.flush();
  11716. };
  11717. Engine.prototype.restoreDefaultFramebuffer = function () {
  11718. if (this._currentRenderTarget) {
  11719. this.unBindFramebuffer(this._currentRenderTarget);
  11720. }
  11721. else {
  11722. this.bindUnboundFramebuffer(null);
  11723. }
  11724. if (this._cachedViewport) {
  11725. this.setViewport(this._cachedViewport);
  11726. }
  11727. this.wipeCaches();
  11728. };
  11729. // UBOs
  11730. Engine.prototype.createUniformBuffer = function (elements) {
  11731. var ubo = this._gl.createBuffer();
  11732. if (!ubo) {
  11733. throw new Error("Unable to create uniform buffer");
  11734. }
  11735. this.bindUniformBuffer(ubo);
  11736. if (elements instanceof Float32Array) {
  11737. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  11738. }
  11739. else {
  11740. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  11741. }
  11742. this.bindUniformBuffer(null);
  11743. ubo.references = 1;
  11744. return ubo;
  11745. };
  11746. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  11747. var ubo = this._gl.createBuffer();
  11748. if (!ubo) {
  11749. throw new Error("Unable to create dynamic uniform buffer");
  11750. }
  11751. this.bindUniformBuffer(ubo);
  11752. if (elements instanceof Float32Array) {
  11753. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  11754. }
  11755. else {
  11756. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  11757. }
  11758. this.bindUniformBuffer(null);
  11759. ubo.references = 1;
  11760. return ubo;
  11761. };
  11762. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  11763. this.bindUniformBuffer(uniformBuffer);
  11764. if (offset === undefined) {
  11765. offset = 0;
  11766. }
  11767. if (count === undefined) {
  11768. if (elements instanceof Float32Array) {
  11769. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  11770. }
  11771. else {
  11772. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  11773. }
  11774. }
  11775. else {
  11776. if (elements instanceof Float32Array) {
  11777. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  11778. }
  11779. else {
  11780. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  11781. }
  11782. }
  11783. this.bindUniformBuffer(null);
  11784. };
  11785. // VBOs
  11786. Engine.prototype._resetVertexBufferBinding = function () {
  11787. this.bindArrayBuffer(null);
  11788. this._cachedVertexBuffers = null;
  11789. };
  11790. Engine.prototype.createVertexBuffer = function (vertices) {
  11791. var vbo = this._gl.createBuffer();
  11792. if (!vbo) {
  11793. throw new Error("Unable to create vertex buffer");
  11794. }
  11795. this.bindArrayBuffer(vbo);
  11796. if (vertices instanceof Float32Array) {
  11797. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  11798. }
  11799. else {
  11800. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  11801. }
  11802. this._resetVertexBufferBinding();
  11803. vbo.references = 1;
  11804. return vbo;
  11805. };
  11806. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  11807. var vbo = this._gl.createBuffer();
  11808. if (!vbo) {
  11809. throw new Error("Unable to create dynamic vertex buffer");
  11810. }
  11811. this.bindArrayBuffer(vbo);
  11812. if (vertices instanceof Float32Array) {
  11813. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  11814. }
  11815. else {
  11816. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  11817. }
  11818. this._resetVertexBufferBinding();
  11819. vbo.references = 1;
  11820. return vbo;
  11821. };
  11822. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  11823. if (offset === void 0) { offset = 0; }
  11824. // Force cache update
  11825. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  11826. this.bindIndexBuffer(indexBuffer);
  11827. var arrayBuffer;
  11828. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  11829. arrayBuffer = indices;
  11830. }
  11831. else {
  11832. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  11833. }
  11834. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  11835. this._resetIndexBufferBinding();
  11836. };
  11837. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  11838. this.bindArrayBuffer(vertexBuffer);
  11839. if (offset === undefined) {
  11840. offset = 0;
  11841. }
  11842. if (count === undefined) {
  11843. if (vertices instanceof Float32Array) {
  11844. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  11845. }
  11846. else {
  11847. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  11848. }
  11849. }
  11850. else {
  11851. if (vertices instanceof Float32Array) {
  11852. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  11853. }
  11854. else {
  11855. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  11856. }
  11857. }
  11858. this._resetVertexBufferBinding();
  11859. };
  11860. Engine.prototype._resetIndexBufferBinding = function () {
  11861. this.bindIndexBuffer(null);
  11862. this._cachedIndexBuffer = null;
  11863. };
  11864. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  11865. var vbo = this._gl.createBuffer();
  11866. if (!vbo) {
  11867. throw new Error("Unable to create index buffer");
  11868. }
  11869. this.bindIndexBuffer(vbo);
  11870. // Check for 32 bits indices
  11871. var arrayBuffer;
  11872. var need32Bits = false;
  11873. if (indices instanceof Uint16Array) {
  11874. arrayBuffer = indices;
  11875. }
  11876. else {
  11877. //check 32 bit support
  11878. if (this._caps.uintIndices) {
  11879. if (indices instanceof Uint32Array) {
  11880. arrayBuffer = indices;
  11881. need32Bits = true;
  11882. }
  11883. else {
  11884. //number[] or Int32Array, check if 32 bit is necessary
  11885. for (var index = 0; index < indices.length; index++) {
  11886. if (indices[index] > 65535) {
  11887. need32Bits = true;
  11888. break;
  11889. }
  11890. }
  11891. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  11892. }
  11893. }
  11894. else {
  11895. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  11896. arrayBuffer = new Uint16Array(indices);
  11897. }
  11898. }
  11899. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  11900. this._resetIndexBufferBinding();
  11901. vbo.references = 1;
  11902. vbo.is32Bits = need32Bits;
  11903. return vbo;
  11904. };
  11905. Engine.prototype.bindArrayBuffer = function (buffer) {
  11906. if (!this._vaoRecordInProgress) {
  11907. this._unbindVertexArrayObject();
  11908. }
  11909. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  11910. };
  11911. Engine.prototype.bindUniformBuffer = function (buffer) {
  11912. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  11913. };
  11914. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  11915. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  11916. };
  11917. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  11918. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  11919. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  11920. };
  11921. ;
  11922. Engine.prototype.bindIndexBuffer = function (buffer) {
  11923. if (!this._vaoRecordInProgress) {
  11924. this._unbindVertexArrayObject();
  11925. }
  11926. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  11927. };
  11928. Engine.prototype.bindBuffer = function (buffer, target) {
  11929. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  11930. this._gl.bindBuffer(target, buffer);
  11931. this._currentBoundBuffer[target] = buffer;
  11932. }
  11933. };
  11934. Engine.prototype.updateArrayBuffer = function (data) {
  11935. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  11936. };
  11937. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  11938. var pointer = this._currentBufferPointers[indx];
  11939. var changed = false;
  11940. if (!pointer.active) {
  11941. changed = true;
  11942. pointer.active = true;
  11943. pointer.index = indx;
  11944. pointer.size = size;
  11945. pointer.type = type;
  11946. pointer.normalized = normalized;
  11947. pointer.stride = stride;
  11948. pointer.offset = offset;
  11949. pointer.buffer = buffer;
  11950. }
  11951. else {
  11952. if (pointer.buffer !== buffer) {
  11953. pointer.buffer = buffer;
  11954. changed = true;
  11955. }
  11956. if (pointer.size !== size) {
  11957. pointer.size = size;
  11958. changed = true;
  11959. }
  11960. if (pointer.type !== type) {
  11961. pointer.type = type;
  11962. changed = true;
  11963. }
  11964. if (pointer.normalized !== normalized) {
  11965. pointer.normalized = normalized;
  11966. changed = true;
  11967. }
  11968. if (pointer.stride !== stride) {
  11969. pointer.stride = stride;
  11970. changed = true;
  11971. }
  11972. if (pointer.offset !== offset) {
  11973. pointer.offset = offset;
  11974. changed = true;
  11975. }
  11976. }
  11977. if (changed || this._vaoRecordInProgress) {
  11978. this.bindArrayBuffer(buffer);
  11979. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  11980. }
  11981. };
  11982. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  11983. if (indexBuffer == null) {
  11984. return;
  11985. }
  11986. if (this._cachedIndexBuffer !== indexBuffer) {
  11987. this._cachedIndexBuffer = indexBuffer;
  11988. this.bindIndexBuffer(indexBuffer);
  11989. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  11990. }
  11991. };
  11992. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  11993. var attributes = effect.getAttributesNames();
  11994. if (!this._vaoRecordInProgress) {
  11995. this._unbindVertexArrayObject();
  11996. }
  11997. this.unbindAllAttributes();
  11998. for (var index = 0; index < attributes.length; index++) {
  11999. var order = effect.getAttributeLocation(index);
  12000. if (order >= 0) {
  12001. var vertexBuffer = vertexBuffers[attributes[index]];
  12002. if (!vertexBuffer) {
  12003. continue;
  12004. }
  12005. this._gl.enableVertexAttribArray(order);
  12006. if (!this._vaoRecordInProgress) {
  12007. this._vertexAttribArraysEnabled[order] = true;
  12008. }
  12009. var buffer = vertexBuffer.getBuffer();
  12010. if (buffer) {
  12011. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  12012. if (vertexBuffer.getIsInstanced()) {
  12013. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  12014. if (!this._vaoRecordInProgress) {
  12015. this._currentInstanceLocations.push(order);
  12016. this._currentInstanceBuffers.push(buffer);
  12017. }
  12018. }
  12019. }
  12020. }
  12021. }
  12022. };
  12023. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  12024. var vao = this._gl.createVertexArray();
  12025. this._vaoRecordInProgress = true;
  12026. this._gl.bindVertexArray(vao);
  12027. this._mustWipeVertexAttributes = true;
  12028. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  12029. this.bindIndexBuffer(indexBuffer);
  12030. this._vaoRecordInProgress = false;
  12031. this._gl.bindVertexArray(null);
  12032. return vao;
  12033. };
  12034. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  12035. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  12036. this._cachedVertexArrayObject = vertexArrayObject;
  12037. this._gl.bindVertexArray(vertexArrayObject);
  12038. this._cachedVertexBuffers = null;
  12039. this._cachedIndexBuffer = null;
  12040. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  12041. this._mustWipeVertexAttributes = true;
  12042. }
  12043. };
  12044. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  12045. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  12046. this._cachedVertexBuffers = vertexBuffer;
  12047. this._cachedEffectForVertexBuffers = effect;
  12048. var attributesCount = effect.getAttributesCount();
  12049. this._unbindVertexArrayObject();
  12050. this.unbindAllAttributes();
  12051. var offset = 0;
  12052. for (var index = 0; index < attributesCount; index++) {
  12053. if (index < vertexDeclaration.length) {
  12054. var order = effect.getAttributeLocation(index);
  12055. if (order >= 0) {
  12056. this._gl.enableVertexAttribArray(order);
  12057. this._vertexAttribArraysEnabled[order] = true;
  12058. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  12059. }
  12060. offset += vertexDeclaration[index] * 4;
  12061. }
  12062. }
  12063. }
  12064. this._bindIndexBufferWithCache(indexBuffer);
  12065. };
  12066. Engine.prototype._unbindVertexArrayObject = function () {
  12067. if (!this._cachedVertexArrayObject) {
  12068. return;
  12069. }
  12070. this._cachedVertexArrayObject = null;
  12071. this._gl.bindVertexArray(null);
  12072. };
  12073. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  12074. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  12075. this._cachedVertexBuffers = vertexBuffers;
  12076. this._cachedEffectForVertexBuffers = effect;
  12077. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  12078. }
  12079. this._bindIndexBufferWithCache(indexBuffer);
  12080. };
  12081. Engine.prototype.unbindInstanceAttributes = function () {
  12082. var boundBuffer;
  12083. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  12084. var instancesBuffer = this._currentInstanceBuffers[i];
  12085. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  12086. boundBuffer = instancesBuffer;
  12087. this.bindArrayBuffer(instancesBuffer);
  12088. }
  12089. var offsetLocation = this._currentInstanceLocations[i];
  12090. this._gl.vertexAttribDivisor(offsetLocation, 0);
  12091. }
  12092. this._currentInstanceBuffers.length = 0;
  12093. this._currentInstanceLocations.length = 0;
  12094. };
  12095. Engine.prototype.releaseVertexArrayObject = function (vao) {
  12096. this._gl.deleteVertexArray(vao);
  12097. };
  12098. Engine.prototype._releaseBuffer = function (buffer) {
  12099. buffer.references--;
  12100. if (buffer.references === 0) {
  12101. this._gl.deleteBuffer(buffer);
  12102. return true;
  12103. }
  12104. return false;
  12105. };
  12106. Engine.prototype.createInstancesBuffer = function (capacity) {
  12107. var buffer = this._gl.createBuffer();
  12108. if (!buffer) {
  12109. throw new Error("Unable to create instance buffer");
  12110. }
  12111. buffer.capacity = capacity;
  12112. this.bindArrayBuffer(buffer);
  12113. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  12114. return buffer;
  12115. };
  12116. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  12117. this._gl.deleteBuffer(buffer);
  12118. };
  12119. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  12120. this.bindArrayBuffer(instancesBuffer);
  12121. if (data) {
  12122. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  12123. }
  12124. if (offsetLocations[0].index !== undefined) {
  12125. var stride = 0;
  12126. for (var i = 0; i < offsetLocations.length; i++) {
  12127. var ai = offsetLocations[i];
  12128. stride += ai.attributeSize * 4;
  12129. }
  12130. for (var i = 0; i < offsetLocations.length; i++) {
  12131. var ai = offsetLocations[i];
  12132. if (!this._vertexAttribArraysEnabled[ai.index]) {
  12133. this._gl.enableVertexAttribArray(ai.index);
  12134. this._vertexAttribArraysEnabled[ai.index] = true;
  12135. }
  12136. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  12137. this._gl.vertexAttribDivisor(ai.index, 1);
  12138. this._currentInstanceLocations.push(ai.index);
  12139. this._currentInstanceBuffers.push(instancesBuffer);
  12140. }
  12141. }
  12142. else {
  12143. for (var index = 0; index < 4; index++) {
  12144. var offsetLocation = offsetLocations[index];
  12145. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  12146. this._gl.enableVertexAttribArray(offsetLocation);
  12147. this._vertexAttribArraysEnabled[offsetLocation] = true;
  12148. }
  12149. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  12150. this._gl.vertexAttribDivisor(offsetLocation, 1);
  12151. this._currentInstanceLocations.push(offsetLocation);
  12152. this._currentInstanceBuffers.push(instancesBuffer);
  12153. }
  12154. }
  12155. };
  12156. Engine.prototype.applyStates = function () {
  12157. this._depthCullingState.apply(this._gl);
  12158. this._stencilState.apply(this._gl);
  12159. this._alphaState.apply(this._gl);
  12160. };
  12161. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  12162. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  12163. };
  12164. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  12165. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  12166. };
  12167. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  12168. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  12169. };
  12170. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  12171. // Apply states
  12172. this.applyStates();
  12173. this._drawCalls.addCount(1, false);
  12174. // Render
  12175. var drawMode = this.DrawMode(fillMode);
  12176. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  12177. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  12178. if (instancesCount) {
  12179. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  12180. }
  12181. else {
  12182. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  12183. }
  12184. };
  12185. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  12186. // Apply states
  12187. this.applyStates();
  12188. this._drawCalls.addCount(1, false);
  12189. var drawMode = this.DrawMode(fillMode);
  12190. if (instancesCount) {
  12191. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  12192. }
  12193. else {
  12194. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  12195. }
  12196. };
  12197. Engine.prototype.DrawMode = function (fillMode) {
  12198. switch (fillMode) {
  12199. // Triangle views
  12200. case BABYLON.Material.TriangleFillMode:
  12201. return this._gl.TRIANGLES;
  12202. case BABYLON.Material.PointFillMode:
  12203. return this._gl.POINTS;
  12204. case BABYLON.Material.WireFrameFillMode:
  12205. return this._gl.LINES;
  12206. // Draw modes
  12207. case BABYLON.Material.PointListDrawMode:
  12208. return this._gl.POINTS;
  12209. case BABYLON.Material.LineListDrawMode:
  12210. return this._gl.LINES;
  12211. case BABYLON.Material.LineLoopDrawMode:
  12212. return this._gl.LINE_LOOP;
  12213. case BABYLON.Material.LineStripDrawMode:
  12214. return this._gl.LINE_STRIP;
  12215. case BABYLON.Material.TriangleStripDrawMode:
  12216. return this._gl.TRIANGLE_STRIP;
  12217. case BABYLON.Material.TriangleFanDrawMode:
  12218. return this._gl.TRIANGLE_FAN;
  12219. default:
  12220. return this._gl.TRIANGLES;
  12221. }
  12222. };
  12223. // Shaders
  12224. Engine.prototype._releaseEffect = function (effect) {
  12225. if (this._compiledEffects[effect._key]) {
  12226. delete this._compiledEffects[effect._key];
  12227. this._deleteProgram(effect.getProgram());
  12228. }
  12229. };
  12230. Engine.prototype._deleteProgram = function (program) {
  12231. if (program) {
  12232. program.__SPECTOR_rebuildProgram = null;
  12233. if (program.transformFeedback) {
  12234. this.deleteTransformFeedback(program.transformFeedback);
  12235. program.transformFeedback = null;
  12236. }
  12237. this._gl.deleteProgram(program);
  12238. }
  12239. };
  12240. /**
  12241. * @param baseName The base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  12242. * @param samplers An array of string used to represent textures
  12243. */
  12244. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  12245. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  12246. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  12247. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  12248. if (this._compiledEffects[name]) {
  12249. var compiledEffect = this._compiledEffects[name];
  12250. if (onCompiled && compiledEffect.isReady()) {
  12251. onCompiled(compiledEffect);
  12252. }
  12253. return compiledEffect;
  12254. }
  12255. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  12256. effect._key = name;
  12257. this._compiledEffects[name] = effect;
  12258. return effect;
  12259. };
  12260. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  12261. if (uniformsNames === void 0) { uniformsNames = []; }
  12262. if (samplers === void 0) { samplers = []; }
  12263. if (defines === void 0) { defines = ""; }
  12264. return this.createEffect({
  12265. vertex: "particles",
  12266. fragmentElement: fragmentName
  12267. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  12268. };
  12269. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  12270. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12271. context = context || this._gl;
  12272. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  12273. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  12274. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  12275. };
  12276. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  12277. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12278. context = context || this._gl;
  12279. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  12280. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  12281. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  12282. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  12283. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  12284. this.onAfterShaderCompilationObservable.notifyObservers(this);
  12285. return program;
  12286. };
  12287. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  12288. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12289. var shaderProgram = context.createProgram();
  12290. if (!shaderProgram) {
  12291. throw new Error("Unable to create program");
  12292. }
  12293. context.attachShader(shaderProgram, vertexShader);
  12294. context.attachShader(shaderProgram, fragmentShader);
  12295. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  12296. var transformFeedback = this.createTransformFeedback();
  12297. this.bindTransformFeedback(transformFeedback);
  12298. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  12299. shaderProgram.transformFeedback = transformFeedback;
  12300. }
  12301. context.linkProgram(shaderProgram);
  12302. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  12303. this.bindTransformFeedback(null);
  12304. }
  12305. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  12306. if (!linked) {
  12307. context.validateProgram(shaderProgram);
  12308. var error = context.getProgramInfoLog(shaderProgram);
  12309. if (error) {
  12310. throw new Error(error);
  12311. }
  12312. }
  12313. context.deleteShader(vertexShader);
  12314. context.deleteShader(fragmentShader);
  12315. return shaderProgram;
  12316. };
  12317. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  12318. var results = new Array();
  12319. for (var index = 0; index < uniformsNames.length; index++) {
  12320. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  12321. }
  12322. return results;
  12323. };
  12324. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  12325. var results = [];
  12326. for (var index = 0; index < attributesNames.length; index++) {
  12327. try {
  12328. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  12329. }
  12330. catch (e) {
  12331. results.push(-1);
  12332. }
  12333. }
  12334. return results;
  12335. };
  12336. Engine.prototype.enableEffect = function (effect) {
  12337. if (!effect) {
  12338. return;
  12339. }
  12340. // Use program
  12341. this.bindSamplers(effect);
  12342. this._currentEffect = effect;
  12343. if (effect.onBind) {
  12344. effect.onBind(effect);
  12345. }
  12346. effect.onBindObservable.notifyObservers(effect);
  12347. };
  12348. Engine.prototype.setIntArray = function (uniform, array) {
  12349. if (!uniform)
  12350. return;
  12351. this._gl.uniform1iv(uniform, array);
  12352. };
  12353. Engine.prototype.setIntArray2 = function (uniform, array) {
  12354. if (!uniform || array.length % 2 !== 0)
  12355. return;
  12356. this._gl.uniform2iv(uniform, array);
  12357. };
  12358. Engine.prototype.setIntArray3 = function (uniform, array) {
  12359. if (!uniform || array.length % 3 !== 0)
  12360. return;
  12361. this._gl.uniform3iv(uniform, array);
  12362. };
  12363. Engine.prototype.setIntArray4 = function (uniform, array) {
  12364. if (!uniform || array.length % 4 !== 0)
  12365. return;
  12366. this._gl.uniform4iv(uniform, array);
  12367. };
  12368. Engine.prototype.setFloatArray = function (uniform, array) {
  12369. if (!uniform)
  12370. return;
  12371. this._gl.uniform1fv(uniform, array);
  12372. };
  12373. Engine.prototype.setFloatArray2 = function (uniform, array) {
  12374. if (!uniform || array.length % 2 !== 0)
  12375. return;
  12376. this._gl.uniform2fv(uniform, array);
  12377. };
  12378. Engine.prototype.setFloatArray3 = function (uniform, array) {
  12379. if (!uniform || array.length % 3 !== 0)
  12380. return;
  12381. this._gl.uniform3fv(uniform, array);
  12382. };
  12383. Engine.prototype.setFloatArray4 = function (uniform, array) {
  12384. if (!uniform || array.length % 4 !== 0)
  12385. return;
  12386. this._gl.uniform4fv(uniform, array);
  12387. };
  12388. Engine.prototype.setArray = function (uniform, array) {
  12389. if (!uniform)
  12390. return;
  12391. this._gl.uniform1fv(uniform, array);
  12392. };
  12393. Engine.prototype.setArray2 = function (uniform, array) {
  12394. if (!uniform || array.length % 2 !== 0)
  12395. return;
  12396. this._gl.uniform2fv(uniform, array);
  12397. };
  12398. Engine.prototype.setArray3 = function (uniform, array) {
  12399. if (!uniform || array.length % 3 !== 0)
  12400. return;
  12401. this._gl.uniform3fv(uniform, array);
  12402. };
  12403. Engine.prototype.setArray4 = function (uniform, array) {
  12404. if (!uniform || array.length % 4 !== 0)
  12405. return;
  12406. this._gl.uniform4fv(uniform, array);
  12407. };
  12408. Engine.prototype.setMatrices = function (uniform, matrices) {
  12409. if (!uniform)
  12410. return;
  12411. this._gl.uniformMatrix4fv(uniform, false, matrices);
  12412. };
  12413. Engine.prototype.setMatrix = function (uniform, matrix) {
  12414. if (!uniform)
  12415. return;
  12416. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  12417. };
  12418. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  12419. if (!uniform)
  12420. return;
  12421. this._gl.uniformMatrix3fv(uniform, false, matrix);
  12422. };
  12423. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  12424. if (!uniform)
  12425. return;
  12426. this._gl.uniformMatrix2fv(uniform, false, matrix);
  12427. };
  12428. Engine.prototype.setInt = function (uniform, value) {
  12429. if (!uniform)
  12430. return;
  12431. this._gl.uniform1i(uniform, value);
  12432. };
  12433. Engine.prototype.setFloat = function (uniform, value) {
  12434. if (!uniform)
  12435. return;
  12436. this._gl.uniform1f(uniform, value);
  12437. };
  12438. Engine.prototype.setFloat2 = function (uniform, x, y) {
  12439. if (!uniform)
  12440. return;
  12441. this._gl.uniform2f(uniform, x, y);
  12442. };
  12443. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  12444. if (!uniform)
  12445. return;
  12446. this._gl.uniform3f(uniform, x, y, z);
  12447. };
  12448. Engine.prototype.setBool = function (uniform, bool) {
  12449. if (!uniform)
  12450. return;
  12451. this._gl.uniform1i(uniform, bool);
  12452. };
  12453. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  12454. if (!uniform)
  12455. return;
  12456. this._gl.uniform4f(uniform, x, y, z, w);
  12457. };
  12458. Engine.prototype.setColor3 = function (uniform, color3) {
  12459. if (!uniform)
  12460. return;
  12461. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  12462. };
  12463. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  12464. if (!uniform)
  12465. return;
  12466. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  12467. };
  12468. // States
  12469. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  12470. if (zOffset === void 0) { zOffset = 0; }
  12471. if (reverseSide === void 0) { reverseSide = false; }
  12472. // Culling
  12473. if (this._depthCullingState.cull !== culling || force) {
  12474. this._depthCullingState.cull = culling;
  12475. }
  12476. // Cull face
  12477. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  12478. if (this._depthCullingState.cullFace !== cullFace || force) {
  12479. this._depthCullingState.cullFace = cullFace;
  12480. }
  12481. // Z offset
  12482. this.setZOffset(zOffset);
  12483. // Front face
  12484. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  12485. if (this._depthCullingState.frontFace !== frontFace || force) {
  12486. this._depthCullingState.frontFace = frontFace;
  12487. }
  12488. };
  12489. Engine.prototype.setZOffset = function (value) {
  12490. this._depthCullingState.zOffset = value;
  12491. };
  12492. Engine.prototype.getZOffset = function () {
  12493. return this._depthCullingState.zOffset;
  12494. };
  12495. Engine.prototype.setDepthBuffer = function (enable) {
  12496. this._depthCullingState.depthTest = enable;
  12497. };
  12498. Engine.prototype.getDepthWrite = function () {
  12499. return this._depthCullingState.depthMask;
  12500. };
  12501. Engine.prototype.setDepthWrite = function (enable) {
  12502. this._depthCullingState.depthMask = enable;
  12503. };
  12504. Engine.prototype.setColorWrite = function (enable) {
  12505. this._gl.colorMask(enable, enable, enable, enable);
  12506. this._colorWrite = enable;
  12507. };
  12508. Engine.prototype.getColorWrite = function () {
  12509. return this._colorWrite;
  12510. };
  12511. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  12512. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  12513. };
  12514. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  12515. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  12516. if (this._alphaMode === mode) {
  12517. return;
  12518. }
  12519. switch (mode) {
  12520. case Engine.ALPHA_DISABLE:
  12521. this._alphaState.alphaBlend = false;
  12522. break;
  12523. case Engine.ALPHA_PREMULTIPLIED:
  12524. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  12525. this._alphaState.alphaBlend = true;
  12526. break;
  12527. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  12528. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  12529. this._alphaState.alphaBlend = true;
  12530. break;
  12531. case Engine.ALPHA_COMBINE:
  12532. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  12533. this._alphaState.alphaBlend = true;
  12534. break;
  12535. case Engine.ALPHA_ONEONE:
  12536. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  12537. this._alphaState.alphaBlend = true;
  12538. break;
  12539. case Engine.ALPHA_ADD:
  12540. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  12541. this._alphaState.alphaBlend = true;
  12542. break;
  12543. case Engine.ALPHA_SUBTRACT:
  12544. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  12545. this._alphaState.alphaBlend = true;
  12546. break;
  12547. case Engine.ALPHA_MULTIPLY:
  12548. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  12549. this._alphaState.alphaBlend = true;
  12550. break;
  12551. case Engine.ALPHA_MAXIMIZED:
  12552. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  12553. this._alphaState.alphaBlend = true;
  12554. break;
  12555. case Engine.ALPHA_INTERPOLATE:
  12556. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  12557. this._alphaState.alphaBlend = true;
  12558. break;
  12559. case Engine.ALPHA_SCREENMODE:
  12560. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  12561. this._alphaState.alphaBlend = true;
  12562. break;
  12563. }
  12564. if (!noDepthWriteChange) {
  12565. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  12566. }
  12567. this._alphaMode = mode;
  12568. };
  12569. Engine.prototype.getAlphaMode = function () {
  12570. return this._alphaMode;
  12571. };
  12572. // Textures
  12573. Engine.prototype.wipeCaches = function (bruteForce) {
  12574. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  12575. return;
  12576. }
  12577. this._currentEffect = null;
  12578. // 6/8/2017: deltakosh: Should not be required anymore.
  12579. // This message is then mostly for the future myself who will scream out loud when seeing that it was actually required :)
  12580. if (bruteForce) {
  12581. this.resetTextureCache();
  12582. this._currentProgram = null;
  12583. this._stencilState.reset();
  12584. this._depthCullingState.reset();
  12585. this.setDepthFunctionToLessOrEqual();
  12586. this._alphaState.reset();
  12587. }
  12588. this._resetVertexBufferBinding();
  12589. this._cachedIndexBuffer = null;
  12590. this._cachedEffectForVertexBuffers = null;
  12591. this._unbindVertexArrayObject();
  12592. this.bindIndexBuffer(null);
  12593. };
  12594. /**
  12595. * Set the compressed texture format to use, based on the formats you have, and the formats
  12596. * supported by the hardware / browser.
  12597. *
  12598. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  12599. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  12600. * to API arguments needed to compressed textures. This puts the burden on the container
  12601. * generator to house the arcane code for determining these for current & future formats.
  12602. *
  12603. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  12604. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  12605. *
  12606. * Note: The result of this call is not taken into account when a texture is base64.
  12607. *
  12608. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  12609. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  12610. *
  12611. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  12612. * @returns The extension selected.
  12613. */
  12614. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  12615. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  12616. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  12617. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  12618. return this._textureFormatInUse = this._texturesSupported[i];
  12619. }
  12620. }
  12621. }
  12622. // actively set format to nothing, to allow this to be called more than once
  12623. // and possibly fail the 2nd time
  12624. this._textureFormatInUse = null;
  12625. return null;
  12626. };
  12627. Engine.prototype._createTexture = function () {
  12628. var texture = this._gl.createTexture();
  12629. if (!texture) {
  12630. throw new Error("Unable to create texture");
  12631. }
  12632. return texture;
  12633. };
  12634. /**
  12635. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  12636. * @param {string} urlArg- This contains one of the following:
  12637. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  12638. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  12639. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  12640. *
  12641. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  12642. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  12643. * @param {Scene} scene- Needed for loading to the correct scene.
  12644. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  12645. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  12646. * @param {callback} onError- Optional callback to be called upon failure.
  12647. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  12648. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  12649. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  12650. *
  12651. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  12652. */
  12653. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  12654. var _this = this;
  12655. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  12656. if (onLoad === void 0) { onLoad = null; }
  12657. if (onError === void 0) { onError = null; }
  12658. if (buffer === void 0) { buffer = null; }
  12659. if (fallBack === void 0) { fallBack = null; }
  12660. if (format === void 0) { format = null; }
  12661. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  12662. var fromData = url.substr(0, 5) === "data:";
  12663. var fromBlob = url.substr(0, 5) === "blob:";
  12664. var isBase64 = fromData && url.indexOf("base64") !== -1;
  12665. var texture = fallBack ? fallBack : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  12666. // establish the file extension, if possible
  12667. var lastDot = url.lastIndexOf('.');
  12668. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  12669. var isDDS = this.getCaps().s3tc && (extension.indexOf(".dds") === 0);
  12670. var isTGA = (extension.indexOf(".tga") === 0);
  12671. // determine if a ktx file should be substituted
  12672. var isKTX = false;
  12673. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  12674. url = url.substring(0, lastDot) + this._textureFormatInUse;
  12675. isKTX = true;
  12676. }
  12677. if (scene) {
  12678. scene._addPendingData(texture);
  12679. }
  12680. texture.url = url;
  12681. texture.generateMipMaps = !noMipmap;
  12682. texture.samplingMode = samplingMode;
  12683. texture.invertY = invertY;
  12684. if (!this._doNotHandleContextLost) {
  12685. // Keep a link to the buffer only if we plan to handle context lost
  12686. texture._buffer = buffer;
  12687. }
  12688. var onLoadObserver = null;
  12689. if (onLoad && !fallBack) {
  12690. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  12691. }
  12692. if (!fallBack)
  12693. this._internalTexturesCache.push(texture);
  12694. var onerror = function (message, exception) {
  12695. if (scene) {
  12696. scene._removePendingData(texture);
  12697. }
  12698. if (onLoadObserver) {
  12699. texture.onLoadedObservable.remove(onLoadObserver);
  12700. }
  12701. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  12702. if (isKTX) {
  12703. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  12704. }
  12705. else if (BABYLON.Tools.UseFallbackTexture) {
  12706. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  12707. }
  12708. if (onError) {
  12709. onError(message || "Unknown error", exception);
  12710. }
  12711. };
  12712. var callback = null;
  12713. // processing for non-image formats
  12714. if (isKTX || isTGA || isDDS) {
  12715. if (isKTX) {
  12716. callback = function (data) {
  12717. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  12718. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  12719. ktx.uploadLevels(_this._gl, !noMipmap);
  12720. return false;
  12721. }, samplingMode);
  12722. };
  12723. }
  12724. else if (isTGA) {
  12725. callback = function (arrayBuffer) {
  12726. var data = new Uint8Array(arrayBuffer);
  12727. var header = BABYLON.TGATools.GetTGAHeader(data);
  12728. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  12729. BABYLON.TGATools.UploadContent(_this._gl, data);
  12730. return false;
  12731. }, samplingMode);
  12732. };
  12733. }
  12734. else if (isDDS) {
  12735. callback = function (data) {
  12736. var info = BABYLON.DDSTools.GetDDSInfo(data);
  12737. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  12738. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  12739. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  12740. return false;
  12741. }, samplingMode);
  12742. };
  12743. }
  12744. if (!buffer) {
  12745. this._loadFile(url, function (data) {
  12746. if (callback) {
  12747. callback(data);
  12748. }
  12749. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  12750. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  12751. });
  12752. }
  12753. else {
  12754. if (callback) {
  12755. callback(buffer);
  12756. }
  12757. }
  12758. // image format processing
  12759. }
  12760. else {
  12761. var onload = function (img) {
  12762. if (fromBlob && !_this._doNotHandleContextLost) {
  12763. // We need to store the image if we need to rebuild the texture
  12764. // in case of a webgl context lost
  12765. texture._buffer = img;
  12766. }
  12767. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  12768. var gl = _this._gl;
  12769. var isPot = (img.width === potWidth && img.height === potHeight);
  12770. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  12771. if (isPot) {
  12772. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  12773. return false;
  12774. }
  12775. // Using shaders to rescale because canvas.drawImage is lossy
  12776. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  12777. _this._bindTextureDirectly(gl.TEXTURE_2D, source, true);
  12778. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  12779. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  12780. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  12781. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12782. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12783. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  12784. _this._releaseTexture(source);
  12785. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  12786. continuationCallback();
  12787. });
  12788. return true;
  12789. }, samplingMode);
  12790. };
  12791. if (!fromData || isBase64)
  12792. if (buffer instanceof HTMLImageElement) {
  12793. onload(buffer);
  12794. }
  12795. else {
  12796. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  12797. }
  12798. else if (buffer instanceof Array || typeof buffer === "string" || buffer instanceof ArrayBuffer)
  12799. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  12800. else
  12801. onload(buffer);
  12802. }
  12803. return texture;
  12804. };
  12805. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  12806. var _this = this;
  12807. var rtt = this.createRenderTargetTexture({
  12808. width: destination.width,
  12809. height: destination.height,
  12810. }, {
  12811. generateMipMaps: false,
  12812. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  12813. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  12814. generateDepthBuffer: false,
  12815. generateStencilBuffer: false
  12816. });
  12817. if (!this._rescalePostProcess) {
  12818. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  12819. }
  12820. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  12821. _this._rescalePostProcess.onApply = function (effect) {
  12822. effect._bindTexture("textureSampler", source);
  12823. };
  12824. var hostingScene = scene;
  12825. if (!hostingScene) {
  12826. hostingScene = _this.scenes[_this.scenes.length - 1];
  12827. }
  12828. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  12829. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  12830. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  12831. _this.unBindFramebuffer(rtt);
  12832. _this._releaseTexture(rtt);
  12833. if (onComplete) {
  12834. onComplete();
  12835. }
  12836. });
  12837. };
  12838. Engine.prototype._getInternalFormat = function (format) {
  12839. var internalFormat = this._gl.RGBA;
  12840. switch (format) {
  12841. case Engine.TEXTUREFORMAT_ALPHA:
  12842. internalFormat = this._gl.ALPHA;
  12843. break;
  12844. case Engine.TEXTUREFORMAT_LUMINANCE:
  12845. internalFormat = this._gl.LUMINANCE;
  12846. break;
  12847. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  12848. internalFormat = this._gl.LUMINANCE_ALPHA;
  12849. break;
  12850. case Engine.TEXTUREFORMAT_RGB:
  12851. internalFormat = this._gl.RGB;
  12852. break;
  12853. case Engine.TEXTUREFORMAT_RGBA:
  12854. internalFormat = this._gl.RGBA;
  12855. break;
  12856. }
  12857. return internalFormat;
  12858. };
  12859. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  12860. if (compression === void 0) { compression = null; }
  12861. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  12862. if (!texture) {
  12863. return;
  12864. }
  12865. var internalFormat = this._getInternalFormat(format);
  12866. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  12867. var textureType = this._getWebGLTextureType(type);
  12868. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  12869. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  12870. if (!this._doNotHandleContextLost) {
  12871. texture._bufferView = data;
  12872. texture.format = format;
  12873. texture.type = type;
  12874. texture.invertY = invertY;
  12875. texture._compression = compression;
  12876. }
  12877. if (texture.width % 4 !== 0) {
  12878. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  12879. }
  12880. if (compression && data) {
  12881. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  12882. }
  12883. else {
  12884. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  12885. }
  12886. if (texture.generateMipMaps) {
  12887. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  12888. }
  12889. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  12890. // this.resetTextureCache();
  12891. texture.isReady = true;
  12892. };
  12893. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  12894. if (compression === void 0) { compression = null; }
  12895. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  12896. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  12897. texture.baseWidth = width;
  12898. texture.baseHeight = height;
  12899. texture.width = width;
  12900. texture.height = height;
  12901. texture.format = format;
  12902. texture.generateMipMaps = generateMipMaps;
  12903. texture.samplingMode = samplingMode;
  12904. texture.invertY = invertY;
  12905. texture._compression = compression;
  12906. texture.type = type;
  12907. if (!this._doNotHandleContextLost) {
  12908. texture._bufferView = data;
  12909. }
  12910. this.updateRawTexture(texture, data, format, invertY, compression, type);
  12911. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  12912. // Filters
  12913. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  12914. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  12915. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  12916. if (generateMipMaps) {
  12917. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  12918. }
  12919. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  12920. this._internalTexturesCache.push(texture);
  12921. return texture;
  12922. };
  12923. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  12924. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  12925. texture.baseWidth = width;
  12926. texture.baseHeight = height;
  12927. if (generateMipMaps) {
  12928. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  12929. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  12930. }
  12931. // this.resetTextureCache();
  12932. texture.width = width;
  12933. texture.height = height;
  12934. texture.isReady = false;
  12935. texture.generateMipMaps = generateMipMaps;
  12936. texture.samplingMode = samplingMode;
  12937. this.updateTextureSamplingMode(samplingMode, texture);
  12938. this._internalTexturesCache.push(texture);
  12939. return texture;
  12940. };
  12941. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  12942. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  12943. if (texture.isCube) {
  12944. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  12945. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  12946. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  12947. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  12948. }
  12949. else if (texture.is3D) {
  12950. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  12951. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  12952. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  12953. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  12954. }
  12955. else {
  12956. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  12957. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  12958. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  12959. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  12960. }
  12961. texture.samplingMode = samplingMode;
  12962. };
  12963. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  12964. if (premulAlpha === void 0) { premulAlpha = false; }
  12965. if (!texture) {
  12966. return;
  12967. }
  12968. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  12969. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  12970. if (premulAlpha) {
  12971. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  12972. }
  12973. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  12974. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  12975. if (texture.generateMipMaps) {
  12976. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  12977. }
  12978. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  12979. if (premulAlpha) {
  12980. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  12981. }
  12982. texture.isReady = true;
  12983. };
  12984. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  12985. if (!texture || texture._isDisabled) {
  12986. return;
  12987. }
  12988. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  12989. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  12990. try {
  12991. // Testing video texture support
  12992. if (this._videoTextureSupported === undefined) {
  12993. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  12994. if (this._gl.getError() !== 0) {
  12995. this._videoTextureSupported = false;
  12996. }
  12997. else {
  12998. this._videoTextureSupported = true;
  12999. }
  13000. }
  13001. // Copy video through the current working canvas if video texture is not supported
  13002. if (!this._videoTextureSupported) {
  13003. if (!texture._workingCanvas) {
  13004. texture._workingCanvas = document.createElement("canvas");
  13005. var context = texture._workingCanvas.getContext("2d");
  13006. if (!context) {
  13007. throw new Error("Unable to get 2d context");
  13008. }
  13009. texture._workingContext = context;
  13010. texture._workingCanvas.width = texture.width;
  13011. texture._workingCanvas.height = texture.height;
  13012. }
  13013. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  13014. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  13015. }
  13016. else {
  13017. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  13018. }
  13019. if (texture.generateMipMaps) {
  13020. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13021. }
  13022. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13023. // this.resetTextureCache();
  13024. texture.isReady = true;
  13025. }
  13026. catch (ex) {
  13027. // Something unexpected
  13028. // Let's disable the texture
  13029. texture._isDisabled = true;
  13030. }
  13031. };
  13032. Engine.prototype.createRenderTargetTexture = function (size, options) {
  13033. var fullOptions = new RenderTargetCreationOptions();
  13034. if (options !== undefined && typeof options === "object") {
  13035. fullOptions.generateMipMaps = options.generateMipMaps;
  13036. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  13037. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  13038. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  13039. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  13040. }
  13041. else {
  13042. fullOptions.generateMipMaps = options;
  13043. fullOptions.generateDepthBuffer = true;
  13044. fullOptions.generateStencilBuffer = false;
  13045. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13046. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  13047. }
  13048. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  13049. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  13050. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13051. }
  13052. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  13053. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  13054. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13055. }
  13056. var gl = this._gl;
  13057. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  13058. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13059. var width = size.width || size;
  13060. var height = size.height || size;
  13061. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  13062. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  13063. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13064. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  13065. }
  13066. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  13067. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  13068. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13069. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13070. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type), width, height, 0, gl.RGBA, this._getWebGLTextureType(fullOptions.type), null);
  13071. // Create the framebuffer
  13072. var framebuffer = gl.createFramebuffer();
  13073. this.bindUnboundFramebuffer(framebuffer);
  13074. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  13075. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  13076. if (fullOptions.generateMipMaps) {
  13077. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13078. }
  13079. // Unbind
  13080. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13081. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13082. this.bindUnboundFramebuffer(null);
  13083. texture._framebuffer = framebuffer;
  13084. texture.baseWidth = width;
  13085. texture.baseHeight = height;
  13086. texture.width = width;
  13087. texture.height = height;
  13088. texture.isReady = true;
  13089. texture.samples = 1;
  13090. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  13091. texture.samplingMode = fullOptions.samplingMode;
  13092. texture.type = fullOptions.type;
  13093. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  13094. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  13095. // this.resetTextureCache();
  13096. this._internalTexturesCache.push(texture);
  13097. return texture;
  13098. };
  13099. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  13100. var generateMipMaps = false;
  13101. var generateDepthBuffer = true;
  13102. var generateStencilBuffer = false;
  13103. var generateDepthTexture = false;
  13104. var textureCount = 1;
  13105. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  13106. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  13107. var types = [], samplingModes = [];
  13108. if (options !== undefined) {
  13109. generateMipMaps = options.generateMipMaps;
  13110. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  13111. generateStencilBuffer = options.generateStencilBuffer;
  13112. generateDepthTexture = options.generateDepthTexture;
  13113. textureCount = options.textureCount || 1;
  13114. if (options.types) {
  13115. types = options.types;
  13116. }
  13117. if (options.samplingModes) {
  13118. samplingModes = options.samplingModes;
  13119. }
  13120. }
  13121. var gl = this._gl;
  13122. // Create the framebuffer
  13123. var framebuffer = gl.createFramebuffer();
  13124. this.bindUnboundFramebuffer(framebuffer);
  13125. var width = size.width || size;
  13126. var height = size.height || size;
  13127. var textures = [];
  13128. var attachments = [];
  13129. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  13130. for (var i = 0; i < textureCount; i++) {
  13131. var samplingMode = samplingModes[i] || defaultSamplingMode;
  13132. var type = types[i] || defaultType;
  13133. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  13134. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  13135. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13136. }
  13137. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  13138. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  13139. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13140. }
  13141. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  13142. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  13143. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13144. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  13145. }
  13146. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  13147. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13148. textures.push(texture);
  13149. attachments.push(attachment);
  13150. gl.activeTexture(gl["TEXTURE" + i]);
  13151. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  13152. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  13153. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  13154. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13155. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13156. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  13157. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  13158. if (generateMipMaps) {
  13159. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13160. }
  13161. // Unbind
  13162. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13163. texture._framebuffer = framebuffer;
  13164. texture._depthStencilBuffer = depthStencilBuffer;
  13165. texture.baseWidth = width;
  13166. texture.baseHeight = height;
  13167. texture.width = width;
  13168. texture.height = height;
  13169. texture.isReady = true;
  13170. texture.samples = 1;
  13171. texture.generateMipMaps = generateMipMaps;
  13172. texture.samplingMode = samplingMode;
  13173. texture.type = type;
  13174. texture._generateDepthBuffer = generateDepthBuffer;
  13175. texture._generateStencilBuffer = generateStencilBuffer;
  13176. texture._attachments = attachments;
  13177. this._internalTexturesCache.push(texture);
  13178. }
  13179. if (generateDepthTexture && this._caps.depthTextureExtension) {
  13180. // Depth texture
  13181. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  13182. gl.activeTexture(gl.TEXTURE0);
  13183. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  13184. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  13185. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  13186. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13187. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13188. 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);
  13189. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  13190. depthTexture._framebuffer = framebuffer;
  13191. depthTexture.baseWidth = width;
  13192. depthTexture.baseHeight = height;
  13193. depthTexture.width = width;
  13194. depthTexture.height = height;
  13195. depthTexture.isReady = true;
  13196. depthTexture.samples = 1;
  13197. depthTexture.generateMipMaps = generateMipMaps;
  13198. depthTexture.samplingMode = gl.NEAREST;
  13199. depthTexture._generateDepthBuffer = generateDepthBuffer;
  13200. depthTexture._generateStencilBuffer = generateStencilBuffer;
  13201. textures.push(depthTexture);
  13202. this._internalTexturesCache.push(depthTexture);
  13203. }
  13204. gl.drawBuffers(attachments);
  13205. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13206. this.bindUnboundFramebuffer(null);
  13207. this.resetTextureCache();
  13208. return textures;
  13209. };
  13210. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  13211. if (samples === void 0) { samples = 1; }
  13212. var depthStencilBuffer = null;
  13213. var gl = this._gl;
  13214. // Create the depth/stencil buffer
  13215. if (generateStencilBuffer) {
  13216. depthStencilBuffer = gl.createRenderbuffer();
  13217. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  13218. if (samples > 1) {
  13219. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  13220. }
  13221. else {
  13222. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  13223. }
  13224. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  13225. }
  13226. else if (generateDepthBuffer) {
  13227. depthStencilBuffer = gl.createRenderbuffer();
  13228. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  13229. if (samples > 1) {
  13230. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  13231. }
  13232. else {
  13233. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  13234. }
  13235. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  13236. }
  13237. return depthStencilBuffer;
  13238. };
  13239. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  13240. if (this.webGLVersion < 2 || !texture) {
  13241. return 1;
  13242. }
  13243. if (texture.samples === samples) {
  13244. return samples;
  13245. }
  13246. var gl = this._gl;
  13247. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  13248. // Dispose previous render buffers
  13249. if (texture._depthStencilBuffer) {
  13250. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  13251. texture._depthStencilBuffer = null;
  13252. }
  13253. if (texture._MSAAFramebuffer) {
  13254. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  13255. texture._MSAAFramebuffer = null;
  13256. }
  13257. if (texture._MSAARenderBuffer) {
  13258. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  13259. texture._MSAARenderBuffer = null;
  13260. }
  13261. if (samples > 1) {
  13262. var framebuffer = gl.createFramebuffer();
  13263. if (!framebuffer) {
  13264. throw new Error("Unable to create multi sampled framebuffer");
  13265. }
  13266. texture._MSAAFramebuffer = framebuffer;
  13267. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  13268. var colorRenderbuffer = gl.createRenderbuffer();
  13269. if (!colorRenderbuffer) {
  13270. throw new Error("Unable to create multi sampled framebuffer");
  13271. }
  13272. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  13273. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  13274. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  13275. texture._MSAARenderBuffer = colorRenderbuffer;
  13276. }
  13277. else {
  13278. this.bindUnboundFramebuffer(texture._framebuffer);
  13279. }
  13280. texture.samples = samples;
  13281. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  13282. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13283. this.bindUnboundFramebuffer(null);
  13284. return samples;
  13285. };
  13286. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  13287. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  13288. return 1;
  13289. }
  13290. if (textures[0].samples === samples) {
  13291. return samples;
  13292. }
  13293. var gl = this._gl;
  13294. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  13295. // Dispose previous render buffers
  13296. if (textures[0]._depthStencilBuffer) {
  13297. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  13298. textures[0]._depthStencilBuffer = null;
  13299. }
  13300. if (textures[0]._MSAAFramebuffer) {
  13301. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  13302. textures[0]._MSAAFramebuffer = null;
  13303. }
  13304. for (var i = 0; i < textures.length; i++) {
  13305. if (textures[i]._MSAARenderBuffer) {
  13306. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  13307. textures[i]._MSAARenderBuffer = null;
  13308. }
  13309. }
  13310. if (samples > 1) {
  13311. var framebuffer = gl.createFramebuffer();
  13312. if (!framebuffer) {
  13313. throw new Error("Unable to create multi sampled framebuffer");
  13314. }
  13315. this.bindUnboundFramebuffer(framebuffer);
  13316. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  13317. var attachments = [];
  13318. for (var i = 0; i < textures.length; i++) {
  13319. var texture = textures[i];
  13320. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13321. var colorRenderbuffer = gl.createRenderbuffer();
  13322. if (!colorRenderbuffer) {
  13323. throw new Error("Unable to create multi sampled framebuffer");
  13324. }
  13325. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  13326. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  13327. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  13328. texture._MSAAFramebuffer = framebuffer;
  13329. texture._MSAARenderBuffer = colorRenderbuffer;
  13330. texture.samples = samples;
  13331. texture._depthStencilBuffer = depthStencilBuffer;
  13332. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13333. attachments.push(attachment);
  13334. }
  13335. gl.drawBuffers(attachments);
  13336. }
  13337. else {
  13338. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  13339. }
  13340. this.bindUnboundFramebuffer(null);
  13341. return samples;
  13342. };
  13343. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  13344. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  13345. };
  13346. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  13347. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  13348. };
  13349. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  13350. var gl = this._gl;
  13351. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  13352. var generateMipMaps = true;
  13353. var generateDepthBuffer = true;
  13354. var generateStencilBuffer = false;
  13355. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  13356. if (options !== undefined) {
  13357. generateMipMaps = options.generateMipMaps === undefined ? true : options.generateMipMaps;
  13358. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  13359. generateStencilBuffer = (generateDepthBuffer && options.generateStencilBuffer) ? true : false;
  13360. if (options.samplingMode !== undefined) {
  13361. samplingMode = options.samplingMode;
  13362. }
  13363. }
  13364. texture.isCube = true;
  13365. texture.generateMipMaps = generateMipMaps;
  13366. texture.samples = 1;
  13367. texture.samplingMode = samplingMode;
  13368. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  13369. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13370. for (var face = 0; face < 6; face++) {
  13371. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  13372. }
  13373. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  13374. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  13375. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13376. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13377. // Create the framebuffer
  13378. var framebuffer = gl.createFramebuffer();
  13379. this.bindUnboundFramebuffer(framebuffer);
  13380. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, size, size);
  13381. // Mipmaps
  13382. if (texture.generateMipMaps) {
  13383. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13384. }
  13385. // Unbind
  13386. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13387. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13388. this.bindUnboundFramebuffer(null);
  13389. texture._framebuffer = framebuffer;
  13390. texture.width = size;
  13391. texture.height = size;
  13392. texture.isReady = true;
  13393. //this.resetTextureCache();
  13394. this._internalTexturesCache.push(texture);
  13395. return texture;
  13396. };
  13397. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  13398. var _this = this;
  13399. if (onLoad === void 0) { onLoad = null; }
  13400. if (onError === void 0) { onError = null; }
  13401. if (forcedExtension === void 0) { forcedExtension = null; }
  13402. var callback = function (loadData) {
  13403. if (!loadData) {
  13404. if (onLoad) {
  13405. onLoad(null);
  13406. }
  13407. return;
  13408. }
  13409. var texture = loadData.texture;
  13410. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  13411. texture._lodGenerationScale = scale;
  13412. texture._lodGenerationOffset = offset;
  13413. if (_this._caps.textureLOD) {
  13414. // Do not add extra process if texture lod is supported.
  13415. if (onLoad) {
  13416. onLoad(texture);
  13417. }
  13418. return;
  13419. }
  13420. var mipSlices = 3;
  13421. var gl = _this._gl;
  13422. var width = loadData.width;
  13423. if (!width) {
  13424. return;
  13425. }
  13426. var textures = [];
  13427. for (var i = 0; i < mipSlices; i++) {
  13428. //compute LOD from even spacing in smoothness (matching shader calculation)
  13429. var smoothness = i / (mipSlices - 1);
  13430. var roughness = 1 - smoothness;
  13431. var minLODIndex = offset; // roughness = 0
  13432. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  13433. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  13434. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  13435. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  13436. glTextureFromLod.isCube = true;
  13437. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  13438. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  13439. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  13440. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13441. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13442. if (loadData.isDDS) {
  13443. var info = loadData.info;
  13444. var data = loadData.data;
  13445. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  13446. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  13447. }
  13448. else {
  13449. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  13450. }
  13451. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13452. // Wrap in a base texture for easy binding.
  13453. var lodTexture = new BABYLON.BaseTexture(scene);
  13454. lodTexture.isCube = true;
  13455. lodTexture._texture = glTextureFromLod;
  13456. glTextureFromLod.isReady = true;
  13457. textures.push(lodTexture);
  13458. }
  13459. texture._lodTextureHigh = textures[2];
  13460. texture._lodTextureMid = textures[1];
  13461. texture._lodTextureLow = textures[0];
  13462. if (onLoad) {
  13463. onLoad(texture);
  13464. }
  13465. };
  13466. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension);
  13467. };
  13468. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension) {
  13469. var _this = this;
  13470. if (onLoad === void 0) { onLoad = null; }
  13471. if (onError === void 0) { onError = null; }
  13472. if (forcedExtension === void 0) { forcedExtension = null; }
  13473. var gl = this._gl;
  13474. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  13475. texture.isCube = true;
  13476. texture.url = rootUrl;
  13477. texture.generateMipMaps = !noMipmap;
  13478. if (!this._doNotHandleContextLost) {
  13479. texture._extension = forcedExtension;
  13480. texture._files = files;
  13481. }
  13482. var isKTX = false;
  13483. var isDDS = false;
  13484. var lastDot = rootUrl.lastIndexOf('.');
  13485. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  13486. if (this._textureFormatInUse) {
  13487. extension = this._textureFormatInUse;
  13488. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  13489. isKTX = true;
  13490. }
  13491. else {
  13492. isDDS = (extension === ".dds");
  13493. }
  13494. var onerror = function (request, exception) {
  13495. if (onError && request) {
  13496. onError(request.status + " " + request.statusText, exception);
  13497. }
  13498. };
  13499. if (isKTX) {
  13500. this._loadFile(rootUrl, function (data) {
  13501. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  13502. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  13503. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13504. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  13505. ktx.uploadLevels(_this._gl, !noMipmap);
  13506. _this.setCubeMapTextureParams(gl, loadMipmap);
  13507. texture.width = ktx.pixelWidth;
  13508. texture.height = ktx.pixelHeight;
  13509. texture.isReady = true;
  13510. }, undefined, undefined, true, onerror);
  13511. }
  13512. else if (isDDS) {
  13513. if (files && files.length === 6) {
  13514. this._cascadeLoadFiles(rootUrl, scene, function (imgs) {
  13515. var info;
  13516. var loadMipmap = false;
  13517. var width = 0;
  13518. for (var index = 0; index < imgs.length; index++) {
  13519. var data = imgs[index];
  13520. info = BABYLON.DDSTools.GetDDSInfo(data);
  13521. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  13522. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13523. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  13524. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  13525. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  13526. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13527. }
  13528. texture.width = info.width;
  13529. texture.height = info.height;
  13530. texture.type = info.textureType;
  13531. width = info.width;
  13532. }
  13533. _this.setCubeMapTextureParams(gl, loadMipmap);
  13534. texture.isReady = true;
  13535. if (onLoad) {
  13536. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  13537. }
  13538. }, files, onError);
  13539. }
  13540. else {
  13541. this._loadFile(rootUrl, function (data) {
  13542. var info = BABYLON.DDSTools.GetDDSInfo(data);
  13543. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  13544. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13545. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  13546. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  13547. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  13548. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13549. }
  13550. _this.setCubeMapTextureParams(gl, loadMipmap);
  13551. texture.width = info.width;
  13552. texture.height = info.height;
  13553. texture.isReady = true;
  13554. texture.type = info.textureType;
  13555. if (onLoad) {
  13556. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  13557. }
  13558. }, undefined, undefined, true, onerror);
  13559. }
  13560. }
  13561. else {
  13562. if (!files) {
  13563. throw new Error("Cannot load cubemap because files were not defined");
  13564. }
  13565. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  13566. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  13567. var height = width;
  13568. _this._prepareWorkingCanvas();
  13569. if (!_this._workingCanvas || !_this._workingContext) {
  13570. return;
  13571. }
  13572. _this._workingCanvas.width = width;
  13573. _this._workingCanvas.height = height;
  13574. var faces = [
  13575. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  13576. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  13577. ];
  13578. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13579. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  13580. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  13581. for (var index = 0; index < faces.length; index++) {
  13582. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  13583. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  13584. }
  13585. if (!noMipmap) {
  13586. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13587. }
  13588. _this.setCubeMapTextureParams(gl, !noMipmap);
  13589. texture.width = width;
  13590. texture.height = height;
  13591. texture.isReady = true;
  13592. if (format) {
  13593. texture.format = format;
  13594. }
  13595. texture.onLoadedObservable.notifyObservers(texture);
  13596. texture.onLoadedObservable.clear();
  13597. if (onLoad) {
  13598. onLoad();
  13599. }
  13600. }, files, onError);
  13601. }
  13602. this._internalTexturesCache.push(texture);
  13603. return texture;
  13604. };
  13605. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  13606. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  13607. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  13608. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13609. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13610. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13611. // this.resetTextureCache();
  13612. };
  13613. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  13614. if (compression === void 0) { compression = null; }
  13615. if (level === void 0) { level = 0; }
  13616. texture._bufferViewArray = data;
  13617. texture.format = format;
  13618. texture.type = type;
  13619. texture.invertY = invertY;
  13620. texture._compression = compression;
  13621. var gl = this._gl;
  13622. var textureType = this._getWebGLTextureType(type);
  13623. var internalFormat = this._getInternalFormat(format);
  13624. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  13625. var needConversion = false;
  13626. if (internalFormat === gl.RGB) {
  13627. internalFormat = gl.RGBA;
  13628. needConversion = true;
  13629. }
  13630. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13631. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  13632. if (texture.width % 4 !== 0) {
  13633. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  13634. }
  13635. // Data are known to be in +X +Y +Z -X -Y -Z
  13636. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  13637. var faceData = data[faceIndex];
  13638. if (compression) {
  13639. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  13640. }
  13641. else {
  13642. if (needConversion) {
  13643. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  13644. }
  13645. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  13646. }
  13647. }
  13648. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  13649. if (isPot && texture.generateMipMaps && level === 0) {
  13650. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  13651. }
  13652. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  13653. // this.resetTextureCache();
  13654. texture.isReady = true;
  13655. };
  13656. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  13657. if (compression === void 0) { compression = null; }
  13658. var gl = this._gl;
  13659. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  13660. texture.isCube = true;
  13661. texture.generateMipMaps = generateMipMaps;
  13662. texture.format = format;
  13663. texture.type = type;
  13664. if (!this._doNotHandleContextLost) {
  13665. texture._bufferViewArray = data;
  13666. }
  13667. var textureType = this._getWebGLTextureType(type);
  13668. var internalFormat = this._getInternalFormat(format);
  13669. if (internalFormat === gl.RGB) {
  13670. internalFormat = gl.RGBA;
  13671. }
  13672. var width = size;
  13673. var height = width;
  13674. texture.width = width;
  13675. texture.height = height;
  13676. // Double check on POT to generate Mips.
  13677. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  13678. if (!isPot) {
  13679. generateMipMaps = false;
  13680. }
  13681. // Upload data if needed. The texture won't be ready until then.
  13682. if (data) {
  13683. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  13684. }
  13685. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  13686. // Filters
  13687. if (data && generateMipMaps) {
  13688. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  13689. }
  13690. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  13691. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  13692. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  13693. }
  13694. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  13695. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  13696. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  13697. }
  13698. else {
  13699. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  13700. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  13701. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  13702. }
  13703. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13704. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13705. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13706. return texture;
  13707. };
  13708. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError, samplingMode, invertY) {
  13709. var _this = this;
  13710. if (onLoad === void 0) { onLoad = null; }
  13711. if (onError === void 0) { onError = null; }
  13712. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  13713. if (invertY === void 0) { invertY = false; }
  13714. var gl = this._gl;
  13715. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  13716. scene._addPendingData(texture);
  13717. texture.url = url;
  13718. this._internalTexturesCache.push(texture);
  13719. var onerror = function (request, exception) {
  13720. scene._removePendingData(texture);
  13721. if (onError && request) {
  13722. onError(request.status + " " + request.statusText, exception);
  13723. }
  13724. };
  13725. var internalCallback = function (data) {
  13726. var width = texture.width;
  13727. var faceDataArrays = callback(data);
  13728. if (!faceDataArrays) {
  13729. return;
  13730. }
  13731. if (mipmmapGenerator) {
  13732. var textureType = _this._getWebGLTextureType(type);
  13733. var internalFormat = _this._getInternalFormat(format);
  13734. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  13735. var needConversion = false;
  13736. if (internalFormat === gl.RGB) {
  13737. internalFormat = gl.RGBA;
  13738. needConversion = true;
  13739. }
  13740. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13741. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  13742. var mipData = mipmmapGenerator(faceDataArrays);
  13743. for (var level = 0; level < mipData.length; level++) {
  13744. var mipSize = width >> level;
  13745. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  13746. var mipFaceData = mipData[level][faceIndex];
  13747. if (needConversion) {
  13748. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  13749. }
  13750. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  13751. }
  13752. }
  13753. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13754. }
  13755. else {
  13756. texture.generateMipMaps = !noMipmap;
  13757. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  13758. }
  13759. texture.isReady = true;
  13760. // this.resetTextureCache();
  13761. scene._removePendingData(texture);
  13762. if (onLoad) {
  13763. onLoad();
  13764. }
  13765. };
  13766. this._loadFile(url, function (data) {
  13767. internalCallback(data);
  13768. }, undefined, scene.database, true, onerror);
  13769. return texture;
  13770. };
  13771. ;
  13772. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression) {
  13773. if (compression === void 0) { compression = null; }
  13774. var internalFormat = this._getInternalFormat(format);
  13775. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  13776. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  13777. if (!this._doNotHandleContextLost) {
  13778. texture._bufferView = data;
  13779. texture.format = format;
  13780. texture.invertY = invertY;
  13781. texture._compression = compression;
  13782. }
  13783. if (texture.width % 4 !== 0) {
  13784. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  13785. }
  13786. if (compression && data) {
  13787. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  13788. }
  13789. else {
  13790. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalFormat, texture.width, texture.height, texture.depth, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  13791. }
  13792. if (texture.generateMipMaps) {
  13793. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  13794. }
  13795. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  13796. // this.resetTextureCache();
  13797. texture.isReady = true;
  13798. };
  13799. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression) {
  13800. if (compression === void 0) { compression = null; }
  13801. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  13802. texture.baseWidth = width;
  13803. texture.baseHeight = height;
  13804. texture.baseDepth = depth;
  13805. texture.width = width;
  13806. texture.height = height;
  13807. texture.depth = depth;
  13808. texture.format = format;
  13809. texture.generateMipMaps = generateMipMaps;
  13810. texture.samplingMode = samplingMode;
  13811. texture.is3D = true;
  13812. if (!this._doNotHandleContextLost) {
  13813. texture._bufferView = data;
  13814. }
  13815. this.updateRawTexture3D(texture, data, format, invertY, compression);
  13816. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  13817. // Filters
  13818. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  13819. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13820. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13821. if (generateMipMaps) {
  13822. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  13823. }
  13824. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  13825. this._internalTexturesCache.push(texture);
  13826. return texture;
  13827. };
  13828. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  13829. var gl = this._gl;
  13830. if (!gl) {
  13831. return;
  13832. }
  13833. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  13834. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  13835. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  13836. if (!noMipmap && !isCompressed) {
  13837. gl.generateMipmap(gl.TEXTURE_2D);
  13838. }
  13839. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13840. // this.resetTextureCache();
  13841. if (scene) {
  13842. scene._removePendingData(texture);
  13843. }
  13844. texture.onLoadedObservable.notifyObservers(texture);
  13845. texture.onLoadedObservable.clear();
  13846. };
  13847. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  13848. var _this = this;
  13849. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  13850. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  13851. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  13852. var gl = this._gl;
  13853. if (!gl) {
  13854. return;
  13855. }
  13856. if (!texture._webGLTexture) {
  13857. // this.resetTextureCache();
  13858. if (scene) {
  13859. scene._removePendingData(texture);
  13860. }
  13861. return;
  13862. }
  13863. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13864. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  13865. texture.baseWidth = width;
  13866. texture.baseHeight = height;
  13867. texture.width = potWidth;
  13868. texture.height = potHeight;
  13869. texture.isReady = true;
  13870. if (processFunction(potWidth, potHeight, function () {
  13871. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  13872. })) {
  13873. // Returning as texture needs extra async steps
  13874. return;
  13875. }
  13876. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  13877. };
  13878. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  13879. // Create new RGBA data container.
  13880. var rgbaData;
  13881. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  13882. rgbaData = new Float32Array(width * height * 4);
  13883. }
  13884. else {
  13885. rgbaData = new Uint32Array(width * height * 4);
  13886. }
  13887. // Convert each pixel.
  13888. for (var x = 0; x < width; x++) {
  13889. for (var y = 0; y < height; y++) {
  13890. var index = (y * width + x) * 3;
  13891. var newIndex = (y * width + x) * 4;
  13892. // Map Old Value to new value.
  13893. rgbaData[newIndex + 0] = rgbData[index + 0];
  13894. rgbaData[newIndex + 1] = rgbData[index + 1];
  13895. rgbaData[newIndex + 2] = rgbData[index + 2];
  13896. // Add fully opaque alpha channel.
  13897. rgbaData[newIndex + 3] = 1;
  13898. }
  13899. }
  13900. return rgbaData;
  13901. };
  13902. Engine.prototype._releaseFramebufferObjects = function (texture) {
  13903. var gl = this._gl;
  13904. if (texture._framebuffer) {
  13905. gl.deleteFramebuffer(texture._framebuffer);
  13906. texture._framebuffer = null;
  13907. }
  13908. if (texture._depthStencilBuffer) {
  13909. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  13910. texture._depthStencilBuffer = null;
  13911. }
  13912. if (texture._MSAAFramebuffer) {
  13913. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  13914. texture._MSAAFramebuffer = null;
  13915. }
  13916. if (texture._MSAARenderBuffer) {
  13917. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  13918. texture._MSAARenderBuffer = null;
  13919. }
  13920. };
  13921. Engine.prototype._releaseTexture = function (texture) {
  13922. var gl = this._gl;
  13923. this._releaseFramebufferObjects(texture);
  13924. gl.deleteTexture(texture._webGLTexture);
  13925. // Unbind channels
  13926. this.unbindAllTextures();
  13927. var index = this._internalTexturesCache.indexOf(texture);
  13928. if (index !== -1) {
  13929. this._internalTexturesCache.splice(index, 1);
  13930. }
  13931. // Integrated fixed lod samplers.
  13932. if (texture._lodTextureHigh) {
  13933. texture._lodTextureHigh.dispose();
  13934. }
  13935. if (texture._lodTextureMid) {
  13936. texture._lodTextureMid.dispose();
  13937. }
  13938. if (texture._lodTextureLow) {
  13939. texture._lodTextureLow.dispose();
  13940. }
  13941. };
  13942. Engine.prototype.setProgram = function (program) {
  13943. if (this._currentProgram !== program) {
  13944. this._gl.useProgram(program);
  13945. this._currentProgram = program;
  13946. }
  13947. };
  13948. Engine.prototype.bindSamplers = function (effect) {
  13949. this.setProgram(effect.getProgram());
  13950. var samplers = effect.getSamplers();
  13951. for (var index = 0; index < samplers.length; index++) {
  13952. var uniform = effect.getUniform(samplers[index]);
  13953. if (uniform) {
  13954. this._boundUniforms[index] = uniform;
  13955. }
  13956. }
  13957. this._currentEffect = null;
  13958. };
  13959. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  13960. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  13961. return;
  13962. }
  13963. // Remove
  13964. this._linkTrackers(internalTexture.previous, internalTexture.next);
  13965. // Bind last to it
  13966. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  13967. // Bind to dummy
  13968. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  13969. };
  13970. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  13971. if (!internalTexture) {
  13972. return -1;
  13973. }
  13974. internalTexture._initialSlot = channel;
  13975. if (this.disableTextureBindingOptimization) {
  13976. if (channel !== internalTexture._designatedSlot) {
  13977. this._textureCollisions.addCount(1, false);
  13978. }
  13979. }
  13980. else {
  13981. if (channel !== internalTexture._designatedSlot) {
  13982. if (internalTexture._designatedSlot > -1) {
  13983. return internalTexture._designatedSlot;
  13984. }
  13985. else {
  13986. // No slot for this texture, let's pick a new one (if we find a free slot)
  13987. if (this._nextFreeTextureSlots.length) {
  13988. return this._nextFreeTextureSlots[0];
  13989. }
  13990. // We need to recycle the oldest bound texture, sorry.
  13991. this._textureCollisions.addCount(1, false);
  13992. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  13993. }
  13994. }
  13995. }
  13996. return channel;
  13997. };
  13998. Engine.prototype._linkTrackers = function (previous, next) {
  13999. previous.next = next;
  14000. next.previous = previous;
  14001. };
  14002. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  14003. var currentSlot = internalTexture._designatedSlot;
  14004. if (currentSlot === -1) {
  14005. return -1;
  14006. }
  14007. internalTexture._designatedSlot = -1;
  14008. if (this.disableTextureBindingOptimization) {
  14009. return -1;
  14010. }
  14011. // Remove from bound list
  14012. this._linkTrackers(internalTexture.previous, internalTexture.next);
  14013. // Free the slot
  14014. this._boundTexturesCache[currentSlot] = null;
  14015. this._nextFreeTextureSlots.push(currentSlot);
  14016. return currentSlot;
  14017. };
  14018. Engine.prototype._activateCurrentTexture = function () {
  14019. if (this._currentTextureChannel !== this._activeChannel) {
  14020. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  14021. this._currentTextureChannel = this._activeChannel;
  14022. }
  14023. };
  14024. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate) {
  14025. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  14026. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  14027. this._activeChannel = texture._designatedSlot;
  14028. }
  14029. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  14030. var isTextureForRendering = texture && texture._initialSlot > -1;
  14031. if (currentTextureBound !== texture) {
  14032. if (currentTextureBound) {
  14033. this._removeDesignatedSlot(currentTextureBound);
  14034. }
  14035. this._activateCurrentTexture();
  14036. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  14037. this._boundTexturesCache[this._activeChannel] = texture;
  14038. if (texture) {
  14039. if (!this.disableTextureBindingOptimization) {
  14040. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  14041. if (slotIndex > -1) {
  14042. this._nextFreeTextureSlots.splice(slotIndex, 1);
  14043. }
  14044. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  14045. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  14046. }
  14047. texture._designatedSlot = this._activeChannel;
  14048. }
  14049. }
  14050. else if (forTextureDataUpdate) {
  14051. this._activateCurrentTexture();
  14052. }
  14053. if (isTextureForRendering && !forTextureDataUpdate) {
  14054. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  14055. }
  14056. };
  14057. Engine.prototype._bindTexture = function (channel, texture) {
  14058. if (channel < 0) {
  14059. return;
  14060. }
  14061. if (texture) {
  14062. channel = this._getCorrectTextureChannel(channel, texture);
  14063. }
  14064. this._activeChannel = channel;
  14065. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  14066. };
  14067. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  14068. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  14069. };
  14070. Engine.prototype.unbindAllTextures = function () {
  14071. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  14072. this._activeChannel = channel;
  14073. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14074. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14075. if (this.webGLVersion > 1) {
  14076. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14077. }
  14078. }
  14079. };
  14080. Engine.prototype.setTexture = function (channel, uniform, texture) {
  14081. if (channel < 0) {
  14082. return;
  14083. }
  14084. if (uniform) {
  14085. this._boundUniforms[channel] = uniform;
  14086. }
  14087. this._setTexture(channel, texture);
  14088. };
  14089. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  14090. var uniform = this._boundUniforms[sourceSlot];
  14091. if (uniform._currentState === destination) {
  14092. return;
  14093. }
  14094. this._gl.uniform1i(uniform, destination);
  14095. uniform._currentState = destination;
  14096. };
  14097. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray) {
  14098. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  14099. // Not ready?
  14100. if (!texture) {
  14101. if (this._boundTexturesCache[channel] != null) {
  14102. this._activeChannel = channel;
  14103. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14104. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14105. if (this.webGLVersion > 1) {
  14106. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14107. }
  14108. }
  14109. return false;
  14110. }
  14111. // Video
  14112. if (texture.video) {
  14113. this._activeChannel = channel;
  14114. texture.update();
  14115. }
  14116. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  14117. texture.delayLoad();
  14118. return false;
  14119. }
  14120. var internalTexture;
  14121. if (texture.isReady()) {
  14122. internalTexture = texture.getInternalTexture();
  14123. }
  14124. else if (texture.isCube) {
  14125. internalTexture = this.emptyCubeTexture;
  14126. }
  14127. else if (texture.is3D) {
  14128. internalTexture = this.emptyTexture3D;
  14129. }
  14130. else {
  14131. internalTexture = this.emptyTexture;
  14132. }
  14133. if (!isPartOfTextureArray) {
  14134. channel = this._getCorrectTextureChannel(channel, internalTexture);
  14135. }
  14136. if (this._boundTexturesCache[channel] === internalTexture) {
  14137. this._moveBoundTextureOnTop(internalTexture);
  14138. if (!isPartOfTextureArray) {
  14139. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  14140. }
  14141. return false;
  14142. }
  14143. this._activeChannel = channel;
  14144. if (internalTexture && internalTexture.is3D) {
  14145. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  14146. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  14147. internalTexture._cachedWrapU = texture.wrapU;
  14148. switch (texture.wrapU) {
  14149. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14150. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  14151. break;
  14152. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14153. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  14154. break;
  14155. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14156. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  14157. break;
  14158. }
  14159. }
  14160. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  14161. internalTexture._cachedWrapV = texture.wrapV;
  14162. switch (texture.wrapV) {
  14163. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14164. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  14165. break;
  14166. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14167. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  14168. break;
  14169. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14170. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  14171. break;
  14172. }
  14173. }
  14174. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  14175. internalTexture._cachedWrapR = texture.wrapR;
  14176. switch (texture.wrapR) {
  14177. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14178. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.REPEAT);
  14179. break;
  14180. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14181. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.CLAMP_TO_EDGE);
  14182. break;
  14183. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14184. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.MIRRORED_REPEAT);
  14185. break;
  14186. }
  14187. }
  14188. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  14189. }
  14190. else if (internalTexture && internalTexture.isCube) {
  14191. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  14192. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  14193. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  14194. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  14195. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  14196. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  14197. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  14198. }
  14199. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  14200. }
  14201. else {
  14202. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  14203. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  14204. internalTexture._cachedWrapU = texture.wrapU;
  14205. switch (texture.wrapU) {
  14206. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14207. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  14208. break;
  14209. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14210. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  14211. break;
  14212. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14213. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  14214. break;
  14215. }
  14216. }
  14217. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  14218. internalTexture._cachedWrapV = texture.wrapV;
  14219. switch (texture.wrapV) {
  14220. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14221. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  14222. break;
  14223. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14224. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  14225. break;
  14226. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14227. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  14228. break;
  14229. }
  14230. }
  14231. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  14232. }
  14233. return true;
  14234. };
  14235. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  14236. if (channel < 0 || !uniform) {
  14237. return;
  14238. }
  14239. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  14240. this._textureUnits = new Int32Array(textures.length);
  14241. }
  14242. for (var i = 0; i < textures.length; i++) {
  14243. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  14244. }
  14245. this._gl.uniform1iv(uniform, this._textureUnits);
  14246. for (var index = 0; index < textures.length; index++) {
  14247. this._setTexture(this._textureUnits[index], textures[index], true);
  14248. }
  14249. };
  14250. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  14251. var internalTexture = texture.getInternalTexture();
  14252. if (!internalTexture) {
  14253. return;
  14254. }
  14255. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  14256. var value = texture.anisotropicFilteringLevel;
  14257. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  14258. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  14259. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  14260. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  14261. }
  14262. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  14263. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  14264. internalTexture._cachedAnisotropicFilteringLevel = value;
  14265. }
  14266. };
  14267. Engine.prototype.readPixels = function (x, y, width, height) {
  14268. var data = new Uint8Array(height * width * 4);
  14269. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  14270. return data;
  14271. };
  14272. /**
  14273. * Add an externaly attached data from its key.
  14274. * This method call will fail and return false, if such key already exists.
  14275. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  14276. * @param key the unique key that identifies the data
  14277. * @param data the data object to associate to the key for this Engine instance
  14278. * @return true if no such key were already present and the data was added successfully, false otherwise
  14279. */
  14280. Engine.prototype.addExternalData = function (key, data) {
  14281. if (!this._externalData) {
  14282. this._externalData = new BABYLON.StringDictionary();
  14283. }
  14284. return this._externalData.add(key, data);
  14285. };
  14286. /**
  14287. * Get an externaly attached data from its key
  14288. * @param key the unique key that identifies the data
  14289. * @return the associated data, if present (can be null), or undefined if not present
  14290. */
  14291. Engine.prototype.getExternalData = function (key) {
  14292. if (!this._externalData) {
  14293. this._externalData = new BABYLON.StringDictionary();
  14294. }
  14295. return this._externalData.get(key);
  14296. };
  14297. /**
  14298. * Get an externaly attached data from its key, create it using a factory if it's not already present
  14299. * @param key the unique key that identifies the data
  14300. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  14301. * @return the associated data, can be null if the factory returned null.
  14302. */
  14303. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  14304. if (!this._externalData) {
  14305. this._externalData = new BABYLON.StringDictionary();
  14306. }
  14307. return this._externalData.getOrAddWithFactory(key, factory);
  14308. };
  14309. /**
  14310. * Remove an externaly attached data from the Engine instance
  14311. * @param key the unique key that identifies the data
  14312. * @return true if the data was successfully removed, false if it doesn't exist
  14313. */
  14314. Engine.prototype.removeExternalData = function (key) {
  14315. if (!this._externalData) {
  14316. this._externalData = new BABYLON.StringDictionary();
  14317. }
  14318. return this._externalData.remove(key);
  14319. };
  14320. Engine.prototype.unbindAllAttributes = function () {
  14321. if (this._mustWipeVertexAttributes) {
  14322. this._mustWipeVertexAttributes = false;
  14323. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  14324. this._gl.disableVertexAttribArray(i);
  14325. this._vertexAttribArraysEnabled[i] = false;
  14326. this._currentBufferPointers[i].active = false;
  14327. }
  14328. return;
  14329. }
  14330. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  14331. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  14332. continue;
  14333. }
  14334. this._gl.disableVertexAttribArray(i);
  14335. this._vertexAttribArraysEnabled[i] = false;
  14336. this._currentBufferPointers[i].active = false;
  14337. }
  14338. };
  14339. Engine.prototype.releaseEffects = function () {
  14340. for (var name in this._compiledEffects) {
  14341. this._deleteProgram(this._compiledEffects[name]._program);
  14342. }
  14343. this._compiledEffects = {};
  14344. };
  14345. // Dispose
  14346. Engine.prototype.dispose = function () {
  14347. this.hideLoadingUI();
  14348. this.stopRenderLoop();
  14349. // Release postProcesses
  14350. while (this.postProcesses.length) {
  14351. this.postProcesses[0].dispose();
  14352. }
  14353. // Empty texture
  14354. if (this._emptyTexture) {
  14355. this._releaseTexture(this._emptyTexture);
  14356. this._emptyTexture = null;
  14357. }
  14358. if (this._emptyCubeTexture) {
  14359. this._releaseTexture(this._emptyCubeTexture);
  14360. this._emptyCubeTexture = null;
  14361. }
  14362. // Rescale PP
  14363. if (this._rescalePostProcess) {
  14364. this._rescalePostProcess.dispose();
  14365. }
  14366. // Release scenes
  14367. while (this.scenes.length) {
  14368. this.scenes[0].dispose();
  14369. }
  14370. // Release audio engine
  14371. if (Engine.audioEngine) {
  14372. Engine.audioEngine.dispose();
  14373. }
  14374. // Release effects
  14375. this.releaseEffects();
  14376. // Unbind
  14377. this.unbindAllAttributes();
  14378. if (this._dummyFramebuffer) {
  14379. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  14380. }
  14381. //WebVR
  14382. this.disableVR();
  14383. // Events
  14384. if (BABYLON.Tools.IsWindowObjectExist()) {
  14385. window.removeEventListener("blur", this._onBlur);
  14386. window.removeEventListener("focus", this._onFocus);
  14387. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  14388. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  14389. if (this._renderingCanvas) {
  14390. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  14391. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  14392. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasBlur);
  14393. if (!this._doNotHandleContextLost) {
  14394. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  14395. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  14396. }
  14397. }
  14398. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  14399. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  14400. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  14401. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  14402. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  14403. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  14404. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  14405. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  14406. if (this._onVrDisplayConnect) {
  14407. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  14408. if (this._onVrDisplayDisconnect) {
  14409. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  14410. }
  14411. if (this._onVrDisplayPresentChange) {
  14412. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  14413. }
  14414. this._onVrDisplayConnect = null;
  14415. this._onVrDisplayDisconnect = null;
  14416. }
  14417. }
  14418. // Remove from Instances
  14419. var index = Engine.Instances.indexOf(this);
  14420. if (index >= 0) {
  14421. Engine.Instances.splice(index, 1);
  14422. }
  14423. this._workingCanvas = null;
  14424. this._workingContext = null;
  14425. this._currentBufferPointers = [];
  14426. this._renderingCanvas = null;
  14427. this._currentProgram = null;
  14428. this.onResizeObservable.clear();
  14429. this.onCanvasBlurObservable.clear();
  14430. this.onCanvasFocusObservable.clear();
  14431. this.onCanvasPointerOutObservable.clear();
  14432. this.onBeginFrameObservable.clear();
  14433. this.onEndFrameObservable.clear();
  14434. BABYLON.Effect.ResetCache();
  14435. // Abort active requests
  14436. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  14437. var request = _a[_i];
  14438. request.abort();
  14439. }
  14440. };
  14441. // Loading screen
  14442. Engine.prototype.displayLoadingUI = function () {
  14443. if (!BABYLON.Tools.IsWindowObjectExist()) {
  14444. return;
  14445. }
  14446. var loadingScreen = this.loadingScreen;
  14447. if (loadingScreen) {
  14448. loadingScreen.displayLoadingUI();
  14449. }
  14450. };
  14451. Engine.prototype.hideLoadingUI = function () {
  14452. if (!BABYLON.Tools.IsWindowObjectExist()) {
  14453. return;
  14454. }
  14455. var loadingScreen = this.loadingScreen;
  14456. if (loadingScreen) {
  14457. loadingScreen.hideLoadingUI();
  14458. }
  14459. };
  14460. Object.defineProperty(Engine.prototype, "loadingScreen", {
  14461. get: function () {
  14462. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  14463. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  14464. return this._loadingScreen;
  14465. },
  14466. set: function (loadingScreen) {
  14467. this._loadingScreen = loadingScreen;
  14468. },
  14469. enumerable: true,
  14470. configurable: true
  14471. });
  14472. Object.defineProperty(Engine.prototype, "loadingUIText", {
  14473. set: function (text) {
  14474. this.loadingScreen.loadingUIText = text;
  14475. },
  14476. enumerable: true,
  14477. configurable: true
  14478. });
  14479. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  14480. set: function (color) {
  14481. this.loadingScreen.loadingUIBackgroundColor = color;
  14482. },
  14483. enumerable: true,
  14484. configurable: true
  14485. });
  14486. Engine.prototype.attachContextLostEvent = function (callback) {
  14487. if (this._renderingCanvas) {
  14488. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  14489. }
  14490. };
  14491. Engine.prototype.attachContextRestoredEvent = function (callback) {
  14492. if (this._renderingCanvas) {
  14493. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  14494. }
  14495. };
  14496. Engine.prototype.getVertexShaderSource = function (program) {
  14497. var shaders = this._gl.getAttachedShaders(program);
  14498. if (!shaders) {
  14499. return null;
  14500. }
  14501. return this._gl.getShaderSource(shaders[0]);
  14502. };
  14503. Engine.prototype.getFragmentShaderSource = function (program) {
  14504. var shaders = this._gl.getAttachedShaders(program);
  14505. if (!shaders) {
  14506. return null;
  14507. }
  14508. return this._gl.getShaderSource(shaders[1]);
  14509. };
  14510. Engine.prototype.getError = function () {
  14511. return this._gl.getError();
  14512. };
  14513. // FPS
  14514. Engine.prototype.getFps = function () {
  14515. return this._fps;
  14516. };
  14517. Engine.prototype.getDeltaTime = function () {
  14518. return this._deltaTime;
  14519. };
  14520. Engine.prototype._measureFps = function () {
  14521. this._performanceMonitor.sampleFrame();
  14522. this._fps = this._performanceMonitor.averageFPS;
  14523. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  14524. };
  14525. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  14526. if (faceIndex === void 0) { faceIndex = -1; }
  14527. var gl = this._gl;
  14528. if (!this._dummyFramebuffer) {
  14529. var dummy = gl.createFramebuffer();
  14530. if (!dummy) {
  14531. throw new Error("Unable to create dummy framebuffer");
  14532. }
  14533. this._dummyFramebuffer = dummy;
  14534. }
  14535. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  14536. if (faceIndex > -1) {
  14537. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  14538. }
  14539. else {
  14540. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  14541. }
  14542. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  14543. var buffer;
  14544. switch (readType) {
  14545. case gl.UNSIGNED_BYTE:
  14546. buffer = new Uint8Array(4 * width * height);
  14547. readType = gl.UNSIGNED_BYTE;
  14548. break;
  14549. default:
  14550. buffer = new Float32Array(4 * width * height);
  14551. readType = gl.FLOAT;
  14552. break;
  14553. }
  14554. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  14555. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  14556. return buffer;
  14557. };
  14558. Engine.prototype._canRenderToFloatFramebuffer = function () {
  14559. if (this._webGLVersion > 1) {
  14560. return this._caps.colorBufferFloat;
  14561. }
  14562. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  14563. };
  14564. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  14565. if (this._webGLVersion > 1) {
  14566. return this._caps.colorBufferFloat;
  14567. }
  14568. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  14569. };
  14570. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  14571. Engine.prototype._canRenderToFramebuffer = function (type) {
  14572. var gl = this._gl;
  14573. //clear existing errors
  14574. while (gl.getError() !== gl.NO_ERROR) { }
  14575. var successful = true;
  14576. var texture = gl.createTexture();
  14577. gl.bindTexture(gl.TEXTURE_2D, texture);
  14578. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  14579. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  14580. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  14581. var fb = gl.createFramebuffer();
  14582. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  14583. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  14584. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  14585. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  14586. successful = successful && (gl.getError() === gl.NO_ERROR);
  14587. //try render by clearing frame buffer's color buffer
  14588. if (successful) {
  14589. gl.clear(gl.COLOR_BUFFER_BIT);
  14590. successful = successful && (gl.getError() === gl.NO_ERROR);
  14591. }
  14592. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  14593. if (successful) {
  14594. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  14595. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  14596. var readFormat = gl.RGBA;
  14597. var readType = gl.UNSIGNED_BYTE;
  14598. var buffer = new Uint8Array(4);
  14599. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  14600. successful = successful && (gl.getError() === gl.NO_ERROR);
  14601. }
  14602. //clean up
  14603. gl.deleteTexture(texture);
  14604. gl.deleteFramebuffer(fb);
  14605. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  14606. //clear accumulated errors
  14607. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  14608. return successful;
  14609. };
  14610. Engine.prototype._getWebGLTextureType = function (type) {
  14611. if (type === Engine.TEXTURETYPE_FLOAT) {
  14612. return this._gl.FLOAT;
  14613. }
  14614. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  14615. // Add Half Float Constant.
  14616. return this._gl.HALF_FLOAT_OES;
  14617. }
  14618. return this._gl.UNSIGNED_BYTE;
  14619. };
  14620. ;
  14621. Engine.prototype._getRGBABufferInternalSizedFormat = function (type) {
  14622. if (this._webGLVersion === 1) {
  14623. return this._gl.RGBA;
  14624. }
  14625. if (type === Engine.TEXTURETYPE_FLOAT) {
  14626. return this._gl.RGBA32F;
  14627. }
  14628. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  14629. return this._gl.RGBA16F;
  14630. }
  14631. return this._gl.RGBA;
  14632. };
  14633. ;
  14634. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  14635. if (type === Engine.TEXTURETYPE_FLOAT) {
  14636. return this._gl.RGBA32F;
  14637. }
  14638. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  14639. return this._gl.RGBA16F;
  14640. }
  14641. return this._gl.RGBA8;
  14642. };
  14643. ;
  14644. Engine.prototype.createQuery = function () {
  14645. return this._gl.createQuery();
  14646. };
  14647. Engine.prototype.deleteQuery = function (query) {
  14648. this._gl.deleteQuery(query);
  14649. return this;
  14650. };
  14651. Engine.prototype.isQueryResultAvailable = function (query) {
  14652. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  14653. };
  14654. Engine.prototype.getQueryResult = function (query) {
  14655. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  14656. };
  14657. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  14658. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  14659. this._gl.beginQuery(glAlgorithm, query);
  14660. return this;
  14661. };
  14662. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  14663. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  14664. this._gl.endQuery(glAlgorithm);
  14665. return this;
  14666. };
  14667. /* Time queries */
  14668. Engine.prototype._createTimeQuery = function () {
  14669. var timerQuery = this._caps.timerQuery;
  14670. if (timerQuery.createQueryEXT) {
  14671. return timerQuery.createQueryEXT();
  14672. }
  14673. return this.createQuery();
  14674. };
  14675. Engine.prototype._deleteTimeQuery = function (query) {
  14676. var timerQuery = this._caps.timerQuery;
  14677. if (timerQuery.deleteQueryEXT) {
  14678. timerQuery.deleteQueryEXT(query);
  14679. return;
  14680. }
  14681. this.deleteQuery(query);
  14682. };
  14683. Engine.prototype._getTimeQueryResult = function (query) {
  14684. var timerQuery = this._caps.timerQuery;
  14685. if (timerQuery.getQueryObjectEXT) {
  14686. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  14687. }
  14688. return this.getQueryResult(query);
  14689. };
  14690. Engine.prototype._getTimeQueryAvailability = function (query) {
  14691. var timerQuery = this._caps.timerQuery;
  14692. if (timerQuery.getQueryObjectEXT) {
  14693. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  14694. }
  14695. return this.isQueryResultAvailable(query);
  14696. };
  14697. Engine.prototype.startTimeQuery = function () {
  14698. var timerQuery = this._caps.timerQuery;
  14699. if (!timerQuery) {
  14700. return null;
  14701. }
  14702. var token = new BABYLON._TimeToken();
  14703. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  14704. if (this._caps.canUseTimestampForTimerQuery) {
  14705. token._startTimeQuery = this._createTimeQuery();
  14706. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  14707. }
  14708. else {
  14709. if (this._currentNonTimestampToken) {
  14710. return this._currentNonTimestampToken;
  14711. }
  14712. token._timeElapsedQuery = this._createTimeQuery();
  14713. if (timerQuery.beginQueryEXT) {
  14714. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  14715. }
  14716. else {
  14717. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  14718. }
  14719. this._currentNonTimestampToken = token;
  14720. }
  14721. return token;
  14722. };
  14723. Engine.prototype.endTimeQuery = function (token) {
  14724. var timerQuery = this._caps.timerQuery;
  14725. if (!timerQuery || !token) {
  14726. return -1;
  14727. }
  14728. if (this._caps.canUseTimestampForTimerQuery) {
  14729. if (!token._startTimeQuery) {
  14730. return -1;
  14731. }
  14732. if (!token._endTimeQuery) {
  14733. token._endTimeQuery = this._createTimeQuery();
  14734. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  14735. }
  14736. }
  14737. else if (!token._timeElapsedQueryEnded) {
  14738. if (!token._timeElapsedQuery) {
  14739. return -1;
  14740. }
  14741. if (timerQuery.endQueryEXT) {
  14742. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  14743. }
  14744. else {
  14745. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  14746. }
  14747. token._timeElapsedQueryEnded = true;
  14748. }
  14749. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  14750. var available = false;
  14751. if (token._endTimeQuery) {
  14752. available = this._getTimeQueryAvailability(token._endTimeQuery);
  14753. }
  14754. else if (token._timeElapsedQuery) {
  14755. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  14756. }
  14757. if (available && !disjoint) {
  14758. var result = 0;
  14759. if (this._caps.canUseTimestampForTimerQuery) {
  14760. if (!token._startTimeQuery || !token._endTimeQuery) {
  14761. return -1;
  14762. }
  14763. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  14764. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  14765. result = timeEnd - timeStart;
  14766. this._deleteTimeQuery(token._startTimeQuery);
  14767. this._deleteTimeQuery(token._endTimeQuery);
  14768. token._startTimeQuery = null;
  14769. token._endTimeQuery = null;
  14770. }
  14771. else {
  14772. if (!token._timeElapsedQuery) {
  14773. return -1;
  14774. }
  14775. result = this._getTimeQueryResult(token._timeElapsedQuery);
  14776. this._deleteTimeQuery(token._timeElapsedQuery);
  14777. token._timeElapsedQuery = null;
  14778. token._timeElapsedQueryEnded = false;
  14779. this._currentNonTimestampToken = null;
  14780. }
  14781. return result;
  14782. }
  14783. return -1;
  14784. };
  14785. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  14786. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  14787. };
  14788. // Transform feedback
  14789. Engine.prototype.createTransformFeedback = function () {
  14790. return this._gl.createTransformFeedback();
  14791. };
  14792. Engine.prototype.deleteTransformFeedback = function (value) {
  14793. this._gl.deleteTransformFeedback(value);
  14794. };
  14795. Engine.prototype.bindTransformFeedback = function (value) {
  14796. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  14797. };
  14798. Engine.prototype.beginTransformFeedback = function (usePoints) {
  14799. if (usePoints === void 0) { usePoints = true; }
  14800. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  14801. };
  14802. Engine.prototype.endTransformFeedback = function () {
  14803. this._gl.endTransformFeedback();
  14804. };
  14805. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  14806. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  14807. };
  14808. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  14809. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  14810. };
  14811. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  14812. var _this = this;
  14813. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  14814. this._activeRequests.push(request);
  14815. request.onCompleteObservable.add(function (request) {
  14816. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  14817. });
  14818. return request;
  14819. };
  14820. /** @ignore */
  14821. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  14822. var _this = this;
  14823. return new Promise(function (resolve, reject) {
  14824. _this._loadFile(url, function (data) {
  14825. resolve(data);
  14826. }, undefined, database, useArrayBuffer, function (request, exception) {
  14827. reject(exception);
  14828. });
  14829. });
  14830. };
  14831. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  14832. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  14833. var onload = function (data) {
  14834. loadedFiles[index] = data;
  14835. loadedFiles._internalCount++;
  14836. if (loadedFiles._internalCount === 6) {
  14837. onfinish(loadedFiles);
  14838. }
  14839. };
  14840. var onerror = function (request, exception) {
  14841. if (onErrorCallBack && request) {
  14842. onErrorCallBack(request.status + " " + request.statusText, exception);
  14843. }
  14844. };
  14845. this._loadFile(url, onload, undefined, undefined, true, onerror);
  14846. };
  14847. Engine.prototype._cascadeLoadFiles = function (rootUrl, scene, onfinish, files, onError) {
  14848. if (onError === void 0) { onError = null; }
  14849. var loadedFiles = [];
  14850. loadedFiles._internalCount = 0;
  14851. for (var index = 0; index < 6; index++) {
  14852. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  14853. }
  14854. };
  14855. // Statics
  14856. Engine.isSupported = function () {
  14857. try {
  14858. var tempcanvas = document.createElement("canvas");
  14859. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  14860. return gl != null && !!window.WebGLRenderingContext;
  14861. }
  14862. catch (e) {
  14863. return false;
  14864. }
  14865. };
  14866. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  14867. Engine.ExceptionList = [
  14868. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  14869. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  14870. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  14871. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  14872. ];
  14873. Engine.Instances = new Array();
  14874. // Const statics
  14875. Engine._ALPHA_DISABLE = 0;
  14876. Engine._ALPHA_ADD = 1;
  14877. Engine._ALPHA_COMBINE = 2;
  14878. Engine._ALPHA_SUBTRACT = 3;
  14879. Engine._ALPHA_MULTIPLY = 4;
  14880. Engine._ALPHA_MAXIMIZED = 5;
  14881. Engine._ALPHA_ONEONE = 6;
  14882. Engine._ALPHA_PREMULTIPLIED = 7;
  14883. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  14884. Engine._ALPHA_INTERPOLATE = 9;
  14885. Engine._ALPHA_SCREENMODE = 10;
  14886. Engine._DELAYLOADSTATE_NONE = 0;
  14887. Engine._DELAYLOADSTATE_LOADED = 1;
  14888. Engine._DELAYLOADSTATE_LOADING = 2;
  14889. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  14890. Engine._TEXTUREFORMAT_ALPHA = 0;
  14891. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  14892. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  14893. Engine._TEXTUREFORMAT_RGB = 4;
  14894. Engine._TEXTUREFORMAT_RGBA = 5;
  14895. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  14896. Engine._TEXTURETYPE_FLOAT = 1;
  14897. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  14898. // Depht or Stencil test Constants.
  14899. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  14900. 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.
  14901. 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.
  14902. 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.
  14903. 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.
  14904. 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.
  14905. 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.
  14906. 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.
  14907. // Stencil Actions Constants.
  14908. Engine._KEEP = 0x1E00;
  14909. Engine._REPLACE = 0x1E01;
  14910. Engine._INCR = 0x1E02;
  14911. Engine._DECR = 0x1E03;
  14912. Engine._INVERT = 0x150A;
  14913. Engine._INCR_WRAP = 0x8507;
  14914. Engine._DECR_WRAP = 0x8508;
  14915. // Texture rescaling mode
  14916. Engine._SCALEMODE_FLOOR = 1;
  14917. Engine._SCALEMODE_NEAREST = 2;
  14918. Engine._SCALEMODE_CEILING = 3;
  14919. // Updatable statics so stick with vars here
  14920. Engine.CollisionsEpsilon = 0.001;
  14921. Engine.CodeRepository = "src/";
  14922. Engine.ShadersRepository = "src/Shaders/";
  14923. return Engine;
  14924. }());
  14925. BABYLON.Engine = Engine;
  14926. })(BABYLON || (BABYLON = {}));
  14927. //# sourceMappingURL=babylon.engine.js.map
  14928. var BABYLON;
  14929. (function (BABYLON) {
  14930. /**
  14931. * Node is the basic class for all scene objects (Mesh, Light Camera).
  14932. */
  14933. var Node = /** @class */ (function () {
  14934. /**
  14935. * @constructor
  14936. * @param {string} name - the name and id to be given to this node
  14937. * @param {BABYLON.Scene} the scene this node will be added to
  14938. */
  14939. function Node(name, scene) {
  14940. if (scene === void 0) { scene = null; }
  14941. this.state = "";
  14942. this.metadata = null;
  14943. this.doNotSerialize = false;
  14944. this.animations = new Array();
  14945. this._ranges = {};
  14946. this._isEnabled = true;
  14947. this._isReady = true;
  14948. this._currentRenderId = -1;
  14949. this._parentRenderId = -1;
  14950. /**
  14951. * An event triggered when the mesh is disposed.
  14952. * @type {BABYLON.Observable}
  14953. */
  14954. this.onDisposeObservable = new BABYLON.Observable();
  14955. // Behaviors
  14956. this._behaviors = new Array();
  14957. this.name = name;
  14958. this.id = name;
  14959. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  14960. this.uniqueId = this._scene.getUniqueId();
  14961. this._initCache();
  14962. }
  14963. Object.defineProperty(Node.prototype, "parent", {
  14964. get: function () {
  14965. return this._parentNode;
  14966. },
  14967. set: function (parent) {
  14968. if (this._parentNode === parent) {
  14969. return;
  14970. }
  14971. // Remove self from list of children of parent
  14972. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  14973. var index = this._parentNode._children.indexOf(this);
  14974. if (index !== -1) {
  14975. this._parentNode._children.splice(index, 1);
  14976. }
  14977. }
  14978. // Store new parent
  14979. this._parentNode = parent;
  14980. // Add as child to new parent
  14981. if (this._parentNode) {
  14982. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  14983. this._parentNode._children = new Array();
  14984. }
  14985. this._parentNode._children.push(this);
  14986. }
  14987. },
  14988. enumerable: true,
  14989. configurable: true
  14990. });
  14991. Node.prototype.getClassName = function () {
  14992. return "Node";
  14993. };
  14994. Object.defineProperty(Node.prototype, "onDispose", {
  14995. set: function (callback) {
  14996. if (this._onDisposeObserver) {
  14997. this.onDisposeObservable.remove(this._onDisposeObserver);
  14998. }
  14999. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  15000. },
  15001. enumerable: true,
  15002. configurable: true
  15003. });
  15004. Node.prototype.getScene = function () {
  15005. return this._scene;
  15006. };
  15007. Node.prototype.getEngine = function () {
  15008. return this._scene.getEngine();
  15009. };
  15010. Node.prototype.addBehavior = function (behavior) {
  15011. var _this = this;
  15012. var index = this._behaviors.indexOf(behavior);
  15013. if (index !== -1) {
  15014. return this;
  15015. }
  15016. behavior.init();
  15017. if (this._scene.isLoading) {
  15018. // We defer the attach when the scene will be loaded
  15019. var observer = this._scene.onDataLoadedObservable.add(function () {
  15020. behavior.attach(_this);
  15021. setTimeout(function () {
  15022. // Need to use a timeout to avoid removing an observer while iterating the list of observers
  15023. _this._scene.onDataLoadedObservable.remove(observer);
  15024. }, 0);
  15025. });
  15026. }
  15027. else {
  15028. behavior.attach(this);
  15029. }
  15030. this._behaviors.push(behavior);
  15031. return this;
  15032. };
  15033. Node.prototype.removeBehavior = function (behavior) {
  15034. var index = this._behaviors.indexOf(behavior);
  15035. if (index === -1) {
  15036. return this;
  15037. }
  15038. this._behaviors[index].detach();
  15039. this._behaviors.splice(index, 1);
  15040. return this;
  15041. };
  15042. Object.defineProperty(Node.prototype, "behaviors", {
  15043. get: function () {
  15044. return this._behaviors;
  15045. },
  15046. enumerable: true,
  15047. configurable: true
  15048. });
  15049. Node.prototype.getBehaviorByName = function (name) {
  15050. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  15051. var behavior = _a[_i];
  15052. if (behavior.name === name) {
  15053. return behavior;
  15054. }
  15055. }
  15056. return null;
  15057. };
  15058. // override it in derived class
  15059. Node.prototype.getWorldMatrix = function () {
  15060. return BABYLON.Matrix.Identity();
  15061. };
  15062. // override it in derived class if you add new variables to the cache
  15063. // and call the parent class method
  15064. Node.prototype._initCache = function () {
  15065. this._cache = {};
  15066. this._cache.parent = undefined;
  15067. };
  15068. Node.prototype.updateCache = function (force) {
  15069. if (!force && this.isSynchronized())
  15070. return;
  15071. this._cache.parent = this.parent;
  15072. this._updateCache();
  15073. };
  15074. // override it in derived class if you add new variables to the cache
  15075. // and call the parent class method if !ignoreParentClass
  15076. Node.prototype._updateCache = function (ignoreParentClass) {
  15077. };
  15078. // override it in derived class if you add new variables to the cache
  15079. Node.prototype._isSynchronized = function () {
  15080. return true;
  15081. };
  15082. Node.prototype._markSyncedWithParent = function () {
  15083. if (this.parent) {
  15084. this._parentRenderId = this.parent._currentRenderId;
  15085. }
  15086. };
  15087. Node.prototype.isSynchronizedWithParent = function () {
  15088. if (!this.parent) {
  15089. return true;
  15090. }
  15091. if (this._parentRenderId !== this.parent._currentRenderId) {
  15092. return false;
  15093. }
  15094. return this.parent.isSynchronized();
  15095. };
  15096. Node.prototype.isSynchronized = function (updateCache) {
  15097. var check = this.hasNewParent();
  15098. check = check || !this.isSynchronizedWithParent();
  15099. check = check || !this._isSynchronized();
  15100. if (updateCache)
  15101. this.updateCache(true);
  15102. return !check;
  15103. };
  15104. Node.prototype.hasNewParent = function (update) {
  15105. if (this._cache.parent === this.parent)
  15106. return false;
  15107. if (update)
  15108. this._cache.parent = this.parent;
  15109. return true;
  15110. };
  15111. /**
  15112. * Is this node ready to be used/rendered
  15113. * @return {boolean} is it ready
  15114. */
  15115. Node.prototype.isReady = function () {
  15116. return this._isReady;
  15117. };
  15118. /**
  15119. * Is this node enabled.
  15120. * 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.
  15121. * @param {boolean} [checkAncestors=true] - 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.
  15122. * @return {boolean} whether this node (and its parent) is enabled.
  15123. * @see setEnabled
  15124. */
  15125. Node.prototype.isEnabled = function (checkAncestors) {
  15126. if (checkAncestors === void 0) { checkAncestors = true; }
  15127. if (checkAncestors === false) {
  15128. return this._isEnabled;
  15129. }
  15130. if (this._isEnabled === false) {
  15131. return false;
  15132. }
  15133. if (this.parent !== undefined && this.parent !== null) {
  15134. return this.parent.isEnabled(checkAncestors);
  15135. }
  15136. return true;
  15137. };
  15138. /**
  15139. * Set the enabled state of this node.
  15140. * @param {boolean} value - the new enabled state
  15141. * @see isEnabled
  15142. */
  15143. Node.prototype.setEnabled = function (value) {
  15144. this._isEnabled = value;
  15145. };
  15146. /**
  15147. * Is this node a descendant of the given node.
  15148. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  15149. * @param {BABYLON.Node} ancestor - The parent node to inspect
  15150. * @see parent
  15151. */
  15152. Node.prototype.isDescendantOf = function (ancestor) {
  15153. if (this.parent) {
  15154. if (this.parent === ancestor) {
  15155. return true;
  15156. }
  15157. return this.parent.isDescendantOf(ancestor);
  15158. }
  15159. return false;
  15160. };
  15161. /**
  15162. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  15163. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  15164. * @param {boolean} directDescendantsOnly 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.
  15165. * @param predicate: an optional predicate that will be called on every evaluated children, the predicate must return true for a given child to be part of the result, otherwise it will be ignored.
  15166. */
  15167. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  15168. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  15169. if (!this._children) {
  15170. return;
  15171. }
  15172. for (var index = 0; index < this._children.length; index++) {
  15173. var item = this._children[index];
  15174. if (!predicate || predicate(item)) {
  15175. results.push(item);
  15176. }
  15177. if (!directDescendantsOnly) {
  15178. item._getDescendants(results, false, predicate);
  15179. }
  15180. }
  15181. };
  15182. /**
  15183. * Will return all nodes that have this node as ascendant.
  15184. * @param {boolean} directDescendantsOnly 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.
  15185. * @param predicate: an optional predicate that will be called on every evaluated children, the predicate must return true for a given child to be part of the result, otherwise it will be ignored.
  15186. * @return {BABYLON.Node[]} all children nodes of all types.
  15187. */
  15188. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  15189. var results = new Array();
  15190. this._getDescendants(results, directDescendantsOnly, predicate);
  15191. return results;
  15192. };
  15193. /**
  15194. * Get all child-meshes of this node.
  15195. */
  15196. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  15197. var results = [];
  15198. this._getDescendants(results, directDescendantsOnly, function (node) {
  15199. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  15200. });
  15201. return results;
  15202. };
  15203. /**
  15204. * Get all child-transformNodes of this node.
  15205. */
  15206. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  15207. var results = [];
  15208. this._getDescendants(results, directDescendantsOnly, function (node) {
  15209. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  15210. });
  15211. return results;
  15212. };
  15213. /**
  15214. * Get all direct children of this node.
  15215. */
  15216. Node.prototype.getChildren = function (predicate) {
  15217. return this.getDescendants(true, predicate);
  15218. };
  15219. Node.prototype._setReady = function (state) {
  15220. if (state === this._isReady) {
  15221. return;
  15222. }
  15223. if (!state) {
  15224. this._isReady = false;
  15225. return;
  15226. }
  15227. this._isReady = true;
  15228. if (this.onReady) {
  15229. this.onReady(this);
  15230. }
  15231. };
  15232. Node.prototype.getAnimationByName = function (name) {
  15233. for (var i = 0; i < this.animations.length; i++) {
  15234. var animation = this.animations[i];
  15235. if (animation.name === name) {
  15236. return animation;
  15237. }
  15238. }
  15239. return null;
  15240. };
  15241. Node.prototype.createAnimationRange = function (name, from, to) {
  15242. // check name not already in use
  15243. if (!this._ranges[name]) {
  15244. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  15245. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  15246. if (this.animations[i]) {
  15247. this.animations[i].createRange(name, from, to);
  15248. }
  15249. }
  15250. }
  15251. };
  15252. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  15253. if (deleteFrames === void 0) { deleteFrames = true; }
  15254. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  15255. if (this.animations[i]) {
  15256. this.animations[i].deleteRange(name, deleteFrames);
  15257. }
  15258. }
  15259. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  15260. };
  15261. Node.prototype.getAnimationRange = function (name) {
  15262. return this._ranges[name];
  15263. };
  15264. /**
  15265. * Will start the animation sequence
  15266. * @param name defines the range frames for animation sequence
  15267. * @param loop defines if the animation should loop (false by default)
  15268. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  15269. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  15270. * @returns the {BABYLON.Animatable} object created for this animation. If range does not exist, it will return null
  15271. */
  15272. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  15273. var range = this.getAnimationRange(name);
  15274. if (!range) {
  15275. return null;
  15276. }
  15277. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  15278. };
  15279. Node.prototype.serializeAnimationRanges = function () {
  15280. var serializationRanges = [];
  15281. for (var name in this._ranges) {
  15282. var localRange = this._ranges[name];
  15283. if (!localRange) {
  15284. continue;
  15285. }
  15286. var range = {};
  15287. range.name = name;
  15288. range.from = localRange.from;
  15289. range.to = localRange.to;
  15290. serializationRanges.push(range);
  15291. }
  15292. return serializationRanges;
  15293. };
  15294. // override it in derived class
  15295. Node.prototype.computeWorldMatrix = function (force) {
  15296. return BABYLON.Matrix.Identity();
  15297. };
  15298. Node.prototype.dispose = function () {
  15299. this.parent = null;
  15300. // Callback
  15301. this.onDisposeObservable.notifyObservers(this);
  15302. this.onDisposeObservable.clear();
  15303. // Behaviors
  15304. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  15305. var behavior = _a[_i];
  15306. behavior.detach();
  15307. }
  15308. this._behaviors = [];
  15309. };
  15310. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  15311. if (parsedNode.ranges) {
  15312. for (var index = 0; index < parsedNode.ranges.length; index++) {
  15313. var data = parsedNode.ranges[index];
  15314. node.createAnimationRange(data.name, data.from, data.to);
  15315. }
  15316. }
  15317. };
  15318. __decorate([
  15319. BABYLON.serialize()
  15320. ], Node.prototype, "name", void 0);
  15321. __decorate([
  15322. BABYLON.serialize()
  15323. ], Node.prototype, "id", void 0);
  15324. __decorate([
  15325. BABYLON.serialize()
  15326. ], Node.prototype, "uniqueId", void 0);
  15327. __decorate([
  15328. BABYLON.serialize()
  15329. ], Node.prototype, "state", void 0);
  15330. __decorate([
  15331. BABYLON.serialize()
  15332. ], Node.prototype, "metadata", void 0);
  15333. return Node;
  15334. }());
  15335. BABYLON.Node = Node;
  15336. })(BABYLON || (BABYLON = {}));
  15337. //# sourceMappingURL=babylon.node.js.map
  15338. var BABYLON;
  15339. (function (BABYLON) {
  15340. var BoundingSphere = /** @class */ (function () {
  15341. function BoundingSphere(minimum, maximum) {
  15342. this.minimum = minimum;
  15343. this.maximum = maximum;
  15344. this._tempRadiusVector = BABYLON.Vector3.Zero();
  15345. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  15346. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  15347. this.radius = distance * 0.5;
  15348. this.centerWorld = BABYLON.Vector3.Zero();
  15349. this._update(BABYLON.Matrix.Identity());
  15350. }
  15351. // Methods
  15352. BoundingSphere.prototype._update = function (world) {
  15353. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  15354. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  15355. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  15356. };
  15357. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  15358. for (var i = 0; i < 6; i++) {
  15359. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  15360. return false;
  15361. }
  15362. return true;
  15363. };
  15364. BoundingSphere.prototype.intersectsPoint = function (point) {
  15365. var x = this.centerWorld.x - point.x;
  15366. var y = this.centerWorld.y - point.y;
  15367. var z = this.centerWorld.z - point.z;
  15368. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  15369. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  15370. return false;
  15371. return true;
  15372. };
  15373. // Statics
  15374. BoundingSphere.Intersects = function (sphere0, sphere1) {
  15375. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  15376. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  15377. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  15378. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  15379. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  15380. return false;
  15381. return true;
  15382. };
  15383. return BoundingSphere;
  15384. }());
  15385. BABYLON.BoundingSphere = BoundingSphere;
  15386. })(BABYLON || (BABYLON = {}));
  15387. //# sourceMappingURL=babylon.boundingSphere.js.map
  15388. var BABYLON;
  15389. (function (BABYLON) {
  15390. var BoundingBox = /** @class */ (function () {
  15391. function BoundingBox(minimum, maximum) {
  15392. this.minimum = minimum;
  15393. this.maximum = maximum;
  15394. this.vectors = new Array();
  15395. this.vectorsWorld = new Array();
  15396. // Bounding vectors
  15397. this.vectors.push(this.minimum.clone());
  15398. this.vectors.push(this.maximum.clone());
  15399. this.vectors.push(this.minimum.clone());
  15400. this.vectors[2].x = this.maximum.x;
  15401. this.vectors.push(this.minimum.clone());
  15402. this.vectors[3].y = this.maximum.y;
  15403. this.vectors.push(this.minimum.clone());
  15404. this.vectors[4].z = this.maximum.z;
  15405. this.vectors.push(this.maximum.clone());
  15406. this.vectors[5].z = this.minimum.z;
  15407. this.vectors.push(this.maximum.clone());
  15408. this.vectors[6].x = this.minimum.x;
  15409. this.vectors.push(this.maximum.clone());
  15410. this.vectors[7].y = this.minimum.y;
  15411. // OBB
  15412. this.center = this.maximum.add(this.minimum).scale(0.5);
  15413. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  15414. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  15415. // World
  15416. for (var index = 0; index < this.vectors.length; index++) {
  15417. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  15418. }
  15419. this.minimumWorld = BABYLON.Vector3.Zero();
  15420. this.maximumWorld = BABYLON.Vector3.Zero();
  15421. this.centerWorld = BABYLON.Vector3.Zero();
  15422. this.extendSizeWorld = BABYLON.Vector3.Zero();
  15423. this._update(BABYLON.Matrix.Identity());
  15424. }
  15425. // Methods
  15426. BoundingBox.prototype.getWorldMatrix = function () {
  15427. return this._worldMatrix;
  15428. };
  15429. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  15430. this._worldMatrix.copyFrom(matrix);
  15431. return this;
  15432. };
  15433. BoundingBox.prototype._update = function (world) {
  15434. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  15435. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  15436. for (var index = 0; index < this.vectors.length; index++) {
  15437. var v = this.vectorsWorld[index];
  15438. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  15439. if (v.x < this.minimumWorld.x)
  15440. this.minimumWorld.x = v.x;
  15441. if (v.y < this.minimumWorld.y)
  15442. this.minimumWorld.y = v.y;
  15443. if (v.z < this.minimumWorld.z)
  15444. this.minimumWorld.z = v.z;
  15445. if (v.x > this.maximumWorld.x)
  15446. this.maximumWorld.x = v.x;
  15447. if (v.y > this.maximumWorld.y)
  15448. this.maximumWorld.y = v.y;
  15449. if (v.z > this.maximumWorld.z)
  15450. this.maximumWorld.z = v.z;
  15451. }
  15452. // Extend
  15453. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  15454. this.extendSizeWorld.scaleInPlace(0.5);
  15455. // OBB
  15456. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  15457. this.centerWorld.scaleInPlace(0.5);
  15458. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  15459. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  15460. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  15461. this._worldMatrix = world;
  15462. };
  15463. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  15464. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  15465. };
  15466. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  15467. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  15468. };
  15469. BoundingBox.prototype.intersectsPoint = function (point) {
  15470. var delta = -BABYLON.Epsilon;
  15471. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  15472. return false;
  15473. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  15474. return false;
  15475. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  15476. return false;
  15477. return true;
  15478. };
  15479. BoundingBox.prototype.intersectsSphere = function (sphere) {
  15480. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  15481. };
  15482. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  15483. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  15484. return false;
  15485. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  15486. return false;
  15487. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  15488. return false;
  15489. return true;
  15490. };
  15491. // Statics
  15492. BoundingBox.Intersects = function (box0, box1) {
  15493. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  15494. return false;
  15495. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  15496. return false;
  15497. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  15498. return false;
  15499. return true;
  15500. };
  15501. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  15502. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  15503. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  15504. return (num <= (sphereRadius * sphereRadius));
  15505. };
  15506. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  15507. for (var p = 0; p < 6; p++) {
  15508. for (var i = 0; i < 8; i++) {
  15509. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  15510. return false;
  15511. }
  15512. }
  15513. }
  15514. return true;
  15515. };
  15516. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  15517. for (var p = 0; p < 6; p++) {
  15518. var inCount = 8;
  15519. for (var i = 0; i < 8; i++) {
  15520. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  15521. --inCount;
  15522. }
  15523. else {
  15524. break;
  15525. }
  15526. }
  15527. if (inCount === 0)
  15528. return false;
  15529. }
  15530. return true;
  15531. };
  15532. return BoundingBox;
  15533. }());
  15534. BABYLON.BoundingBox = BoundingBox;
  15535. })(BABYLON || (BABYLON = {}));
  15536. //# sourceMappingURL=babylon.boundingBox.js.map
  15537. var BABYLON;
  15538. (function (BABYLON) {
  15539. var computeBoxExtents = function (axis, box) {
  15540. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  15541. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  15542. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  15543. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  15544. var r = r0 + r1 + r2;
  15545. return {
  15546. min: p - r,
  15547. max: p + r
  15548. };
  15549. };
  15550. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  15551. var axisOverlap = function (axis, box0, box1) {
  15552. var result0 = computeBoxExtents(axis, box0);
  15553. var result1 = computeBoxExtents(axis, box1);
  15554. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  15555. };
  15556. var BoundingInfo = /** @class */ (function () {
  15557. function BoundingInfo(minimum, maximum) {
  15558. this.minimum = minimum;
  15559. this.maximum = maximum;
  15560. this._isLocked = false;
  15561. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  15562. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  15563. }
  15564. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  15565. get: function () {
  15566. return this._isLocked;
  15567. },
  15568. set: function (value) {
  15569. this._isLocked = value;
  15570. },
  15571. enumerable: true,
  15572. configurable: true
  15573. });
  15574. // Methods
  15575. BoundingInfo.prototype.update = function (world) {
  15576. if (this._isLocked) {
  15577. return;
  15578. }
  15579. this.boundingBox._update(world);
  15580. this.boundingSphere._update(world);
  15581. };
  15582. /**
  15583. * Recreate the bounding info to be centered around a specific point given a specific extend.
  15584. * @param center New center of the bounding info
  15585. * @param extend New extend of the bounding info
  15586. */
  15587. BoundingInfo.prototype.centerOn = function (center, extend) {
  15588. this.minimum = center.subtract(extend);
  15589. this.maximum = center.add(extend);
  15590. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  15591. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  15592. return this;
  15593. };
  15594. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  15595. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  15596. return false;
  15597. return this.boundingBox.isInFrustum(frustumPlanes);
  15598. };
  15599. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  15600. /**
  15601. * Gets the world distance between the min and max points of the bounding box
  15602. */
  15603. get: function () {
  15604. var boundingBox = this.boundingBox;
  15605. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  15606. return size.length();
  15607. },
  15608. enumerable: true,
  15609. configurable: true
  15610. });
  15611. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  15612. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  15613. };
  15614. BoundingInfo.prototype._checkCollision = function (collider) {
  15615. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  15616. };
  15617. BoundingInfo.prototype.intersectsPoint = function (point) {
  15618. if (!this.boundingSphere.centerWorld) {
  15619. return false;
  15620. }
  15621. if (!this.boundingSphere.intersectsPoint(point)) {
  15622. return false;
  15623. }
  15624. if (!this.boundingBox.intersectsPoint(point)) {
  15625. return false;
  15626. }
  15627. return true;
  15628. };
  15629. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  15630. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  15631. return false;
  15632. }
  15633. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  15634. return false;
  15635. }
  15636. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  15637. return false;
  15638. }
  15639. if (!precise) {
  15640. return true;
  15641. }
  15642. var box0 = this.boundingBox;
  15643. var box1 = boundingInfo.boundingBox;
  15644. if (!axisOverlap(box0.directions[0], box0, box1))
  15645. return false;
  15646. if (!axisOverlap(box0.directions[1], box0, box1))
  15647. return false;
  15648. if (!axisOverlap(box0.directions[2], box0, box1))
  15649. return false;
  15650. if (!axisOverlap(box1.directions[0], box0, box1))
  15651. return false;
  15652. if (!axisOverlap(box1.directions[1], box0, box1))
  15653. return false;
  15654. if (!axisOverlap(box1.directions[2], box0, box1))
  15655. return false;
  15656. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  15657. return false;
  15658. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  15659. return false;
  15660. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  15661. return false;
  15662. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  15663. return false;
  15664. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  15665. return false;
  15666. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  15667. return false;
  15668. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  15669. return false;
  15670. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  15671. return false;
  15672. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  15673. return false;
  15674. return true;
  15675. };
  15676. return BoundingInfo;
  15677. }());
  15678. BABYLON.BoundingInfo = BoundingInfo;
  15679. })(BABYLON || (BABYLON = {}));
  15680. //# sourceMappingURL=babylon.boundingInfo.js.map
  15681. var BABYLON;
  15682. (function (BABYLON) {
  15683. var TransformNode = /** @class */ (function (_super) {
  15684. __extends(TransformNode, _super);
  15685. function TransformNode(name, scene, isPure) {
  15686. if (scene === void 0) { scene = null; }
  15687. if (isPure === void 0) { isPure = true; }
  15688. var _this = _super.call(this, name, scene) || this;
  15689. // Properties
  15690. _this._rotation = BABYLON.Vector3.Zero();
  15691. _this._scaling = BABYLON.Vector3.One();
  15692. _this._isDirty = false;
  15693. _this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_NONE;
  15694. _this.scalingDeterminant = 1;
  15695. _this.infiniteDistance = false;
  15696. _this.position = BABYLON.Vector3.Zero();
  15697. _this._localWorld = BABYLON.Matrix.Zero();
  15698. _this._worldMatrix = BABYLON.Matrix.Zero();
  15699. _this._worldMatrixDeterminant = 0;
  15700. _this._absolutePosition = BABYLON.Vector3.Zero();
  15701. _this._pivotMatrix = BABYLON.Matrix.Identity();
  15702. _this._postMultiplyPivotMatrix = false;
  15703. _this._isWorldMatrixFrozen = false;
  15704. /**
  15705. * An event triggered after the world matrix is updated
  15706. * @type {BABYLON.Observable}
  15707. */
  15708. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  15709. _this._nonUniformScaling = false;
  15710. if (isPure) {
  15711. _this.getScene().addTransformNode(_this);
  15712. }
  15713. return _this;
  15714. }
  15715. Object.defineProperty(TransformNode.prototype, "rotation", {
  15716. /**
  15717. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  15718. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  15719. * Default : (0.0, 0.0, 0.0)
  15720. */
  15721. get: function () {
  15722. return this._rotation;
  15723. },
  15724. set: function (newRotation) {
  15725. this._rotation = newRotation;
  15726. },
  15727. enumerable: true,
  15728. configurable: true
  15729. });
  15730. Object.defineProperty(TransformNode.prototype, "scaling", {
  15731. /**
  15732. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  15733. * Default : (1.0, 1.0, 1.0)
  15734. */
  15735. get: function () {
  15736. return this._scaling;
  15737. },
  15738. /**
  15739. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  15740. * Default : (1.0, 1.0, 1.0)
  15741. */
  15742. set: function (newScaling) {
  15743. this._scaling = newScaling;
  15744. },
  15745. enumerable: true,
  15746. configurable: true
  15747. });
  15748. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  15749. /**
  15750. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  15751. * It's null by default.
  15752. * 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)
  15753. */
  15754. get: function () {
  15755. return this._rotationQuaternion;
  15756. },
  15757. set: function (quaternion) {
  15758. this._rotationQuaternion = quaternion;
  15759. //reset the rotation vector.
  15760. if (quaternion && this.rotation.length()) {
  15761. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  15762. }
  15763. },
  15764. enumerable: true,
  15765. configurable: true
  15766. });
  15767. /**
  15768. * Returns the latest update of the World matrix
  15769. * Returns a Matrix.
  15770. */
  15771. TransformNode.prototype.getWorldMatrix = function () {
  15772. if (this._currentRenderId !== this.getScene().getRenderId()) {
  15773. this.computeWorldMatrix();
  15774. }
  15775. return this._worldMatrix;
  15776. };
  15777. /**
  15778. * Returns the latest update of the World matrix determinant.
  15779. */
  15780. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  15781. return this._worldMatrixDeterminant;
  15782. };
  15783. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  15784. /**
  15785. * Returns directly the latest state of the mesh World matrix.
  15786. * A Matrix is returned.
  15787. */
  15788. get: function () {
  15789. return this._worldMatrix;
  15790. },
  15791. enumerable: true,
  15792. configurable: true
  15793. });
  15794. /**
  15795. * Copies the paramater passed Matrix into the mesh Pose matrix.
  15796. * Returns the AbstractMesh.
  15797. */
  15798. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  15799. this._poseMatrix.copyFrom(matrix);
  15800. return this;
  15801. };
  15802. /**
  15803. * Returns the mesh Pose matrix.
  15804. * Returned object : Matrix
  15805. */
  15806. TransformNode.prototype.getPoseMatrix = function () {
  15807. return this._poseMatrix;
  15808. };
  15809. TransformNode.prototype._isSynchronized = function () {
  15810. if (this._isDirty) {
  15811. return false;
  15812. }
  15813. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE)
  15814. return false;
  15815. if (this._cache.pivotMatrixUpdated) {
  15816. return false;
  15817. }
  15818. if (this.infiniteDistance) {
  15819. return false;
  15820. }
  15821. if (!this._cache.position.equals(this.position))
  15822. return false;
  15823. if (this.rotationQuaternion) {
  15824. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  15825. return false;
  15826. }
  15827. if (!this._cache.rotation.equals(this.rotation))
  15828. return false;
  15829. if (!this._cache.scaling.equals(this.scaling))
  15830. return false;
  15831. return true;
  15832. };
  15833. TransformNode.prototype._initCache = function () {
  15834. _super.prototype._initCache.call(this);
  15835. this._cache.localMatrixUpdated = false;
  15836. this._cache.position = BABYLON.Vector3.Zero();
  15837. this._cache.scaling = BABYLON.Vector3.Zero();
  15838. this._cache.rotation = BABYLON.Vector3.Zero();
  15839. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  15840. this._cache.billboardMode = -1;
  15841. };
  15842. TransformNode.prototype.markAsDirty = function (property) {
  15843. if (property === "rotation") {
  15844. this.rotationQuaternion = null;
  15845. }
  15846. this._currentRenderId = Number.MAX_VALUE;
  15847. this._isDirty = true;
  15848. return this;
  15849. };
  15850. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  15851. /**
  15852. * Returns the current mesh absolute position.
  15853. * Retuns a Vector3.
  15854. */
  15855. get: function () {
  15856. return this._absolutePosition;
  15857. },
  15858. enumerable: true,
  15859. configurable: true
  15860. });
  15861. /**
  15862. * Sets a new matrix to apply before all other transformation
  15863. * @param matrix defines the transform matrix
  15864. * @returns the current TransformNode
  15865. */
  15866. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  15867. return this.setPivotMatrix(matrix, false);
  15868. };
  15869. /**
  15870. * Sets a new pivot matrix to the current node
  15871. * @param matrix defines the new pivot matrix to use
  15872. * @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
  15873. * @returns the current TransformNode
  15874. */
  15875. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  15876. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  15877. this._pivotMatrix = matrix.clone();
  15878. this._cache.pivotMatrixUpdated = true;
  15879. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  15880. if (this._postMultiplyPivotMatrix) {
  15881. if (!this._pivotMatrixInverse) {
  15882. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  15883. }
  15884. else {
  15885. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  15886. }
  15887. }
  15888. return this;
  15889. };
  15890. /**
  15891. * Returns the mesh pivot matrix.
  15892. * Default : Identity.
  15893. * A Matrix is returned.
  15894. */
  15895. TransformNode.prototype.getPivotMatrix = function () {
  15896. return this._pivotMatrix;
  15897. };
  15898. /**
  15899. * Prevents the World matrix to be computed any longer.
  15900. * Returns the AbstractMesh.
  15901. */
  15902. TransformNode.prototype.freezeWorldMatrix = function () {
  15903. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  15904. this.computeWorldMatrix(true);
  15905. this._isWorldMatrixFrozen = true;
  15906. return this;
  15907. };
  15908. /**
  15909. * Allows back the World matrix computation.
  15910. * Returns the AbstractMesh.
  15911. */
  15912. TransformNode.prototype.unfreezeWorldMatrix = function () {
  15913. this._isWorldMatrixFrozen = false;
  15914. this.computeWorldMatrix(true);
  15915. return this;
  15916. };
  15917. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  15918. /**
  15919. * True if the World matrix has been frozen.
  15920. * Returns a boolean.
  15921. */
  15922. get: function () {
  15923. return this._isWorldMatrixFrozen;
  15924. },
  15925. enumerable: true,
  15926. configurable: true
  15927. });
  15928. /**
  15929. * Retuns the mesh absolute position in the World.
  15930. * Returns a Vector3.
  15931. */
  15932. TransformNode.prototype.getAbsolutePosition = function () {
  15933. this.computeWorldMatrix();
  15934. return this._absolutePosition;
  15935. };
  15936. /**
  15937. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  15938. * Returns the AbstractMesh.
  15939. */
  15940. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  15941. if (!absolutePosition) {
  15942. return this;
  15943. }
  15944. var absolutePositionX;
  15945. var absolutePositionY;
  15946. var absolutePositionZ;
  15947. if (absolutePosition.x === undefined) {
  15948. if (arguments.length < 3) {
  15949. return this;
  15950. }
  15951. absolutePositionX = arguments[0];
  15952. absolutePositionY = arguments[1];
  15953. absolutePositionZ = arguments[2];
  15954. }
  15955. else {
  15956. absolutePositionX = absolutePosition.x;
  15957. absolutePositionY = absolutePosition.y;
  15958. absolutePositionZ = absolutePosition.z;
  15959. }
  15960. if (this.parent) {
  15961. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  15962. invertParentWorldMatrix.invert();
  15963. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  15964. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  15965. }
  15966. else {
  15967. this.position.x = absolutePositionX;
  15968. this.position.y = absolutePositionY;
  15969. this.position.z = absolutePositionZ;
  15970. }
  15971. return this;
  15972. };
  15973. /**
  15974. * Sets the mesh position in its local space.
  15975. * Returns the AbstractMesh.
  15976. */
  15977. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  15978. this.computeWorldMatrix();
  15979. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  15980. return this;
  15981. };
  15982. /**
  15983. * Returns the mesh position in the local space from the current World matrix values.
  15984. * Returns a new Vector3.
  15985. */
  15986. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  15987. this.computeWorldMatrix();
  15988. var invLocalWorldMatrix = this._localWorld.clone();
  15989. invLocalWorldMatrix.invert();
  15990. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  15991. };
  15992. /**
  15993. * Translates the mesh along the passed Vector3 in its local space.
  15994. * Returns the AbstractMesh.
  15995. */
  15996. TransformNode.prototype.locallyTranslate = function (vector3) {
  15997. this.computeWorldMatrix(true);
  15998. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  15999. return this;
  16000. };
  16001. /**
  16002. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  16003. * @param targetPoint the position (must be in same space as current mesh) to look at
  16004. * @param yawCor optional yaw (y-axis) correction in radians
  16005. * @param pitchCor optional pitch (x-axis) correction in radians
  16006. * @param rollCor optional roll (z-axis) correction in radians
  16007. * @param space the choosen space of the target
  16008. * @returns the TransformNode.
  16009. */
  16010. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  16011. if (yawCor === void 0) { yawCor = 0; }
  16012. if (pitchCor === void 0) { pitchCor = 0; }
  16013. if (rollCor === void 0) { rollCor = 0; }
  16014. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  16015. var dv = BABYLON.AbstractMesh._lookAtVectorCache;
  16016. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  16017. targetPoint.subtractToRef(pos, dv);
  16018. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  16019. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  16020. var pitch = Math.atan2(dv.y, len);
  16021. if (this.rotationQuaternion) {
  16022. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  16023. }
  16024. else {
  16025. this.rotation.x = pitch + pitchCor;
  16026. this.rotation.y = yaw + yawCor;
  16027. this.rotation.z = rollCor;
  16028. }
  16029. return this;
  16030. };
  16031. /**
  16032. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  16033. * This Vector3 is expressed in the World space.
  16034. */
  16035. TransformNode.prototype.getDirection = function (localAxis) {
  16036. var result = BABYLON.Vector3.Zero();
  16037. this.getDirectionToRef(localAxis, result);
  16038. return result;
  16039. };
  16040. /**
  16041. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  16042. * localAxis is expressed in the mesh local space.
  16043. * result is computed in the Wordl space from the mesh World matrix.
  16044. * Returns the AbstractMesh.
  16045. */
  16046. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  16047. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  16048. return this;
  16049. };
  16050. /**
  16051. * Sets a new pivot point to the current node
  16052. * @param point defines the new pivot point to use
  16053. * @param space defines if the point is in world or local space (local by default)
  16054. * @returns the current TransformNode
  16055. */
  16056. TransformNode.prototype.setPivotPoint = function (point, space) {
  16057. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  16058. if (this.getScene().getRenderId() == 0) {
  16059. this.computeWorldMatrix(true);
  16060. }
  16061. var wm = this.getWorldMatrix();
  16062. if (space == BABYLON.Space.WORLD) {
  16063. var tmat = BABYLON.Tmp.Matrix[0];
  16064. wm.invertToRef(tmat);
  16065. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  16066. }
  16067. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  16068. };
  16069. /**
  16070. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  16071. */
  16072. TransformNode.prototype.getPivotPoint = function () {
  16073. var point = BABYLON.Vector3.Zero();
  16074. this.getPivotPointToRef(point);
  16075. return point;
  16076. };
  16077. /**
  16078. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  16079. * Returns the AbstractMesh.
  16080. */
  16081. TransformNode.prototype.getPivotPointToRef = function (result) {
  16082. result.x = -this._pivotMatrix.m[12];
  16083. result.y = -this._pivotMatrix.m[13];
  16084. result.z = -this._pivotMatrix.m[14];
  16085. return this;
  16086. };
  16087. /**
  16088. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  16089. */
  16090. TransformNode.prototype.getAbsolutePivotPoint = function () {
  16091. var point = BABYLON.Vector3.Zero();
  16092. this.getAbsolutePivotPointToRef(point);
  16093. return point;
  16094. };
  16095. /**
  16096. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  16097. * Returns the AbstractMesh.
  16098. */
  16099. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  16100. result.x = this._pivotMatrix.m[12];
  16101. result.y = this._pivotMatrix.m[13];
  16102. result.z = this._pivotMatrix.m[14];
  16103. this.getPivotPointToRef(result);
  16104. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  16105. return this;
  16106. };
  16107. /**
  16108. * Defines the passed node as the parent of the current node.
  16109. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  16110. * Returns the TransformNode.
  16111. */
  16112. TransformNode.prototype.setParent = function (node) {
  16113. if (node === null) {
  16114. var rotation = BABYLON.Tmp.Quaternion[0];
  16115. var position = BABYLON.Tmp.Vector3[0];
  16116. var scale = BABYLON.Tmp.Vector3[1];
  16117. if (this.parent && this.parent.computeWorldMatrix) {
  16118. this.parent.computeWorldMatrix(true);
  16119. }
  16120. this.computeWorldMatrix(true);
  16121. this.getWorldMatrix().decompose(scale, rotation, position);
  16122. if (this.rotationQuaternion) {
  16123. this.rotationQuaternion.copyFrom(rotation);
  16124. }
  16125. else {
  16126. rotation.toEulerAnglesToRef(this.rotation);
  16127. }
  16128. this.scaling.x = scale.x;
  16129. this.scaling.y = scale.y;
  16130. this.scaling.z = scale.z;
  16131. this.position.x = position.x;
  16132. this.position.y = position.y;
  16133. this.position.z = position.z;
  16134. }
  16135. else {
  16136. var rotation = BABYLON.Tmp.Quaternion[0];
  16137. var position = BABYLON.Tmp.Vector3[0];
  16138. var scale = BABYLON.Tmp.Vector3[1];
  16139. var diffMatrix = BABYLON.Tmp.Matrix[0];
  16140. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  16141. this.computeWorldMatrix(true);
  16142. node.computeWorldMatrix(true);
  16143. node.getWorldMatrix().invertToRef(invParentMatrix);
  16144. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  16145. diffMatrix.decompose(scale, rotation, position);
  16146. if (this.rotationQuaternion) {
  16147. this.rotationQuaternion.copyFrom(rotation);
  16148. }
  16149. else {
  16150. rotation.toEulerAnglesToRef(this.rotation);
  16151. }
  16152. this.position.x = position.x;
  16153. this.position.y = position.y;
  16154. this.position.z = position.z;
  16155. this.scaling.x = scale.x;
  16156. this.scaling.y = scale.y;
  16157. this.scaling.z = scale.z;
  16158. }
  16159. this.parent = node;
  16160. return this;
  16161. };
  16162. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  16163. get: function () {
  16164. return this._nonUniformScaling;
  16165. },
  16166. enumerable: true,
  16167. configurable: true
  16168. });
  16169. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  16170. if (this._nonUniformScaling === value) {
  16171. return false;
  16172. }
  16173. this._nonUniformScaling = true;
  16174. return true;
  16175. };
  16176. /**
  16177. * Attach the current TransformNode to another TransformNode associated with a bone
  16178. * @param bone Bone affecting the TransformNode
  16179. * @param affectedTransformNode TransformNode associated with the bone
  16180. */
  16181. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  16182. this._transformToBoneReferal = affectedTransformNode;
  16183. this.parent = bone;
  16184. if (bone.getWorldMatrix().determinant() < 0) {
  16185. this.scalingDeterminant *= -1;
  16186. }
  16187. return this;
  16188. };
  16189. TransformNode.prototype.detachFromBone = function () {
  16190. if (!this.parent) {
  16191. return this;
  16192. }
  16193. if (this.parent.getWorldMatrix().determinant() < 0) {
  16194. this.scalingDeterminant *= -1;
  16195. }
  16196. this._transformToBoneReferal = null;
  16197. this.parent = null;
  16198. return this;
  16199. };
  16200. /**
  16201. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  16202. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  16203. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  16204. * The passed axis is also normalized.
  16205. * Returns the AbstractMesh.
  16206. */
  16207. TransformNode.prototype.rotate = function (axis, amount, space) {
  16208. axis.normalize();
  16209. if (!this.rotationQuaternion) {
  16210. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  16211. this.rotation = BABYLON.Vector3.Zero();
  16212. }
  16213. var rotationQuaternion;
  16214. if (!space || space === BABYLON.Space.LOCAL) {
  16215. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  16216. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  16217. }
  16218. else {
  16219. if (this.parent) {
  16220. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  16221. invertParentWorldMatrix.invert();
  16222. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  16223. }
  16224. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  16225. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  16226. }
  16227. return this;
  16228. };
  16229. /**
  16230. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  16231. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  16232. * The passed axis is also normalized.
  16233. * Returns the AbstractMesh.
  16234. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  16235. */
  16236. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  16237. axis.normalize();
  16238. if (!this.rotationQuaternion) {
  16239. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  16240. this.rotation.copyFromFloats(0, 0, 0);
  16241. }
  16242. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  16243. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  16244. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  16245. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  16246. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  16247. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  16248. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  16249. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  16250. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  16251. return this;
  16252. };
  16253. /**
  16254. * Translates the mesh along the axis vector for the passed distance in the given space.
  16255. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  16256. * Returns the AbstractMesh.
  16257. */
  16258. TransformNode.prototype.translate = function (axis, distance, space) {
  16259. var displacementVector = axis.scale(distance);
  16260. if (!space || space === BABYLON.Space.LOCAL) {
  16261. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  16262. this.setPositionWithLocalVector(tempV3);
  16263. }
  16264. else {
  16265. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  16266. }
  16267. return this;
  16268. };
  16269. /**
  16270. * Adds a rotation step to the mesh current rotation.
  16271. * x, y, z are Euler angles expressed in radians.
  16272. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  16273. * This means this rotation is made in the mesh local space only.
  16274. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  16275. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  16276. * ```javascript
  16277. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  16278. * ```
  16279. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  16280. * 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.
  16281. * Returns the AbstractMesh.
  16282. */
  16283. TransformNode.prototype.addRotation = function (x, y, z) {
  16284. var rotationQuaternion;
  16285. if (this.rotationQuaternion) {
  16286. rotationQuaternion = this.rotationQuaternion;
  16287. }
  16288. else {
  16289. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  16290. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  16291. }
  16292. var accumulation = BABYLON.Tmp.Quaternion[0];
  16293. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  16294. rotationQuaternion.multiplyInPlace(accumulation);
  16295. if (!this.rotationQuaternion) {
  16296. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  16297. }
  16298. return this;
  16299. };
  16300. /**
  16301. * Computes the mesh World matrix and returns it.
  16302. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  16303. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  16304. * If the parameter `force`is set to `true`, the actual computation is done.
  16305. * Returns the mesh World Matrix.
  16306. */
  16307. TransformNode.prototype.computeWorldMatrix = function (force) {
  16308. if (this._isWorldMatrixFrozen) {
  16309. return this._worldMatrix;
  16310. }
  16311. if (!force && this.isSynchronized(true)) {
  16312. return this._worldMatrix;
  16313. }
  16314. this._cache.position.copyFrom(this.position);
  16315. this._cache.scaling.copyFrom(this.scaling);
  16316. this._cache.pivotMatrixUpdated = false;
  16317. this._cache.billboardMode = this.billboardMode;
  16318. this._currentRenderId = this.getScene().getRenderId();
  16319. this._isDirty = false;
  16320. // Scaling
  16321. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  16322. // Rotation
  16323. //rotate, if quaternion is set and rotation was used
  16324. if (this.rotationQuaternion) {
  16325. var len = this.rotation.length();
  16326. if (len) {
  16327. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  16328. this.rotation.copyFromFloats(0, 0, 0);
  16329. }
  16330. }
  16331. if (this.rotationQuaternion) {
  16332. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  16333. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  16334. }
  16335. else {
  16336. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  16337. this._cache.rotation.copyFrom(this.rotation);
  16338. }
  16339. // Translation
  16340. var camera = this.getScene().activeCamera;
  16341. if (this.infiniteDistance && !this.parent && camera) {
  16342. var cameraWorldMatrix = camera.getWorldMatrix();
  16343. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  16344. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  16345. }
  16346. else {
  16347. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  16348. }
  16349. // Composing transformations
  16350. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  16351. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  16352. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  16353. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE && camera) {
  16354. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_ALL) !== BABYLON.AbstractMesh.BILLBOARDMODE_ALL) {
  16355. // Need to decompose each rotation here
  16356. var currentPosition = BABYLON.Tmp.Vector3[3];
  16357. if (this.parent && this.parent.getWorldMatrix) {
  16358. if (this._transformToBoneReferal) {
  16359. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  16360. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  16361. }
  16362. else {
  16363. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  16364. }
  16365. }
  16366. else {
  16367. currentPosition.copyFrom(this.position);
  16368. }
  16369. currentPosition.subtractInPlace(camera.globalPosition);
  16370. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  16371. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_X) === BABYLON.AbstractMesh.BILLBOARDMODE_X) {
  16372. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  16373. }
  16374. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Y) === BABYLON.AbstractMesh.BILLBOARDMODE_Y) {
  16375. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  16376. }
  16377. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Z) === BABYLON.AbstractMesh.BILLBOARDMODE_Z) {
  16378. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  16379. }
  16380. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  16381. }
  16382. else {
  16383. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  16384. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  16385. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  16386. }
  16387. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  16388. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  16389. }
  16390. // Local world
  16391. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  16392. // Parent
  16393. if (this.parent && this.parent.getWorldMatrix) {
  16394. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE) {
  16395. if (this._transformToBoneReferal) {
  16396. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  16397. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  16398. }
  16399. else {
  16400. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  16401. }
  16402. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  16403. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  16404. this._worldMatrix.copyFrom(this._localWorld);
  16405. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  16406. }
  16407. else {
  16408. if (this._transformToBoneReferal) {
  16409. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  16410. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  16411. }
  16412. else {
  16413. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  16414. }
  16415. }
  16416. this._markSyncedWithParent();
  16417. }
  16418. else {
  16419. this._worldMatrix.copyFrom(this._localWorld);
  16420. }
  16421. // Post multiply inverse of pivotMatrix
  16422. if (this._postMultiplyPivotMatrix) {
  16423. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  16424. }
  16425. // Normal matrix
  16426. if (this.scaling.isNonUniform) {
  16427. this._updateNonUniformScalingState(true);
  16428. }
  16429. else if (this.parent && this.parent._nonUniformScaling) {
  16430. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  16431. }
  16432. else {
  16433. this._updateNonUniformScalingState(false);
  16434. }
  16435. this._afterComputeWorldMatrix();
  16436. // Absolute position
  16437. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  16438. // Callbacks
  16439. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  16440. if (!this._poseMatrix) {
  16441. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  16442. }
  16443. // Cache the determinant
  16444. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  16445. return this._worldMatrix;
  16446. };
  16447. TransformNode.prototype._afterComputeWorldMatrix = function () {
  16448. };
  16449. /**
  16450. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  16451. * @param func: callback function to add
  16452. *
  16453. * Returns the TransformNode.
  16454. */
  16455. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  16456. this.onAfterWorldMatrixUpdateObservable.add(func);
  16457. return this;
  16458. };
  16459. /**
  16460. * Removes a registered callback function.
  16461. * Returns the TransformNode.
  16462. */
  16463. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  16464. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  16465. return this;
  16466. };
  16467. /**
  16468. * Clone the current transform node
  16469. * Returns the new transform node
  16470. * @param name Name of the new clone
  16471. * @param newParent New parent for the clone
  16472. * @param doNotCloneChildren Do not clone children hierarchy
  16473. */
  16474. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  16475. var _this = this;
  16476. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  16477. result.name = name;
  16478. result.id = name;
  16479. if (newParent) {
  16480. result.parent = newParent;
  16481. }
  16482. if (!doNotCloneChildren) {
  16483. // Children
  16484. var directDescendants = this.getDescendants(true);
  16485. for (var index = 0; index < directDescendants.length; index++) {
  16486. var child = directDescendants[index];
  16487. if (child.clone) {
  16488. child.clone(name + "." + child.name, result);
  16489. }
  16490. }
  16491. }
  16492. return result;
  16493. };
  16494. TransformNode.prototype.serialize = function (currentSerializationObject) {
  16495. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  16496. serializationObject.type = this.getClassName();
  16497. // Parent
  16498. if (this.parent) {
  16499. serializationObject.parentId = this.parent.id;
  16500. }
  16501. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  16502. serializationObject.tags = BABYLON.Tags.GetTags(this);
  16503. }
  16504. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  16505. serializationObject.isEnabled = this.isEnabled();
  16506. // Parent
  16507. if (this.parent) {
  16508. serializationObject.parentId = this.parent.id;
  16509. }
  16510. return serializationObject;
  16511. };
  16512. // Statics
  16513. /**
  16514. * Returns a new TransformNode object parsed from the source provided.
  16515. * The parameter `parsedMesh` is the source.
  16516. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  16517. */
  16518. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  16519. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  16520. if (BABYLON.Tags) {
  16521. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  16522. }
  16523. if (parsedTransformNode.localMatrix) {
  16524. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  16525. }
  16526. else if (parsedTransformNode.pivotMatrix) {
  16527. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  16528. }
  16529. transformNode.setEnabled(parsedTransformNode.isEnabled);
  16530. // Parent
  16531. if (parsedTransformNode.parentId) {
  16532. transformNode._waitingParentId = parsedTransformNode.parentId;
  16533. }
  16534. return transformNode;
  16535. };
  16536. /**
  16537. * Disposes the TransformNode.
  16538. * By default, all the children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  16539. * Returns nothing.
  16540. */
  16541. TransformNode.prototype.dispose = function (doNotRecurse) {
  16542. // Animations
  16543. this.getScene().stopAnimation(this);
  16544. // Remove from scene
  16545. this.getScene().removeTransformNode(this);
  16546. if (!doNotRecurse) {
  16547. // Children
  16548. var objects = this.getDescendants(true);
  16549. for (var index = 0; index < objects.length; index++) {
  16550. objects[index].dispose();
  16551. }
  16552. }
  16553. else {
  16554. var childMeshes = this.getChildMeshes(true);
  16555. for (index = 0; index < childMeshes.length; index++) {
  16556. var child = childMeshes[index];
  16557. child.parent = null;
  16558. child.computeWorldMatrix(true);
  16559. }
  16560. }
  16561. this.onAfterWorldMatrixUpdateObservable.clear();
  16562. _super.prototype.dispose.call(this);
  16563. };
  16564. // Statics
  16565. TransformNode.BILLBOARDMODE_NONE = 0;
  16566. TransformNode.BILLBOARDMODE_X = 1;
  16567. TransformNode.BILLBOARDMODE_Y = 2;
  16568. TransformNode.BILLBOARDMODE_Z = 4;
  16569. TransformNode.BILLBOARDMODE_ALL = 7;
  16570. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  16571. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  16572. __decorate([
  16573. BABYLON.serializeAsVector3()
  16574. ], TransformNode.prototype, "_rotation", void 0);
  16575. __decorate([
  16576. BABYLON.serializeAsQuaternion()
  16577. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  16578. __decorate([
  16579. BABYLON.serializeAsVector3()
  16580. ], TransformNode.prototype, "_scaling", void 0);
  16581. __decorate([
  16582. BABYLON.serialize()
  16583. ], TransformNode.prototype, "billboardMode", void 0);
  16584. __decorate([
  16585. BABYLON.serialize()
  16586. ], TransformNode.prototype, "scalingDeterminant", void 0);
  16587. __decorate([
  16588. BABYLON.serialize()
  16589. ], TransformNode.prototype, "infiniteDistance", void 0);
  16590. __decorate([
  16591. BABYLON.serializeAsVector3()
  16592. ], TransformNode.prototype, "position", void 0);
  16593. return TransformNode;
  16594. }(BABYLON.Node));
  16595. BABYLON.TransformNode = TransformNode;
  16596. })(BABYLON || (BABYLON = {}));
  16597. //# sourceMappingURL=babylon.transformNode.js.map
  16598. var BABYLON;
  16599. (function (BABYLON) {
  16600. var AbstractMesh = /** @class */ (function (_super) {
  16601. __extends(AbstractMesh, _super);
  16602. // Constructor
  16603. function AbstractMesh(name, scene) {
  16604. if (scene === void 0) { scene = null; }
  16605. var _this = _super.call(this, name, scene, false) || this;
  16606. _this._facetNb = 0; // facet number
  16607. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  16608. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  16609. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  16610. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  16611. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  16612. _this._subDiv = {
  16613. max: 1,
  16614. X: 1,
  16615. Y: 1,
  16616. Z: 1
  16617. };
  16618. _this._facetDepthSort = false; // is the facet depth sort to be computed
  16619. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  16620. // Events
  16621. /**
  16622. * An event triggered when this mesh collides with another one
  16623. * @type {BABYLON.Observable}
  16624. */
  16625. _this.onCollideObservable = new BABYLON.Observable();
  16626. /**
  16627. * An event triggered when the collision's position changes
  16628. * @type {BABYLON.Observable}
  16629. */
  16630. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  16631. /**
  16632. * An event triggered when material is changed
  16633. * @type {BABYLON.Observable}
  16634. */
  16635. _this.onMaterialChangedObservable = new BABYLON.Observable();
  16636. // Properties
  16637. _this.definedFacingForward = true; // orientation for POV movement & rotation
  16638. /**
  16639. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  16640. * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  16641. * or
  16642. * 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.
  16643. * for more info check WebGl documentations
  16644. */
  16645. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  16646. /**
  16647. * 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:
  16648. * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  16649. * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  16650. * 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.
  16651. */
  16652. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  16653. /**
  16654. * 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.
  16655. * The default value is -1 which means don't break the query and wait till the result.
  16656. */
  16657. _this.occlusionRetryCount = -1;
  16658. _this._occlusionInternalRetryCounter = 0;
  16659. _this._isOccluded = false;
  16660. _this._isOcclusionQueryInProgress = false;
  16661. _this._visibility = 1.0;
  16662. _this.alphaIndex = Number.MAX_VALUE;
  16663. _this.isVisible = true;
  16664. _this.isPickable = true;
  16665. _this.showBoundingBox = false;
  16666. _this.showSubMeshesBoundingBox = false;
  16667. _this.isBlocker = false;
  16668. _this.enablePointerMoveEvents = false;
  16669. _this.renderingGroupId = 0;
  16670. _this._receiveShadows = false;
  16671. _this.renderOutline = false;
  16672. _this.outlineColor = BABYLON.Color3.Red();
  16673. _this.outlineWidth = 0.02;
  16674. _this.renderOverlay = false;
  16675. _this.overlayColor = BABYLON.Color3.Red();
  16676. _this.overlayAlpha = 0.5;
  16677. _this._hasVertexAlpha = false;
  16678. _this._useVertexColors = true;
  16679. _this._computeBonesUsingShaders = true;
  16680. _this._numBoneInfluencers = 4;
  16681. _this._applyFog = true;
  16682. _this.useOctreeForRenderingSelection = true;
  16683. _this.useOctreeForPicking = true;
  16684. _this.useOctreeForCollisions = true;
  16685. _this._layerMask = 0x0FFFFFFF;
  16686. /**
  16687. * True if the mesh must be rendered in any case.
  16688. */
  16689. _this.alwaysSelectAsActiveMesh = false;
  16690. /**
  16691. * This scene's action manager
  16692. * @type {BABYLON.ActionManager}
  16693. */
  16694. _this.actionManager = null;
  16695. // Physics
  16696. _this.physicsImpostor = null;
  16697. // Collisions
  16698. _this._checkCollisions = false;
  16699. _this._collisionMask = -1;
  16700. _this._collisionGroup = -1;
  16701. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  16702. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  16703. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  16704. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  16705. // Edges
  16706. _this.edgesWidth = 1;
  16707. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  16708. // Cache
  16709. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  16710. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  16711. _this._isDisposed = false;
  16712. _this._renderId = 0;
  16713. _this._intersectionsInProgress = new Array();
  16714. _this._unIndexed = false;
  16715. _this._lightSources = new Array();
  16716. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  16717. if (collidedMesh === void 0) { collidedMesh = null; }
  16718. //TODO move this to the collision coordinator!
  16719. if (_this.getScene().workerCollisions)
  16720. newPosition.multiplyInPlace(_this._collider._radius);
  16721. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  16722. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  16723. _this.position.addInPlace(_this._diffPositionForCollisions);
  16724. }
  16725. if (collidedMesh) {
  16726. _this.onCollideObservable.notifyObservers(collidedMesh);
  16727. }
  16728. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  16729. };
  16730. _this.getScene().addMesh(_this);
  16731. _this._resyncLightSources();
  16732. return _this;
  16733. }
  16734. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  16735. get: function () {
  16736. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  16737. },
  16738. enumerable: true,
  16739. configurable: true
  16740. });
  16741. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  16742. get: function () {
  16743. return BABYLON.TransformNode.BILLBOARDMODE_X;
  16744. },
  16745. enumerable: true,
  16746. configurable: true
  16747. });
  16748. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  16749. get: function () {
  16750. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  16751. },
  16752. enumerable: true,
  16753. configurable: true
  16754. });
  16755. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  16756. get: function () {
  16757. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  16758. },
  16759. enumerable: true,
  16760. configurable: true
  16761. });
  16762. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  16763. get: function () {
  16764. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  16765. },
  16766. enumerable: true,
  16767. configurable: true
  16768. });
  16769. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  16770. /**
  16771. * Read-only : the number of facets in the mesh
  16772. */
  16773. get: function () {
  16774. return this._facetNb;
  16775. },
  16776. enumerable: true,
  16777. configurable: true
  16778. });
  16779. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  16780. /**
  16781. * The number (integer) of subdivisions per axis in the partioning space
  16782. */
  16783. get: function () {
  16784. return this._partitioningSubdivisions;
  16785. },
  16786. set: function (nb) {
  16787. this._partitioningSubdivisions = nb;
  16788. },
  16789. enumerable: true,
  16790. configurable: true
  16791. });
  16792. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  16793. /**
  16794. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  16795. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  16796. */
  16797. get: function () {
  16798. return this._partitioningBBoxRatio;
  16799. },
  16800. set: function (ratio) {
  16801. this._partitioningBBoxRatio = ratio;
  16802. },
  16803. enumerable: true,
  16804. configurable: true
  16805. });
  16806. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  16807. /**
  16808. * Boolean : must the facet be depth sorted on next call to `updateFacetData()` ?
  16809. * Works only for updatable meshes.
  16810. * Doesn't work with multi-materials.
  16811. */
  16812. get: function () {
  16813. return this._facetDepthSort;
  16814. },
  16815. set: function (sort) {
  16816. this._facetDepthSort = sort;
  16817. },
  16818. enumerable: true,
  16819. configurable: true
  16820. });
  16821. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  16822. /**
  16823. * The location (Vector3) where the facet depth sort must be computed from.
  16824. * By default, the active camera position.
  16825. * Used only when facet depth sort is enabled.
  16826. */
  16827. get: function () {
  16828. return this._facetDepthSortFrom;
  16829. },
  16830. set: function (location) {
  16831. this._facetDepthSortFrom = location;
  16832. },
  16833. enumerable: true,
  16834. configurable: true
  16835. });
  16836. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  16837. /**
  16838. * Read-only boolean : is the feature facetData enabled ?
  16839. */
  16840. get: function () {
  16841. return this._facetDataEnabled;
  16842. },
  16843. enumerable: true,
  16844. configurable: true
  16845. });
  16846. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  16847. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  16848. return false;
  16849. }
  16850. this._markSubMeshesAsMiscDirty();
  16851. return true;
  16852. };
  16853. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  16854. set: function (callback) {
  16855. if (this._onCollideObserver) {
  16856. this.onCollideObservable.remove(this._onCollideObserver);
  16857. }
  16858. this._onCollideObserver = this.onCollideObservable.add(callback);
  16859. },
  16860. enumerable: true,
  16861. configurable: true
  16862. });
  16863. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  16864. set: function (callback) {
  16865. if (this._onCollisionPositionChangeObserver) {
  16866. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  16867. }
  16868. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  16869. },
  16870. enumerable: true,
  16871. configurable: true
  16872. });
  16873. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  16874. /**
  16875. * Property isOccluded : 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.
  16876. */
  16877. get: function () {
  16878. return this._isOccluded;
  16879. },
  16880. set: function (value) {
  16881. this._isOccluded = value;
  16882. },
  16883. enumerable: true,
  16884. configurable: true
  16885. });
  16886. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  16887. /**
  16888. * Flag to check the progress status of the query
  16889. */
  16890. get: function () {
  16891. return this._isOcclusionQueryInProgress;
  16892. },
  16893. enumerable: true,
  16894. configurable: true
  16895. });
  16896. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  16897. /**
  16898. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  16899. */
  16900. get: function () {
  16901. return this._visibility;
  16902. },
  16903. /**
  16904. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  16905. */
  16906. set: function (value) {
  16907. if (this._visibility === value) {
  16908. return;
  16909. }
  16910. this._visibility = value;
  16911. this._markSubMeshesAsMiscDirty();
  16912. },
  16913. enumerable: true,
  16914. configurable: true
  16915. });
  16916. Object.defineProperty(AbstractMesh.prototype, "material", {
  16917. get: function () {
  16918. return this._material;
  16919. },
  16920. set: function (value) {
  16921. if (this._material === value) {
  16922. return;
  16923. }
  16924. this._material = value;
  16925. if (this.onMaterialChangedObservable.hasObservers) {
  16926. this.onMaterialChangedObservable.notifyObservers(this);
  16927. }
  16928. if (!this.subMeshes) {
  16929. return;
  16930. }
  16931. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  16932. var subMesh = _a[_i];
  16933. subMesh.setEffect(null);
  16934. }
  16935. },
  16936. enumerable: true,
  16937. configurable: true
  16938. });
  16939. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  16940. get: function () {
  16941. return this._receiveShadows;
  16942. },
  16943. set: function (value) {
  16944. if (this._receiveShadows === value) {
  16945. return;
  16946. }
  16947. this._receiveShadows = value;
  16948. this._markSubMeshesAsLightDirty();
  16949. },
  16950. enumerable: true,
  16951. configurable: true
  16952. });
  16953. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  16954. get: function () {
  16955. return this._hasVertexAlpha;
  16956. },
  16957. set: function (value) {
  16958. if (this._hasVertexAlpha === value) {
  16959. return;
  16960. }
  16961. this._hasVertexAlpha = value;
  16962. this._markSubMeshesAsAttributesDirty();
  16963. this._markSubMeshesAsMiscDirty();
  16964. },
  16965. enumerable: true,
  16966. configurable: true
  16967. });
  16968. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  16969. get: function () {
  16970. return this._useVertexColors;
  16971. },
  16972. set: function (value) {
  16973. if (this._useVertexColors === value) {
  16974. return;
  16975. }
  16976. this._useVertexColors = value;
  16977. this._markSubMeshesAsAttributesDirty();
  16978. },
  16979. enumerable: true,
  16980. configurable: true
  16981. });
  16982. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  16983. get: function () {
  16984. return this._computeBonesUsingShaders;
  16985. },
  16986. set: function (value) {
  16987. if (this._computeBonesUsingShaders === value) {
  16988. return;
  16989. }
  16990. this._computeBonesUsingShaders = value;
  16991. this._markSubMeshesAsAttributesDirty();
  16992. },
  16993. enumerable: true,
  16994. configurable: true
  16995. });
  16996. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  16997. get: function () {
  16998. return this._numBoneInfluencers;
  16999. },
  17000. set: function (value) {
  17001. if (this._numBoneInfluencers === value) {
  17002. return;
  17003. }
  17004. this._numBoneInfluencers = value;
  17005. this._markSubMeshesAsAttributesDirty();
  17006. },
  17007. enumerable: true,
  17008. configurable: true
  17009. });
  17010. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  17011. get: function () {
  17012. return this._applyFog;
  17013. },
  17014. set: function (value) {
  17015. if (this._applyFog === value) {
  17016. return;
  17017. }
  17018. this._applyFog = value;
  17019. this._markSubMeshesAsMiscDirty();
  17020. },
  17021. enumerable: true,
  17022. configurable: true
  17023. });
  17024. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  17025. get: function () {
  17026. return this._layerMask;
  17027. },
  17028. set: function (value) {
  17029. if (value === this._layerMask) {
  17030. return;
  17031. }
  17032. this._layerMask = value;
  17033. this._resyncLightSources();
  17034. },
  17035. enumerable: true,
  17036. configurable: true
  17037. });
  17038. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  17039. get: function () {
  17040. return this._collisionMask;
  17041. },
  17042. set: function (mask) {
  17043. this._collisionMask = !isNaN(mask) ? mask : -1;
  17044. },
  17045. enumerable: true,
  17046. configurable: true
  17047. });
  17048. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  17049. get: function () {
  17050. return this._collisionGroup;
  17051. },
  17052. set: function (mask) {
  17053. this._collisionGroup = !isNaN(mask) ? mask : -1;
  17054. },
  17055. enumerable: true,
  17056. configurable: true
  17057. });
  17058. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  17059. get: function () {
  17060. return null;
  17061. },
  17062. enumerable: true,
  17063. configurable: true
  17064. });
  17065. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  17066. get: function () {
  17067. return this._skeleton;
  17068. },
  17069. set: function (value) {
  17070. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  17071. this._skeleton._unregisterMeshWithPoseMatrix(this);
  17072. }
  17073. if (value && value.needInitialSkinMatrix) {
  17074. value._registerMeshWithPoseMatrix(this);
  17075. }
  17076. this._skeleton = value;
  17077. if (!this._skeleton) {
  17078. this._bonesTransformMatrices = null;
  17079. }
  17080. this._markSubMeshesAsAttributesDirty();
  17081. },
  17082. enumerable: true,
  17083. configurable: true
  17084. });
  17085. /**
  17086. * Boolean : true if the mesh has been disposed.
  17087. */
  17088. AbstractMesh.prototype.isDisposed = function () {
  17089. return this._isDisposed;
  17090. };
  17091. /**
  17092. * Returns the string "AbstractMesh"
  17093. */
  17094. AbstractMesh.prototype.getClassName = function () {
  17095. return "AbstractMesh";
  17096. };
  17097. /**
  17098. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  17099. */
  17100. AbstractMesh.prototype.toString = function (fullDetails) {
  17101. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  17102. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  17103. if (this._skeleton) {
  17104. ret += ", skeleton: " + this._skeleton.name;
  17105. }
  17106. if (fullDetails) {
  17107. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  17108. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  17109. }
  17110. return ret;
  17111. };
  17112. AbstractMesh.prototype._rebuild = function () {
  17113. if (this._occlusionQuery) {
  17114. this._occlusionQuery = null;
  17115. }
  17116. if (this._edgesRenderer) {
  17117. this._edgesRenderer._rebuild();
  17118. }
  17119. if (!this.subMeshes) {
  17120. return;
  17121. }
  17122. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17123. var subMesh = _a[_i];
  17124. subMesh._rebuild();
  17125. }
  17126. };
  17127. AbstractMesh.prototype._resyncLightSources = function () {
  17128. this._lightSources.length = 0;
  17129. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  17130. var light = _a[_i];
  17131. if (!light.isEnabled()) {
  17132. continue;
  17133. }
  17134. if (light.canAffectMesh(this)) {
  17135. this._lightSources.push(light);
  17136. }
  17137. }
  17138. this._markSubMeshesAsLightDirty();
  17139. };
  17140. AbstractMesh.prototype._resyncLighSource = function (light) {
  17141. var isIn = light.isEnabled() && light.canAffectMesh(this);
  17142. var index = this._lightSources.indexOf(light);
  17143. if (index === -1) {
  17144. if (!isIn) {
  17145. return;
  17146. }
  17147. this._lightSources.push(light);
  17148. }
  17149. else {
  17150. if (isIn) {
  17151. return;
  17152. }
  17153. this._lightSources.splice(index, 1);
  17154. }
  17155. this._markSubMeshesAsLightDirty();
  17156. };
  17157. AbstractMesh.prototype._removeLightSource = function (light) {
  17158. var index = this._lightSources.indexOf(light);
  17159. if (index === -1) {
  17160. return;
  17161. }
  17162. this._lightSources.splice(index, 1);
  17163. this._markSubMeshesAsLightDirty();
  17164. };
  17165. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  17166. if (!this.subMeshes) {
  17167. return;
  17168. }
  17169. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17170. var subMesh = _a[_i];
  17171. if (subMesh._materialDefines) {
  17172. func(subMesh._materialDefines);
  17173. }
  17174. }
  17175. };
  17176. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  17177. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  17178. };
  17179. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  17180. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  17181. };
  17182. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  17183. if (!this.subMeshes) {
  17184. return;
  17185. }
  17186. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17187. var subMesh = _a[_i];
  17188. var material = subMesh.getMaterial();
  17189. if (material) {
  17190. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  17191. }
  17192. }
  17193. };
  17194. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  17195. /**
  17196. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  17197. * Default : (1.0, 1.0, 1.0)
  17198. */
  17199. get: function () {
  17200. return this._scaling;
  17201. },
  17202. /**
  17203. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  17204. * Default : (1.0, 1.0, 1.0)
  17205. */
  17206. set: function (newScaling) {
  17207. this._scaling = newScaling;
  17208. if (this.physicsImpostor) {
  17209. this.physicsImpostor.forceUpdate();
  17210. }
  17211. },
  17212. enumerable: true,
  17213. configurable: true
  17214. });
  17215. // Methods
  17216. /**
  17217. * Disables the mesh edger rendering mode.
  17218. * Returns the AbstractMesh.
  17219. */
  17220. AbstractMesh.prototype.disableEdgesRendering = function () {
  17221. if (this._edgesRenderer) {
  17222. this._edgesRenderer.dispose();
  17223. this._edgesRenderer = null;
  17224. }
  17225. return this;
  17226. };
  17227. /**
  17228. * Enables the edge rendering mode on the mesh.
  17229. * This mode makes the mesh edges visible.
  17230. * Returns the AbstractMesh.
  17231. */
  17232. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  17233. if (epsilon === void 0) { epsilon = 0.95; }
  17234. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  17235. this.disableEdgesRendering();
  17236. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  17237. return this;
  17238. };
  17239. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  17240. /**
  17241. * Returns true if the mesh is blocked. Used by the class Mesh.
  17242. * Returns the boolean `false` by default.
  17243. */
  17244. get: function () {
  17245. return false;
  17246. },
  17247. enumerable: true,
  17248. configurable: true
  17249. });
  17250. /**
  17251. * Returns the mesh itself by default, used by the class Mesh.
  17252. * Returned type : AbstractMesh
  17253. */
  17254. AbstractMesh.prototype.getLOD = function (camera) {
  17255. return this;
  17256. };
  17257. /**
  17258. * Returns 0 by default, used by the class Mesh.
  17259. * Returns an integer.
  17260. */
  17261. AbstractMesh.prototype.getTotalVertices = function () {
  17262. return 0;
  17263. };
  17264. /**
  17265. * Returns null by default, used by the class Mesh.
  17266. * Returned type : integer array
  17267. */
  17268. AbstractMesh.prototype.getIndices = function () {
  17269. return null;
  17270. };
  17271. /**
  17272. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  17273. * Returned type : float array or Float32Array
  17274. */
  17275. AbstractMesh.prototype.getVerticesData = function (kind) {
  17276. return null;
  17277. };
  17278. /**
  17279. * Sets the vertex data of the mesh geometry for the requested `kind`.
  17280. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  17281. * The `data` are either a numeric array either a Float32Array.
  17282. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  17283. * 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).
  17284. * Note that a new underlying VertexBuffer object is created each call.
  17285. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  17286. *
  17287. * Possible `kind` values :
  17288. * - BABYLON.VertexBuffer.PositionKind
  17289. * - BABYLON.VertexBuffer.UVKind
  17290. * - BABYLON.VertexBuffer.UV2Kind
  17291. * - BABYLON.VertexBuffer.UV3Kind
  17292. * - BABYLON.VertexBuffer.UV4Kind
  17293. * - BABYLON.VertexBuffer.UV5Kind
  17294. * - BABYLON.VertexBuffer.UV6Kind
  17295. * - BABYLON.VertexBuffer.ColorKind
  17296. * - BABYLON.VertexBuffer.MatricesIndicesKind
  17297. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  17298. * - BABYLON.VertexBuffer.MatricesWeightsKind
  17299. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  17300. *
  17301. * Returns the Mesh.
  17302. */
  17303. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  17304. return this;
  17305. };
  17306. /**
  17307. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  17308. * If the mesh has no geometry, it is simply returned as it is.
  17309. * The `data` are either a numeric array either a Float32Array.
  17310. * No new underlying VertexBuffer object is created.
  17311. * 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.
  17312. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  17313. *
  17314. * Possible `kind` values :
  17315. * - BABYLON.VertexBuffer.PositionKind
  17316. * - BABYLON.VertexBuffer.UVKind
  17317. * - BABYLON.VertexBuffer.UV2Kind
  17318. * - BABYLON.VertexBuffer.UV3Kind
  17319. * - BABYLON.VertexBuffer.UV4Kind
  17320. * - BABYLON.VertexBuffer.UV5Kind
  17321. * - BABYLON.VertexBuffer.UV6Kind
  17322. * - BABYLON.VertexBuffer.ColorKind
  17323. * - BABYLON.VertexBuffer.MatricesIndicesKind
  17324. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  17325. * - BABYLON.VertexBuffer.MatricesWeightsKind
  17326. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  17327. *
  17328. * Returns the Mesh.
  17329. */
  17330. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  17331. return this;
  17332. };
  17333. /**
  17334. * Sets the mesh indices.
  17335. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  17336. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  17337. * This method creates a new index buffer each call.
  17338. * Returns the Mesh.
  17339. */
  17340. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  17341. return this;
  17342. };
  17343. /** Returns false by default, used by the class Mesh.
  17344. * Returns a boolean
  17345. */
  17346. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  17347. return false;
  17348. };
  17349. /**
  17350. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  17351. * Returns a BoundingInfo
  17352. */
  17353. AbstractMesh.prototype.getBoundingInfo = function () {
  17354. if (this._masterMesh) {
  17355. return this._masterMesh.getBoundingInfo();
  17356. }
  17357. if (!this._boundingInfo) {
  17358. // this._boundingInfo is being created here
  17359. this._updateBoundingInfo();
  17360. }
  17361. // cannot be null.
  17362. return this._boundingInfo;
  17363. };
  17364. /**
  17365. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units).
  17366. * @param includeDescendants Take the hierarchy's bounding box instead of the mesh's bounding box.
  17367. */
  17368. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  17369. if (includeDescendants === void 0) { includeDescendants = true; }
  17370. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  17371. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  17372. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  17373. if (maxDimension === 0) {
  17374. return this;
  17375. }
  17376. var scale = 1 / maxDimension;
  17377. this.scaling.scaleInPlace(scale);
  17378. return this;
  17379. };
  17380. /**
  17381. * Sets a mesh new object BoundingInfo.
  17382. * Returns the AbstractMesh.
  17383. */
  17384. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  17385. this._boundingInfo = boundingInfo;
  17386. return this;
  17387. };
  17388. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  17389. get: function () {
  17390. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  17391. },
  17392. enumerable: true,
  17393. configurable: true
  17394. });
  17395. AbstractMesh.prototype._preActivate = function () {
  17396. };
  17397. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  17398. };
  17399. AbstractMesh.prototype._activate = function (renderId) {
  17400. this._renderId = renderId;
  17401. };
  17402. /**
  17403. * Returns the latest update of the World matrix
  17404. * Returns a Matrix.
  17405. */
  17406. AbstractMesh.prototype.getWorldMatrix = function () {
  17407. if (this._masterMesh) {
  17408. return this._masterMesh.getWorldMatrix();
  17409. }
  17410. return _super.prototype.getWorldMatrix.call(this);
  17411. };
  17412. /**
  17413. * Returns the latest update of the World matrix determinant.
  17414. */
  17415. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  17416. if (this._masterMesh) {
  17417. return this._masterMesh._getWorldMatrixDeterminant();
  17418. }
  17419. return _super.prototype._getWorldMatrixDeterminant.call(this);
  17420. };
  17421. // ================================== Point of View Movement =================================
  17422. /**
  17423. * Perform relative position change from the point of view of behind the front of the mesh.
  17424. * This is performed taking into account the meshes current rotation, so you do not have to care.
  17425. * Supports definition of mesh facing forward or backward.
  17426. * @param {number} amountRight
  17427. * @param {number} amountUp
  17428. * @param {number} amountForward
  17429. *
  17430. * Returns the AbstractMesh.
  17431. */
  17432. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  17433. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  17434. return this;
  17435. };
  17436. /**
  17437. * Calculate relative position change from the point of view of behind the front of the mesh.
  17438. * This is performed taking into account the meshes current rotation, so you do not have to care.
  17439. * Supports definition of mesh facing forward or backward.
  17440. * @param {number} amountRight
  17441. * @param {number} amountUp
  17442. * @param {number} amountForward
  17443. *
  17444. * Returns a new Vector3.
  17445. */
  17446. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  17447. var rotMatrix = new BABYLON.Matrix();
  17448. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  17449. rotQuaternion.toRotationMatrix(rotMatrix);
  17450. var translationDelta = BABYLON.Vector3.Zero();
  17451. var defForwardMult = this.definedFacingForward ? -1 : 1;
  17452. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  17453. return translationDelta;
  17454. };
  17455. // ================================== Point of View Rotation =================================
  17456. /**
  17457. * Perform relative rotation change from the point of view of behind the front of the mesh.
  17458. * Supports definition of mesh facing forward or backward.
  17459. * @param {number} flipBack
  17460. * @param {number} twirlClockwise
  17461. * @param {number} tiltRight
  17462. *
  17463. * Returns the AbstractMesh.
  17464. */
  17465. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  17466. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  17467. return this;
  17468. };
  17469. /**
  17470. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  17471. * Supports definition of mesh facing forward or backward.
  17472. * @param {number} flipBack
  17473. * @param {number} twirlClockwise
  17474. * @param {number} tiltRight
  17475. *
  17476. * Returns a new Vector3.
  17477. */
  17478. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  17479. var defForwardMult = this.definedFacingForward ? 1 : -1;
  17480. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  17481. };
  17482. /**
  17483. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  17484. * @param includeDescendants Include bounding info from descendants as well (true by default).
  17485. */
  17486. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants) {
  17487. if (includeDescendants === void 0) { includeDescendants = true; }
  17488. this.computeWorldMatrix(true);
  17489. var min;
  17490. var max;
  17491. var boundingInfo = this.getBoundingInfo();
  17492. if (!this.subMeshes) {
  17493. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  17494. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  17495. }
  17496. else {
  17497. min = boundingInfo.boundingBox.minimumWorld;
  17498. max = boundingInfo.boundingBox.maximumWorld;
  17499. }
  17500. if (includeDescendants) {
  17501. var descendants = this.getDescendants(false);
  17502. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  17503. var descendant = descendants_1[_i];
  17504. var childMesh = descendant;
  17505. childMesh.computeWorldMatrix(true);
  17506. //make sure we have the needed params to get mix and max
  17507. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  17508. continue;
  17509. }
  17510. var childBoundingInfo = childMesh.getBoundingInfo();
  17511. var boundingBox = childBoundingInfo.boundingBox;
  17512. var minBox = boundingBox.minimumWorld;
  17513. var maxBox = boundingBox.maximumWorld;
  17514. BABYLON.Tools.CheckExtends(minBox, min, max);
  17515. BABYLON.Tools.CheckExtends(maxBox, min, max);
  17516. }
  17517. }
  17518. return {
  17519. min: min,
  17520. max: max
  17521. };
  17522. };
  17523. /**
  17524. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  17525. * Returns the AbstractMesh.
  17526. */
  17527. AbstractMesh.prototype._updateBoundingInfo = function () {
  17528. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  17529. this._boundingInfo.update(this.worldMatrixFromCache);
  17530. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  17531. return this;
  17532. };
  17533. /**
  17534. * Update a mesh's children BoundingInfo objects only.
  17535. * Returns the AbstractMesh.
  17536. */
  17537. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  17538. if (!this.subMeshes) {
  17539. return this;
  17540. }
  17541. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  17542. var subMesh = this.subMeshes[subIndex];
  17543. if (!subMesh.IsGlobal) {
  17544. subMesh.updateBoundingInfo(matrix);
  17545. }
  17546. }
  17547. return this;
  17548. };
  17549. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  17550. // Bounding info
  17551. this._updateBoundingInfo();
  17552. };
  17553. /**
  17554. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  17555. * A mesh is in the frustum if its bounding box intersects the frustum.
  17556. * Boolean returned.
  17557. */
  17558. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  17559. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  17560. };
  17561. /**
  17562. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  17563. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  17564. * Boolean returned.
  17565. */
  17566. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  17567. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  17568. ;
  17569. };
  17570. /**
  17571. * True if the mesh intersects another mesh or a SolidParticle object.
  17572. * 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)
  17573. * includeDescendants can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  17574. * Returns a boolean.
  17575. */
  17576. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  17577. if (precise === void 0) { precise = false; }
  17578. if (!this._boundingInfo || !mesh._boundingInfo) {
  17579. return false;
  17580. }
  17581. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  17582. return true;
  17583. }
  17584. if (includeDescendants) {
  17585. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  17586. var child = _a[_i];
  17587. if (child.intersectsMesh(mesh, precise, true)) {
  17588. return true;
  17589. }
  17590. }
  17591. }
  17592. return false;
  17593. };
  17594. /**
  17595. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  17596. * Returns a boolean.
  17597. */
  17598. AbstractMesh.prototype.intersectsPoint = function (point) {
  17599. if (!this._boundingInfo) {
  17600. return false;
  17601. }
  17602. return this._boundingInfo.intersectsPoint(point);
  17603. };
  17604. AbstractMesh.prototype.getPhysicsImpostor = function () {
  17605. return this.physicsImpostor;
  17606. };
  17607. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  17608. if (camera === void 0) { camera = null; }
  17609. if (!camera) {
  17610. camera = this.getScene().activeCamera;
  17611. }
  17612. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  17613. };
  17614. /**
  17615. * Returns the distance from the mesh to the active camera.
  17616. * Returns a float.
  17617. */
  17618. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  17619. if (camera === void 0) { camera = null; }
  17620. if (!camera) {
  17621. camera = this.getScene().activeCamera;
  17622. }
  17623. return this.absolutePosition.subtract(camera.position).length();
  17624. };
  17625. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  17626. if (!this.physicsImpostor) {
  17627. return this;
  17628. }
  17629. this.physicsImpostor.applyImpulse(force, contactPoint);
  17630. return this;
  17631. };
  17632. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  17633. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  17634. return this;
  17635. }
  17636. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  17637. mainPivot: pivot1,
  17638. connectedPivot: pivot2,
  17639. nativeParams: options
  17640. });
  17641. return this;
  17642. };
  17643. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  17644. // Collisions
  17645. /**
  17646. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  17647. * Default `false`.
  17648. */
  17649. get: function () {
  17650. return this._checkCollisions;
  17651. },
  17652. set: function (collisionEnabled) {
  17653. this._checkCollisions = collisionEnabled;
  17654. if (this.getScene().workerCollisions) {
  17655. this.getScene().collisionCoordinator.onMeshUpdated(this);
  17656. }
  17657. },
  17658. enumerable: true,
  17659. configurable: true
  17660. });
  17661. Object.defineProperty(AbstractMesh.prototype, "collider", {
  17662. /**
  17663. * Gets Collider object used to compute collisions (not physics)
  17664. */
  17665. get: function () {
  17666. return this._collider;
  17667. },
  17668. enumerable: true,
  17669. configurable: true
  17670. });
  17671. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  17672. var globalPosition = this.getAbsolutePosition();
  17673. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  17674. if (!this._collider) {
  17675. this._collider = new BABYLON.Collider();
  17676. }
  17677. this._collider._radius = this.ellipsoid;
  17678. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  17679. return this;
  17680. };
  17681. // Submeshes octree
  17682. /**
  17683. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  17684. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  17685. * Returns an Octree of submeshes.
  17686. */
  17687. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  17688. if (maxCapacity === void 0) { maxCapacity = 64; }
  17689. if (maxDepth === void 0) { maxDepth = 2; }
  17690. if (!this._submeshesOctree) {
  17691. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  17692. }
  17693. this.computeWorldMatrix(true);
  17694. var boundingInfo = this.getBoundingInfo();
  17695. // Update octree
  17696. var bbox = boundingInfo.boundingBox;
  17697. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  17698. return this._submeshesOctree;
  17699. };
  17700. // Collisions
  17701. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  17702. this._generatePointsArray();
  17703. if (!this._positions) {
  17704. return this;
  17705. }
  17706. // Transformation
  17707. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  17708. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  17709. subMesh._lastColliderWorldVertices = [];
  17710. subMesh._trianglePlanes = [];
  17711. var start = subMesh.verticesStart;
  17712. var end = (subMesh.verticesStart + subMesh.verticesCount);
  17713. for (var i = start; i < end; i++) {
  17714. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  17715. }
  17716. }
  17717. // Collide
  17718. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  17719. if (collider.collisionFound) {
  17720. collider.collidedMesh = this;
  17721. }
  17722. return this;
  17723. };
  17724. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  17725. var subMeshes;
  17726. var len;
  17727. // Octrees
  17728. if (this._submeshesOctree && this.useOctreeForCollisions) {
  17729. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  17730. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  17731. len = intersections.length;
  17732. subMeshes = intersections.data;
  17733. }
  17734. else {
  17735. subMeshes = this.subMeshes;
  17736. len = subMeshes.length;
  17737. }
  17738. for (var index = 0; index < len; index++) {
  17739. var subMesh = subMeshes[index];
  17740. // Bounding test
  17741. if (len > 1 && !subMesh._checkCollision(collider))
  17742. continue;
  17743. this._collideForSubMesh(subMesh, transformMatrix, collider);
  17744. }
  17745. return this;
  17746. };
  17747. AbstractMesh.prototype._checkCollision = function (collider) {
  17748. // Bounding box test
  17749. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  17750. return this;
  17751. // Transformation matrix
  17752. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  17753. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  17754. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  17755. return this;
  17756. };
  17757. // Picking
  17758. AbstractMesh.prototype._generatePointsArray = function () {
  17759. return false;
  17760. };
  17761. /**
  17762. * Checks if the passed Ray intersects with the mesh.
  17763. * Returns an object PickingInfo.
  17764. */
  17765. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  17766. var pickingInfo = new BABYLON.PickingInfo();
  17767. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  17768. return pickingInfo;
  17769. }
  17770. if (!this._generatePointsArray()) {
  17771. return pickingInfo;
  17772. }
  17773. var intersectInfo = null;
  17774. // Octrees
  17775. var subMeshes;
  17776. var len;
  17777. if (this._submeshesOctree && this.useOctreeForPicking) {
  17778. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  17779. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  17780. len = intersections.length;
  17781. subMeshes = intersections.data;
  17782. }
  17783. else {
  17784. subMeshes = this.subMeshes;
  17785. len = subMeshes.length;
  17786. }
  17787. for (var index = 0; index < len; index++) {
  17788. var subMesh = subMeshes[index];
  17789. // Bounding test
  17790. if (len > 1 && !subMesh.canIntersects(ray))
  17791. continue;
  17792. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  17793. if (currentIntersectInfo) {
  17794. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  17795. intersectInfo = currentIntersectInfo;
  17796. intersectInfo.subMeshId = index;
  17797. if (fastCheck) {
  17798. break;
  17799. }
  17800. }
  17801. }
  17802. }
  17803. if (intersectInfo) {
  17804. // Get picked point
  17805. var world = this.getWorldMatrix();
  17806. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  17807. var direction = ray.direction.clone();
  17808. direction = direction.scale(intersectInfo.distance);
  17809. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  17810. var pickedPoint = worldOrigin.add(worldDirection);
  17811. // Return result
  17812. pickingInfo.hit = true;
  17813. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  17814. pickingInfo.pickedPoint = pickedPoint;
  17815. pickingInfo.pickedMesh = this;
  17816. pickingInfo.bu = intersectInfo.bu || 0;
  17817. pickingInfo.bv = intersectInfo.bv || 0;
  17818. pickingInfo.faceId = intersectInfo.faceId;
  17819. pickingInfo.subMeshId = intersectInfo.subMeshId;
  17820. return pickingInfo;
  17821. }
  17822. return pickingInfo;
  17823. };
  17824. /**
  17825. * Clones the mesh, used by the class Mesh.
  17826. * Just returns `null` for an AbstractMesh.
  17827. */
  17828. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  17829. return null;
  17830. };
  17831. /**
  17832. * Disposes all the mesh submeshes.
  17833. * Returns the AbstractMesh.
  17834. */
  17835. AbstractMesh.prototype.releaseSubMeshes = function () {
  17836. if (this.subMeshes) {
  17837. while (this.subMeshes.length) {
  17838. this.subMeshes[0].dispose();
  17839. }
  17840. }
  17841. else {
  17842. this.subMeshes = new Array();
  17843. }
  17844. return this;
  17845. };
  17846. /**
  17847. * Disposes the AbstractMesh.
  17848. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  17849. * Returns nothing.
  17850. */
  17851. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  17852. var _this = this;
  17853. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  17854. var index;
  17855. // Action manager
  17856. if (this.actionManager !== undefined && this.actionManager !== null) {
  17857. this.actionManager.dispose();
  17858. this.actionManager = null;
  17859. }
  17860. // Skeleton
  17861. this.skeleton = null;
  17862. // Physics
  17863. if (this.physicsImpostor) {
  17864. this.physicsImpostor.dispose();
  17865. }
  17866. // Intersections in progress
  17867. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  17868. var other = this._intersectionsInProgress[index];
  17869. var pos = other._intersectionsInProgress.indexOf(this);
  17870. other._intersectionsInProgress.splice(pos, 1);
  17871. }
  17872. this._intersectionsInProgress = [];
  17873. // Lights
  17874. var lights = this.getScene().lights;
  17875. lights.forEach(function (light) {
  17876. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  17877. if (meshIndex !== -1) {
  17878. light.includedOnlyMeshes.splice(meshIndex, 1);
  17879. }
  17880. meshIndex = light.excludedMeshes.indexOf(_this);
  17881. if (meshIndex !== -1) {
  17882. light.excludedMeshes.splice(meshIndex, 1);
  17883. }
  17884. // Shadow generators
  17885. var generator = light.getShadowGenerator();
  17886. if (generator) {
  17887. var shadowMap = generator.getShadowMap();
  17888. if (shadowMap && shadowMap.renderList) {
  17889. meshIndex = shadowMap.renderList.indexOf(_this);
  17890. if (meshIndex !== -1) {
  17891. shadowMap.renderList.splice(meshIndex, 1);
  17892. }
  17893. }
  17894. }
  17895. });
  17896. // Edges
  17897. if (this._edgesRenderer) {
  17898. this._edgesRenderer.dispose();
  17899. this._edgesRenderer = null;
  17900. }
  17901. // SubMeshes
  17902. if (this.getClassName() !== "InstancedMesh") {
  17903. this.releaseSubMeshes();
  17904. }
  17905. // Octree
  17906. var sceneOctree = this.getScene().selectionOctree;
  17907. if (sceneOctree !== undefined && sceneOctree !== null) {
  17908. var index = sceneOctree.dynamicContent.indexOf(this);
  17909. if (index !== -1) {
  17910. sceneOctree.dynamicContent.splice(index, 1);
  17911. }
  17912. }
  17913. // Query
  17914. var engine = this.getScene().getEngine();
  17915. if (this._occlusionQuery) {
  17916. this._isOcclusionQueryInProgress = false;
  17917. engine.deleteQuery(this._occlusionQuery);
  17918. this._occlusionQuery = null;
  17919. }
  17920. // Engine
  17921. engine.wipeCaches();
  17922. // Remove from scene
  17923. this.getScene().removeMesh(this);
  17924. if (disposeMaterialAndTextures) {
  17925. if (this.material) {
  17926. this.material.dispose(false, true);
  17927. }
  17928. }
  17929. if (!doNotRecurse) {
  17930. // Particles
  17931. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  17932. if (this.getScene().particleSystems[index].emitter === this) {
  17933. this.getScene().particleSystems[index].dispose();
  17934. index--;
  17935. }
  17936. }
  17937. }
  17938. // facet data
  17939. if (this._facetDataEnabled) {
  17940. this.disableFacetData();
  17941. }
  17942. this.onAfterWorldMatrixUpdateObservable.clear();
  17943. this.onCollideObservable.clear();
  17944. this.onCollisionPositionChangeObservable.clear();
  17945. this._isDisposed = true;
  17946. _super.prototype.dispose.call(this, doNotRecurse);
  17947. };
  17948. /**
  17949. * Adds the passed mesh as a child to the current mesh.
  17950. * Returns the AbstractMesh.
  17951. */
  17952. AbstractMesh.prototype.addChild = function (mesh) {
  17953. mesh.setParent(this);
  17954. return this;
  17955. };
  17956. /**
  17957. * Removes the passed mesh from the current mesh children list.
  17958. * Returns the AbstractMesh.
  17959. */
  17960. AbstractMesh.prototype.removeChild = function (mesh) {
  17961. mesh.setParent(null);
  17962. return this;
  17963. };
  17964. // Facet data
  17965. /**
  17966. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  17967. * Returns the AbstractMesh.
  17968. */
  17969. AbstractMesh.prototype._initFacetData = function () {
  17970. if (!this._facetNormals) {
  17971. this._facetNormals = new Array();
  17972. }
  17973. if (!this._facetPositions) {
  17974. this._facetPositions = new Array();
  17975. }
  17976. if (!this._facetPartitioning) {
  17977. this._facetPartitioning = new Array();
  17978. }
  17979. this._facetNb = (this.getIndices().length / 3) | 0;
  17980. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  17981. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  17982. for (var f = 0; f < this._facetNb; f++) {
  17983. this._facetNormals[f] = BABYLON.Vector3.Zero();
  17984. this._facetPositions[f] = BABYLON.Vector3.Zero();
  17985. }
  17986. this._facetDataEnabled = true;
  17987. return this;
  17988. };
  17989. /**
  17990. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  17991. * This method can be called within the render loop.
  17992. * 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.
  17993. * Returns the AbstractMesh.
  17994. */
  17995. AbstractMesh.prototype.updateFacetData = function () {
  17996. if (!this._facetDataEnabled) {
  17997. this._initFacetData();
  17998. }
  17999. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18000. var indices = this.getIndices();
  18001. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18002. var bInfo = this.getBoundingInfo();
  18003. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  18004. // init arrays, matrix and sort function on first call
  18005. this._facetDepthSortEnabled = true;
  18006. if (indices instanceof Uint16Array) {
  18007. this._depthSortedIndices = new Uint16Array(indices);
  18008. }
  18009. else if (indices instanceof Uint32Array) {
  18010. this._depthSortedIndices = new Uint32Array(indices);
  18011. }
  18012. else {
  18013. var needs32bits = false;
  18014. for (var i = 0; i < indices.length; i++) {
  18015. if (indices[i] > 65535) {
  18016. needs32bits = true;
  18017. break;
  18018. }
  18019. }
  18020. if (needs32bits) {
  18021. this._depthSortedIndices = new Uint32Array(indices);
  18022. }
  18023. else {
  18024. this._depthSortedIndices = new Uint16Array(indices);
  18025. }
  18026. }
  18027. this._facetDepthSortFunction = function (f1, f2) {
  18028. return (f2.sqDistance - f1.sqDistance);
  18029. };
  18030. if (!this._facetDepthSortFrom) {
  18031. var camera = this.getScene().activeCamera;
  18032. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  18033. }
  18034. this._depthSortedFacets = [];
  18035. for (var f = 0; f < this._facetNb; f++) {
  18036. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  18037. this._depthSortedFacets.push(depthSortedFacet);
  18038. }
  18039. this._invertedMatrix = BABYLON.Matrix.Identity();
  18040. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  18041. }
  18042. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  18043. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  18044. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  18045. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  18046. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  18047. this._subDiv.max = this._partitioningSubdivisions;
  18048. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  18049. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  18050. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  18051. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  18052. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  18053. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  18054. // set the parameters for ComputeNormals()
  18055. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  18056. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  18057. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  18058. this._facetParameters.bInfo = bInfo;
  18059. this._facetParameters.bbSize = this._bbSize;
  18060. this._facetParameters.subDiv = this._subDiv;
  18061. this._facetParameters.ratio = this.partitioningBBoxRatio;
  18062. this._facetParameters.depthSort = this._facetDepthSort;
  18063. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  18064. this.computeWorldMatrix(true);
  18065. this._worldMatrix.invertToRef(this._invertedMatrix);
  18066. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  18067. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  18068. }
  18069. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  18070. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  18071. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  18072. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  18073. var l = (this._depthSortedIndices.length / 3) | 0;
  18074. for (var f = 0; f < l; f++) {
  18075. var sind = this._depthSortedFacets[f].ind;
  18076. this._depthSortedIndices[f * 3] = indices[sind];
  18077. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  18078. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  18079. }
  18080. this.updateIndices(this._depthSortedIndices);
  18081. }
  18082. return this;
  18083. };
  18084. /**
  18085. * Returns the facetLocalNormals array.
  18086. * The normals are expressed in the mesh local space.
  18087. */
  18088. AbstractMesh.prototype.getFacetLocalNormals = function () {
  18089. if (!this._facetNormals) {
  18090. this.updateFacetData();
  18091. }
  18092. return this._facetNormals;
  18093. };
  18094. /**
  18095. * Returns the facetLocalPositions array.
  18096. * The facet positions are expressed in the mesh local space.
  18097. */
  18098. AbstractMesh.prototype.getFacetLocalPositions = function () {
  18099. if (!this._facetPositions) {
  18100. this.updateFacetData();
  18101. }
  18102. return this._facetPositions;
  18103. };
  18104. /**
  18105. * Returns the facetLocalPartioning array.
  18106. */
  18107. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  18108. if (!this._facetPartitioning) {
  18109. this.updateFacetData();
  18110. }
  18111. return this._facetPartitioning;
  18112. };
  18113. /**
  18114. * Returns the i-th facet position in the world system.
  18115. * This method allocates a new Vector3 per call.
  18116. */
  18117. AbstractMesh.prototype.getFacetPosition = function (i) {
  18118. var pos = BABYLON.Vector3.Zero();
  18119. this.getFacetPositionToRef(i, pos);
  18120. return pos;
  18121. };
  18122. /**
  18123. * Sets the reference Vector3 with the i-th facet position in the world system.
  18124. * Returns the AbstractMesh.
  18125. */
  18126. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  18127. var localPos = (this.getFacetLocalPositions())[i];
  18128. var world = this.getWorldMatrix();
  18129. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  18130. return this;
  18131. };
  18132. /**
  18133. * Returns the i-th facet normal in the world system.
  18134. * This method allocates a new Vector3 per call.
  18135. */
  18136. AbstractMesh.prototype.getFacetNormal = function (i) {
  18137. var norm = BABYLON.Vector3.Zero();
  18138. this.getFacetNormalToRef(i, norm);
  18139. return norm;
  18140. };
  18141. /**
  18142. * Sets the reference Vector3 with the i-th facet normal in the world system.
  18143. * Returns the AbstractMesh.
  18144. */
  18145. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  18146. var localNorm = (this.getFacetLocalNormals())[i];
  18147. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  18148. return this;
  18149. };
  18150. /**
  18151. * 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).
  18152. */
  18153. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  18154. var bInfo = this.getBoundingInfo();
  18155. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  18156. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  18157. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  18158. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  18159. return null;
  18160. }
  18161. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  18162. };
  18163. /**
  18164. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  18165. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  18166. * If checkFace is 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.
  18167. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  18168. * 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.
  18169. */
  18170. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  18171. if (checkFace === void 0) { checkFace = false; }
  18172. if (facing === void 0) { facing = true; }
  18173. var world = this.getWorldMatrix();
  18174. var invMat = BABYLON.Tmp.Matrix[5];
  18175. world.invertToRef(invMat);
  18176. var invVect = BABYLON.Tmp.Vector3[8];
  18177. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  18178. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  18179. if (projected) {
  18180. // tranform the local computed projected vector to world coordinates
  18181. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  18182. }
  18183. return closest;
  18184. };
  18185. /**
  18186. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  18187. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  18188. * If checkFace is 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.
  18189. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  18190. * 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.
  18191. */
  18192. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  18193. if (checkFace === void 0) { checkFace = false; }
  18194. if (facing === void 0) { facing = true; }
  18195. var closest = null;
  18196. var tmpx = 0.0;
  18197. var tmpy = 0.0;
  18198. var tmpz = 0.0;
  18199. var d = 0.0; // tmp dot facet normal * facet position
  18200. var t0 = 0.0;
  18201. var projx = 0.0;
  18202. var projy = 0.0;
  18203. var projz = 0.0;
  18204. // Get all the facets in the same partitioning block than (x, y, z)
  18205. var facetPositions = this.getFacetLocalPositions();
  18206. var facetNormals = this.getFacetLocalNormals();
  18207. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  18208. if (!facetsInBlock) {
  18209. return null;
  18210. }
  18211. // Get the closest facet to (x, y, z)
  18212. var shortest = Number.MAX_VALUE; // init distance vars
  18213. var tmpDistance = shortest;
  18214. var fib; // current facet in the block
  18215. var norm; // current facet normal
  18216. var p0; // current facet barycenter position
  18217. // loop on all the facets in the current partitioning block
  18218. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  18219. fib = facetsInBlock[idx];
  18220. norm = facetNormals[fib];
  18221. p0 = facetPositions[fib];
  18222. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  18223. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  18224. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  18225. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  18226. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  18227. projx = x + norm.x * t0;
  18228. projy = y + norm.y * t0;
  18229. projz = z + norm.z * t0;
  18230. tmpx = projx - x;
  18231. tmpy = projy - y;
  18232. tmpz = projz - z;
  18233. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  18234. if (tmpDistance < shortest) {
  18235. shortest = tmpDistance;
  18236. closest = fib;
  18237. if (projected) {
  18238. projected.x = projx;
  18239. projected.y = projy;
  18240. projected.z = projz;
  18241. }
  18242. }
  18243. }
  18244. }
  18245. return closest;
  18246. };
  18247. /**
  18248. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  18249. */
  18250. AbstractMesh.prototype.getFacetDataParameters = function () {
  18251. return this._facetParameters;
  18252. };
  18253. /**
  18254. * Disables the feature FacetData and frees the related memory.
  18255. * Returns the AbstractMesh.
  18256. */
  18257. AbstractMesh.prototype.disableFacetData = function () {
  18258. if (this._facetDataEnabled) {
  18259. this._facetDataEnabled = false;
  18260. this._facetPositions = new Array();
  18261. this._facetNormals = new Array();
  18262. this._facetPartitioning = new Array();
  18263. this._facetParameters = null;
  18264. this._depthSortedIndices = new Uint32Array(0);
  18265. }
  18266. return this;
  18267. };
  18268. /**
  18269. * Updates the AbstractMesh indices array. Actually, used by the Mesh object.
  18270. * Returns the mesh.
  18271. */
  18272. AbstractMesh.prototype.updateIndices = function (indices) {
  18273. return this;
  18274. };
  18275. /**
  18276. * The mesh Geometry. Actually used by the Mesh object.
  18277. * Returns a blank geometry object.
  18278. */
  18279. /**
  18280. * Creates new normals data for the mesh.
  18281. * @param updatable.
  18282. */
  18283. AbstractMesh.prototype.createNormals = function (updatable) {
  18284. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18285. var indices = this.getIndices();
  18286. var normals;
  18287. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  18288. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18289. }
  18290. else {
  18291. normals = [];
  18292. }
  18293. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  18294. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  18295. };
  18296. /**
  18297. * Align the mesh with a normal.
  18298. * Returns the mesh.
  18299. */
  18300. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  18301. if (!upDirection) {
  18302. upDirection = BABYLON.Axis.Y;
  18303. }
  18304. var axisX = BABYLON.Tmp.Vector3[0];
  18305. var axisZ = BABYLON.Tmp.Vector3[1];
  18306. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  18307. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  18308. if (this.rotationQuaternion) {
  18309. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  18310. }
  18311. else {
  18312. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  18313. }
  18314. return this;
  18315. };
  18316. AbstractMesh.prototype.checkOcclusionQuery = function () {
  18317. var engine = this.getEngine();
  18318. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  18319. this._isOccluded = false;
  18320. return;
  18321. }
  18322. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  18323. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  18324. if (isOcclusionQueryAvailable) {
  18325. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  18326. this._isOcclusionQueryInProgress = false;
  18327. this._occlusionInternalRetryCounter = 0;
  18328. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  18329. }
  18330. else {
  18331. this._occlusionInternalRetryCounter++;
  18332. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  18333. this._isOcclusionQueryInProgress = false;
  18334. this._occlusionInternalRetryCounter = 0;
  18335. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  18336. // if strict continue the last state of the object.
  18337. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  18338. }
  18339. else {
  18340. return;
  18341. }
  18342. }
  18343. }
  18344. var scene = this.getScene();
  18345. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  18346. if (!this._occlusionQuery) {
  18347. this._occlusionQuery = engine.createQuery();
  18348. }
  18349. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  18350. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  18351. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  18352. this._isOcclusionQueryInProgress = true;
  18353. };
  18354. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  18355. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  18356. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  18357. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  18358. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  18359. return AbstractMesh;
  18360. }(BABYLON.TransformNode));
  18361. BABYLON.AbstractMesh = AbstractMesh;
  18362. })(BABYLON || (BABYLON = {}));
  18363. //# sourceMappingURL=babylon.abstractMesh.js.map
  18364. var BABYLON;
  18365. (function (BABYLON) {
  18366. /**
  18367. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  18368. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  18369. * 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.
  18370. */
  18371. var Light = /** @class */ (function (_super) {
  18372. __extends(Light, _super);
  18373. /**
  18374. * Creates a Light object in the scene.
  18375. * Documentation : http://doc.babylonjs.com/tutorials/lights
  18376. * @param name The firendly name of the light
  18377. * @param scene The scene the light belongs too
  18378. */
  18379. function Light(name, scene) {
  18380. var _this = _super.call(this, name, scene) || this;
  18381. /**
  18382. * Diffuse gives the basic color to an object.
  18383. */
  18384. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  18385. /**
  18386. * Specular produces a highlight color on an object.
  18387. * Note: This is note affecting PBR materials.
  18388. */
  18389. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  18390. /**
  18391. * Strength of the light.
  18392. * Note: By default it is define in the framework own unit.
  18393. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  18394. */
  18395. _this.intensity = 1.0;
  18396. /**
  18397. * Defines how far from the source the light is impacting in scene units.
  18398. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  18399. */
  18400. _this.range = Number.MAX_VALUE;
  18401. /**
  18402. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  18403. * of light.
  18404. */
  18405. _this._photometricScale = 1.0;
  18406. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  18407. _this._radius = 0.00001;
  18408. /**
  18409. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  18410. * exceeding the number allowed of the materials.
  18411. */
  18412. _this.renderPriority = 0;
  18413. /**
  18414. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  18415. * the current shadow generator.
  18416. */
  18417. _this.shadowEnabled = true;
  18418. _this._excludeWithLayerMask = 0;
  18419. _this._includeOnlyWithLayerMask = 0;
  18420. _this._lightmapMode = 0;
  18421. /**
  18422. * @ignore Internal use only.
  18423. */
  18424. _this._excludedMeshesIds = new Array();
  18425. /**
  18426. * @ignore Internal use only.
  18427. */
  18428. _this._includedOnlyMeshesIds = new Array();
  18429. _this.getScene().addLight(_this);
  18430. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  18431. _this._buildUniformLayout();
  18432. _this.includedOnlyMeshes = new Array();
  18433. _this.excludedMeshes = new Array();
  18434. _this._resyncMeshes();
  18435. return _this;
  18436. }
  18437. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  18438. /**
  18439. * If every light affecting the material is in this lightmapMode,
  18440. * material.lightmapTexture adds or multiplies
  18441. * (depends on material.useLightmapAsShadowmap)
  18442. * after every other light calculations.
  18443. */
  18444. get: function () {
  18445. return Light._LIGHTMAP_DEFAULT;
  18446. },
  18447. enumerable: true,
  18448. configurable: true
  18449. });
  18450. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  18451. /**
  18452. * material.lightmapTexture as only diffuse lighting from this light
  18453. * adds only specular lighting from this light
  18454. * adds dynamic shadows
  18455. */
  18456. get: function () {
  18457. return Light._LIGHTMAP_SPECULAR;
  18458. },
  18459. enumerable: true,
  18460. configurable: true
  18461. });
  18462. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  18463. /**
  18464. * material.lightmapTexture as only lighting
  18465. * no light calculation from this light
  18466. * only adds dynamic shadows from this light
  18467. */
  18468. get: function () {
  18469. return Light._LIGHTMAP_SHADOWSONLY;
  18470. },
  18471. enumerable: true,
  18472. configurable: true
  18473. });
  18474. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  18475. /**
  18476. * Each light type uses the default quantity according to its type:
  18477. * point/spot lights use luminous intensity
  18478. * directional lights use illuminance
  18479. */
  18480. get: function () {
  18481. return Light._INTENSITYMODE_AUTOMATIC;
  18482. },
  18483. enumerable: true,
  18484. configurable: true
  18485. });
  18486. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  18487. /**
  18488. * lumen (lm)
  18489. */
  18490. get: function () {
  18491. return Light._INTENSITYMODE_LUMINOUSPOWER;
  18492. },
  18493. enumerable: true,
  18494. configurable: true
  18495. });
  18496. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  18497. /**
  18498. * candela (lm/sr)
  18499. */
  18500. get: function () {
  18501. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  18502. },
  18503. enumerable: true,
  18504. configurable: true
  18505. });
  18506. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  18507. /**
  18508. * lux (lm/m^2)
  18509. */
  18510. get: function () {
  18511. return Light._INTENSITYMODE_ILLUMINANCE;
  18512. },
  18513. enumerable: true,
  18514. configurable: true
  18515. });
  18516. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  18517. /**
  18518. * nit (cd/m^2)
  18519. */
  18520. get: function () {
  18521. return Light._INTENSITYMODE_LUMINANCE;
  18522. },
  18523. enumerable: true,
  18524. configurable: true
  18525. });
  18526. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  18527. /**
  18528. * Light type const id of the point light.
  18529. */
  18530. get: function () {
  18531. return Light._LIGHTTYPEID_POINTLIGHT;
  18532. },
  18533. enumerable: true,
  18534. configurable: true
  18535. });
  18536. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  18537. /**
  18538. * Light type const id of the directional light.
  18539. */
  18540. get: function () {
  18541. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  18542. },
  18543. enumerable: true,
  18544. configurable: true
  18545. });
  18546. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  18547. /**
  18548. * Light type const id of the spot light.
  18549. */
  18550. get: function () {
  18551. return Light._LIGHTTYPEID_SPOTLIGHT;
  18552. },
  18553. enumerable: true,
  18554. configurable: true
  18555. });
  18556. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  18557. /**
  18558. * Light type const id of the hemispheric light.
  18559. */
  18560. get: function () {
  18561. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  18562. },
  18563. enumerable: true,
  18564. configurable: true
  18565. });
  18566. Object.defineProperty(Light.prototype, "intensityMode", {
  18567. /**
  18568. * Gets the photometric scale used to interpret the intensity.
  18569. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  18570. */
  18571. get: function () {
  18572. return this._intensityMode;
  18573. },
  18574. /**
  18575. * Sets the photometric scale used to interpret the intensity.
  18576. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  18577. */
  18578. set: function (value) {
  18579. this._intensityMode = value;
  18580. this._computePhotometricScale();
  18581. },
  18582. enumerable: true,
  18583. configurable: true
  18584. });
  18585. ;
  18586. ;
  18587. Object.defineProperty(Light.prototype, "radius", {
  18588. /**
  18589. * Gets the light radius used by PBR Materials to simulate soft area lights.
  18590. */
  18591. get: function () {
  18592. return this._radius;
  18593. },
  18594. /**
  18595. * sets the light radius used by PBR Materials to simulate soft area lights.
  18596. */
  18597. set: function (value) {
  18598. this._radius = value;
  18599. this._computePhotometricScale();
  18600. },
  18601. enumerable: true,
  18602. configurable: true
  18603. });
  18604. ;
  18605. ;
  18606. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  18607. /**
  18608. * Gets the only meshes impacted by this light.
  18609. */
  18610. get: function () {
  18611. return this._includedOnlyMeshes;
  18612. },
  18613. /**
  18614. * Sets the only meshes impacted by this light.
  18615. */
  18616. set: function (value) {
  18617. this._includedOnlyMeshes = value;
  18618. this._hookArrayForIncludedOnly(value);
  18619. },
  18620. enumerable: true,
  18621. configurable: true
  18622. });
  18623. Object.defineProperty(Light.prototype, "excludedMeshes", {
  18624. /**
  18625. * Gets the meshes not impacted by this light.
  18626. */
  18627. get: function () {
  18628. return this._excludedMeshes;
  18629. },
  18630. /**
  18631. * Sets the meshes not impacted by this light.
  18632. */
  18633. set: function (value) {
  18634. this._excludedMeshes = value;
  18635. this._hookArrayForExcluded(value);
  18636. },
  18637. enumerable: true,
  18638. configurable: true
  18639. });
  18640. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  18641. /**
  18642. * Gets the layer id use to find what meshes are not impacted by the light.
  18643. * Inactive if 0
  18644. */
  18645. get: function () {
  18646. return this._excludeWithLayerMask;
  18647. },
  18648. /**
  18649. * Sets the layer id use to find what meshes are not impacted by the light.
  18650. * Inactive if 0
  18651. */
  18652. set: function (value) {
  18653. this._excludeWithLayerMask = value;
  18654. this._resyncMeshes();
  18655. },
  18656. enumerable: true,
  18657. configurable: true
  18658. });
  18659. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  18660. /**
  18661. * Gets the layer id use to find what meshes are impacted by the light.
  18662. * Inactive if 0
  18663. */
  18664. get: function () {
  18665. return this._includeOnlyWithLayerMask;
  18666. },
  18667. /**
  18668. * Sets the layer id use to find what meshes are impacted by the light.
  18669. * Inactive if 0
  18670. */
  18671. set: function (value) {
  18672. this._includeOnlyWithLayerMask = value;
  18673. this._resyncMeshes();
  18674. },
  18675. enumerable: true,
  18676. configurable: true
  18677. });
  18678. Object.defineProperty(Light.prototype, "lightmapMode", {
  18679. /**
  18680. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  18681. */
  18682. get: function () {
  18683. return this._lightmapMode;
  18684. },
  18685. /**
  18686. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  18687. */
  18688. set: function (value) {
  18689. if (this._lightmapMode === value) {
  18690. return;
  18691. }
  18692. this._lightmapMode = value;
  18693. this._markMeshesAsLightDirty();
  18694. },
  18695. enumerable: true,
  18696. configurable: true
  18697. });
  18698. /**
  18699. * Returns the string "Light".
  18700. * @returns the class name
  18701. */
  18702. Light.prototype.getClassName = function () {
  18703. return "Light";
  18704. };
  18705. /**
  18706. * Converts the light information to a readable string for debug purpose.
  18707. * @param fullDetails Supports for multiple levels of logging within scene loading
  18708. * @returns the human readable light info
  18709. */
  18710. Light.prototype.toString = function (fullDetails) {
  18711. var ret = "Name: " + this.name;
  18712. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  18713. if (this.animations) {
  18714. for (var i = 0; i < this.animations.length; i++) {
  18715. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  18716. }
  18717. }
  18718. if (fullDetails) {
  18719. }
  18720. return ret;
  18721. };
  18722. /**
  18723. * Set the enabled state of this node.
  18724. * @param value - the new enabled state
  18725. * @see isEnabled
  18726. */
  18727. Light.prototype.setEnabled = function (value) {
  18728. _super.prototype.setEnabled.call(this, value);
  18729. this._resyncMeshes();
  18730. };
  18731. /**
  18732. * Returns the Light associated shadow generator if any.
  18733. * @return the associated shadow generator.
  18734. */
  18735. Light.prototype.getShadowGenerator = function () {
  18736. return this._shadowGenerator;
  18737. };
  18738. /**
  18739. * Returns a Vector3, the absolute light position in the World.
  18740. * @returns the world space position of the light
  18741. */
  18742. Light.prototype.getAbsolutePosition = function () {
  18743. return BABYLON.Vector3.Zero();
  18744. };
  18745. /**
  18746. * Specifies if the light will affect the passed mesh.
  18747. * @param mesh The mesh to test against the light
  18748. * @return true the mesh is affected otherwise, false.
  18749. */
  18750. Light.prototype.canAffectMesh = function (mesh) {
  18751. if (!mesh) {
  18752. return true;
  18753. }
  18754. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  18755. return false;
  18756. }
  18757. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  18758. return false;
  18759. }
  18760. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  18761. return false;
  18762. }
  18763. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  18764. return false;
  18765. }
  18766. return true;
  18767. };
  18768. /**
  18769. * Computes and Returns the light World matrix.
  18770. * @returns the world matrix
  18771. */
  18772. Light.prototype.getWorldMatrix = function () {
  18773. this._currentRenderId = this.getScene().getRenderId();
  18774. var worldMatrix = this._getWorldMatrix();
  18775. if (this.parent && this.parent.getWorldMatrix) {
  18776. if (!this._parentedWorldMatrix) {
  18777. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  18778. }
  18779. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  18780. this._markSyncedWithParent();
  18781. return this._parentedWorldMatrix;
  18782. }
  18783. return worldMatrix;
  18784. };
  18785. /**
  18786. * Sort function to order lights for rendering.
  18787. * @param a First Light object to compare to second.
  18788. * @param b Second Light object to compare first.
  18789. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  18790. */
  18791. Light.CompareLightsPriority = function (a, b) {
  18792. //shadow-casting lights have priority over non-shadow-casting lights
  18793. //the renderPrioirty is a secondary sort criterion
  18794. if (a.shadowEnabled !== b.shadowEnabled) {
  18795. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  18796. }
  18797. return b.renderPriority - a.renderPriority;
  18798. };
  18799. /**
  18800. * Disposes the light.
  18801. */
  18802. Light.prototype.dispose = function () {
  18803. if (this._shadowGenerator) {
  18804. this._shadowGenerator.dispose();
  18805. this._shadowGenerator = null;
  18806. }
  18807. // Animations
  18808. this.getScene().stopAnimation(this);
  18809. // Remove from meshes
  18810. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  18811. var mesh = _a[_i];
  18812. mesh._removeLightSource(this);
  18813. }
  18814. this._uniformBuffer.dispose();
  18815. // Remove from scene
  18816. this.getScene().removeLight(this);
  18817. _super.prototype.dispose.call(this);
  18818. };
  18819. /**
  18820. * Returns the light type ID (integer).
  18821. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  18822. */
  18823. Light.prototype.getTypeID = function () {
  18824. return 0;
  18825. };
  18826. /**
  18827. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  18828. * @returns the scaled intensity in intensity mode unit
  18829. */
  18830. Light.prototype.getScaledIntensity = function () {
  18831. return this._photometricScale * this.intensity;
  18832. };
  18833. /**
  18834. * Returns a new Light object, named "name", from the current one.
  18835. * @param name The name of the cloned light
  18836. * @returns the new created light
  18837. */
  18838. Light.prototype.clone = function (name) {
  18839. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  18840. if (!constructor) {
  18841. return null;
  18842. }
  18843. return BABYLON.SerializationHelper.Clone(constructor, this);
  18844. };
  18845. /**
  18846. * Serializes the current light into a Serialization object.
  18847. * @returns the serialized object.
  18848. */
  18849. Light.prototype.serialize = function () {
  18850. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  18851. // Type
  18852. serializationObject.type = this.getTypeID();
  18853. // Parent
  18854. if (this.parent) {
  18855. serializationObject.parentId = this.parent.id;
  18856. }
  18857. // Inclusion / exclusions
  18858. if (this.excludedMeshes.length > 0) {
  18859. serializationObject.excludedMeshesIds = [];
  18860. this.excludedMeshes.forEach(function (mesh) {
  18861. serializationObject.excludedMeshesIds.push(mesh.id);
  18862. });
  18863. }
  18864. if (this.includedOnlyMeshes.length > 0) {
  18865. serializationObject.includedOnlyMeshesIds = [];
  18866. this.includedOnlyMeshes.forEach(function (mesh) {
  18867. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  18868. });
  18869. }
  18870. // Animations
  18871. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  18872. serializationObject.ranges = this.serializeAnimationRanges();
  18873. return serializationObject;
  18874. };
  18875. /**
  18876. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  18877. * This new light is named "name" and added to the passed scene.
  18878. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  18879. * @param name The friendly name of the light
  18880. * @param scene The scene the new light will belong to
  18881. * @returns the constructor function
  18882. */
  18883. Light.GetConstructorFromName = function (type, name, scene) {
  18884. switch (type) {
  18885. case 0:
  18886. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  18887. case 1:
  18888. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  18889. case 2:
  18890. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  18891. case 3:
  18892. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  18893. }
  18894. return null;
  18895. };
  18896. /**
  18897. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  18898. * @param parsedLight The JSON representation of the light
  18899. * @param scene The scene to create the parsed light in
  18900. * @returns the created light after parsing
  18901. */
  18902. Light.Parse = function (parsedLight, scene) {
  18903. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  18904. if (!constructor) {
  18905. return null;
  18906. }
  18907. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  18908. // Inclusion / exclusions
  18909. if (parsedLight.excludedMeshesIds) {
  18910. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  18911. }
  18912. if (parsedLight.includedOnlyMeshesIds) {
  18913. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  18914. }
  18915. // Parent
  18916. if (parsedLight.parentId) {
  18917. light._waitingParentId = parsedLight.parentId;
  18918. }
  18919. // Animations
  18920. if (parsedLight.animations) {
  18921. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  18922. var parsedAnimation = parsedLight.animations[animationIndex];
  18923. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  18924. }
  18925. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  18926. }
  18927. if (parsedLight.autoAnimate) {
  18928. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  18929. }
  18930. return light;
  18931. };
  18932. Light.prototype._hookArrayForExcluded = function (array) {
  18933. var _this = this;
  18934. var oldPush = array.push;
  18935. array.push = function () {
  18936. var items = [];
  18937. for (var _i = 0; _i < arguments.length; _i++) {
  18938. items[_i] = arguments[_i];
  18939. }
  18940. var result = oldPush.apply(array, items);
  18941. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  18942. var item = items_1[_a];
  18943. item._resyncLighSource(_this);
  18944. }
  18945. return result;
  18946. };
  18947. var oldSplice = array.splice;
  18948. array.splice = function (index, deleteCount) {
  18949. var deleted = oldSplice.apply(array, [index, deleteCount]);
  18950. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  18951. var item = deleted_1[_i];
  18952. item._resyncLighSource(_this);
  18953. }
  18954. return deleted;
  18955. };
  18956. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  18957. var item = array_1[_i];
  18958. item._resyncLighSource(this);
  18959. }
  18960. };
  18961. Light.prototype._hookArrayForIncludedOnly = function (array) {
  18962. var _this = this;
  18963. var oldPush = array.push;
  18964. array.push = function () {
  18965. var items = [];
  18966. for (var _i = 0; _i < arguments.length; _i++) {
  18967. items[_i] = arguments[_i];
  18968. }
  18969. var result = oldPush.apply(array, items);
  18970. _this._resyncMeshes();
  18971. return result;
  18972. };
  18973. var oldSplice = array.splice;
  18974. array.splice = function (index, deleteCount) {
  18975. var deleted = oldSplice.apply(array, [index, deleteCount]);
  18976. _this._resyncMeshes();
  18977. return deleted;
  18978. };
  18979. this._resyncMeshes();
  18980. };
  18981. Light.prototype._resyncMeshes = function () {
  18982. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  18983. var mesh = _a[_i];
  18984. mesh._resyncLighSource(this);
  18985. }
  18986. };
  18987. /**
  18988. * Forces the meshes to update their light related information in their rendering used effects
  18989. * @ignore Internal Use Only
  18990. */
  18991. Light.prototype._markMeshesAsLightDirty = function () {
  18992. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  18993. var mesh = _a[_i];
  18994. if (mesh._lightSources.indexOf(this) !== -1) {
  18995. mesh._markSubMeshesAsLightDirty();
  18996. }
  18997. }
  18998. };
  18999. /**
  19000. * Recomputes the cached photometric scale if needed.
  19001. */
  19002. Light.prototype._computePhotometricScale = function () {
  19003. this._photometricScale = this._getPhotometricScale();
  19004. this.getScene().resetCachedMaterial();
  19005. };
  19006. /**
  19007. * Returns the Photometric Scale according to the light type and intensity mode.
  19008. */
  19009. Light.prototype._getPhotometricScale = function () {
  19010. var photometricScale = 0.0;
  19011. var lightTypeID = this.getTypeID();
  19012. //get photometric mode
  19013. var photometricMode = this.intensityMode;
  19014. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  19015. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  19016. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  19017. }
  19018. else {
  19019. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  19020. }
  19021. }
  19022. //compute photometric scale
  19023. switch (lightTypeID) {
  19024. case Light.LIGHTTYPEID_POINTLIGHT:
  19025. case Light.LIGHTTYPEID_SPOTLIGHT:
  19026. switch (photometricMode) {
  19027. case Light.INTENSITYMODE_LUMINOUSPOWER:
  19028. photometricScale = 1.0 / (4.0 * Math.PI);
  19029. break;
  19030. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  19031. photometricScale = 1.0;
  19032. break;
  19033. case Light.INTENSITYMODE_LUMINANCE:
  19034. photometricScale = this.radius * this.radius;
  19035. break;
  19036. }
  19037. break;
  19038. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  19039. switch (photometricMode) {
  19040. case Light.INTENSITYMODE_ILLUMINANCE:
  19041. photometricScale = 1.0;
  19042. break;
  19043. case Light.INTENSITYMODE_LUMINANCE:
  19044. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  19045. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  19046. var apexAngleRadians = this.radius;
  19047. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  19048. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  19049. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  19050. photometricScale = solidAngle;
  19051. break;
  19052. }
  19053. break;
  19054. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  19055. // No fall off in hemisperic light.
  19056. photometricScale = 1.0;
  19057. break;
  19058. }
  19059. return photometricScale;
  19060. };
  19061. /**
  19062. * Reorder the light in the scene according to their defined priority.
  19063. * @ignore Internal Use Only
  19064. */
  19065. Light.prototype._reorderLightsInScene = function () {
  19066. var scene = this.getScene();
  19067. if (this._renderPriority != 0) {
  19068. scene.requireLightSorting = true;
  19069. }
  19070. this.getScene().sortLightsByPriority();
  19071. };
  19072. //lightmapMode Consts
  19073. Light._LIGHTMAP_DEFAULT = 0;
  19074. Light._LIGHTMAP_SPECULAR = 1;
  19075. Light._LIGHTMAP_SHADOWSONLY = 2;
  19076. // Intensity Mode Consts
  19077. Light._INTENSITYMODE_AUTOMATIC = 0;
  19078. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  19079. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  19080. Light._INTENSITYMODE_ILLUMINANCE = 3;
  19081. Light._INTENSITYMODE_LUMINANCE = 4;
  19082. // Light types ids const.
  19083. Light._LIGHTTYPEID_POINTLIGHT = 0;
  19084. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  19085. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  19086. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  19087. __decorate([
  19088. BABYLON.serializeAsColor3()
  19089. ], Light.prototype, "diffuse", void 0);
  19090. __decorate([
  19091. BABYLON.serializeAsColor3()
  19092. ], Light.prototype, "specular", void 0);
  19093. __decorate([
  19094. BABYLON.serialize()
  19095. ], Light.prototype, "intensity", void 0);
  19096. __decorate([
  19097. BABYLON.serialize()
  19098. ], Light.prototype, "range", void 0);
  19099. __decorate([
  19100. BABYLON.serialize()
  19101. ], Light.prototype, "intensityMode", null);
  19102. __decorate([
  19103. BABYLON.serialize()
  19104. ], Light.prototype, "radius", null);
  19105. __decorate([
  19106. BABYLON.serialize()
  19107. ], Light.prototype, "_renderPriority", void 0);
  19108. __decorate([
  19109. BABYLON.expandToProperty("_reorderLightsInScene")
  19110. ], Light.prototype, "renderPriority", void 0);
  19111. __decorate([
  19112. BABYLON.serialize()
  19113. ], Light.prototype, "shadowEnabled", void 0);
  19114. __decorate([
  19115. BABYLON.serialize("excludeWithLayerMask")
  19116. ], Light.prototype, "_excludeWithLayerMask", void 0);
  19117. __decorate([
  19118. BABYLON.serialize("includeOnlyWithLayerMask")
  19119. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  19120. __decorate([
  19121. BABYLON.serialize("lightmapMode")
  19122. ], Light.prototype, "_lightmapMode", void 0);
  19123. return Light;
  19124. }(BABYLON.Node));
  19125. BABYLON.Light = Light;
  19126. })(BABYLON || (BABYLON = {}));
  19127. //# sourceMappingURL=babylon.light.js.map
  19128. var BABYLON;
  19129. (function (BABYLON) {
  19130. var Camera = /** @class */ (function (_super) {
  19131. __extends(Camera, _super);
  19132. function Camera(name, position, scene) {
  19133. var _this = _super.call(this, name, scene) || this;
  19134. /**
  19135. * The vector the camera should consider as up.
  19136. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  19137. */
  19138. _this.upVector = BABYLON.Vector3.Up();
  19139. _this.orthoLeft = null;
  19140. _this.orthoRight = null;
  19141. _this.orthoBottom = null;
  19142. _this.orthoTop = null;
  19143. /**
  19144. * FOV is set in Radians. (default is 0.8)
  19145. */
  19146. _this.fov = 0.8;
  19147. _this.minZ = 1;
  19148. _this.maxZ = 10000.0;
  19149. _this.inertia = 0.9;
  19150. _this.mode = Camera.PERSPECTIVE_CAMERA;
  19151. _this.isIntermediate = false;
  19152. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  19153. /**
  19154. * Restricts the camera to viewing objects with the same layerMask.
  19155. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  19156. */
  19157. _this.layerMask = 0x0FFFFFFF;
  19158. /**
  19159. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  19160. */
  19161. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  19162. // Camera rig members
  19163. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  19164. _this._rigCameras = new Array();
  19165. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  19166. _this._skipRendering = false;
  19167. _this.customRenderTargets = new Array();
  19168. // Observables
  19169. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  19170. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  19171. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  19172. _this.onRestoreStateObservable = new BABYLON.Observable();
  19173. // Cache
  19174. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  19175. _this._projectionMatrix = new BABYLON.Matrix();
  19176. _this._doNotComputeProjectionMatrix = false;
  19177. _this._postProcesses = new Array();
  19178. _this._transformMatrix = BABYLON.Matrix.Zero();
  19179. _this._activeMeshes = new BABYLON.SmartArray(256);
  19180. _this._globalPosition = BABYLON.Vector3.Zero();
  19181. _this._refreshFrustumPlanes = true;
  19182. _this.getScene().addCamera(_this);
  19183. if (!_this.getScene().activeCamera) {
  19184. _this.getScene().activeCamera = _this;
  19185. }
  19186. _this.position = position;
  19187. return _this;
  19188. }
  19189. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  19190. get: function () {
  19191. return Camera._PERSPECTIVE_CAMERA;
  19192. },
  19193. enumerable: true,
  19194. configurable: true
  19195. });
  19196. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  19197. get: function () {
  19198. return Camera._ORTHOGRAPHIC_CAMERA;
  19199. },
  19200. enumerable: true,
  19201. configurable: true
  19202. });
  19203. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  19204. /**
  19205. * This is the default FOV mode for perspective cameras.
  19206. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  19207. *
  19208. */
  19209. get: function () {
  19210. return Camera._FOVMODE_VERTICAL_FIXED;
  19211. },
  19212. enumerable: true,
  19213. configurable: true
  19214. });
  19215. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  19216. /**
  19217. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  19218. *
  19219. */
  19220. get: function () {
  19221. return Camera._FOVMODE_HORIZONTAL_FIXED;
  19222. },
  19223. enumerable: true,
  19224. configurable: true
  19225. });
  19226. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  19227. get: function () {
  19228. return Camera._RIG_MODE_NONE;
  19229. },
  19230. enumerable: true,
  19231. configurable: true
  19232. });
  19233. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  19234. get: function () {
  19235. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  19236. },
  19237. enumerable: true,
  19238. configurable: true
  19239. });
  19240. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  19241. get: function () {
  19242. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  19243. },
  19244. enumerable: true,
  19245. configurable: true
  19246. });
  19247. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  19248. get: function () {
  19249. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  19250. },
  19251. enumerable: true,
  19252. configurable: true
  19253. });
  19254. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  19255. get: function () {
  19256. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  19257. },
  19258. enumerable: true,
  19259. configurable: true
  19260. });
  19261. Object.defineProperty(Camera, "RIG_MODE_VR", {
  19262. get: function () {
  19263. return Camera._RIG_MODE_VR;
  19264. },
  19265. enumerable: true,
  19266. configurable: true
  19267. });
  19268. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  19269. get: function () {
  19270. return Camera._RIG_MODE_WEBVR;
  19271. },
  19272. enumerable: true,
  19273. configurable: true
  19274. });
  19275. /**
  19276. * Store current camera state (fov, position, etc..)
  19277. */
  19278. Camera.prototype.storeState = function () {
  19279. this._stateStored = true;
  19280. this._storedFov = this.fov;
  19281. return this;
  19282. };
  19283. /**
  19284. * Restores the camera state values if it has been stored. You must call storeState() first
  19285. */
  19286. Camera.prototype._restoreStateValues = function () {
  19287. if (!this._stateStored) {
  19288. return false;
  19289. }
  19290. this.fov = this._storedFov;
  19291. return true;
  19292. };
  19293. /**
  19294. * Restored camera state. You must call storeState() first
  19295. */
  19296. Camera.prototype.restoreState = function () {
  19297. if (this._restoreStateValues()) {
  19298. this.onRestoreStateObservable.notifyObservers(this);
  19299. return true;
  19300. }
  19301. return false;
  19302. };
  19303. Camera.prototype.getClassName = function () {
  19304. return "Camera";
  19305. };
  19306. /**
  19307. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  19308. */
  19309. Camera.prototype.toString = function (fullDetails) {
  19310. var ret = "Name: " + this.name;
  19311. ret += ", type: " + this.getClassName();
  19312. if (this.animations) {
  19313. for (var i = 0; i < this.animations.length; i++) {
  19314. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  19315. }
  19316. }
  19317. if (fullDetails) {
  19318. }
  19319. return ret;
  19320. };
  19321. Object.defineProperty(Camera.prototype, "globalPosition", {
  19322. get: function () {
  19323. return this._globalPosition;
  19324. },
  19325. enumerable: true,
  19326. configurable: true
  19327. });
  19328. Camera.prototype.getActiveMeshes = function () {
  19329. return this._activeMeshes;
  19330. };
  19331. Camera.prototype.isActiveMesh = function (mesh) {
  19332. return (this._activeMeshes.indexOf(mesh) !== -1);
  19333. };
  19334. //Cache
  19335. Camera.prototype._initCache = function () {
  19336. _super.prototype._initCache.call(this);
  19337. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  19338. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  19339. this._cache.mode = undefined;
  19340. this._cache.minZ = undefined;
  19341. this._cache.maxZ = undefined;
  19342. this._cache.fov = undefined;
  19343. this._cache.fovMode = undefined;
  19344. this._cache.aspectRatio = undefined;
  19345. this._cache.orthoLeft = undefined;
  19346. this._cache.orthoRight = undefined;
  19347. this._cache.orthoBottom = undefined;
  19348. this._cache.orthoTop = undefined;
  19349. this._cache.renderWidth = undefined;
  19350. this._cache.renderHeight = undefined;
  19351. };
  19352. Camera.prototype._updateCache = function (ignoreParentClass) {
  19353. if (!ignoreParentClass) {
  19354. _super.prototype._updateCache.call(this);
  19355. }
  19356. this._cache.position.copyFrom(this.position);
  19357. this._cache.upVector.copyFrom(this.upVector);
  19358. };
  19359. // Synchronized
  19360. Camera.prototype._isSynchronized = function () {
  19361. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  19362. };
  19363. Camera.prototype._isSynchronizedViewMatrix = function () {
  19364. if (!_super.prototype._isSynchronized.call(this))
  19365. return false;
  19366. return this._cache.position.equals(this.position)
  19367. && this._cache.upVector.equals(this.upVector)
  19368. && this.isSynchronizedWithParent();
  19369. };
  19370. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  19371. var check = this._cache.mode === this.mode
  19372. && this._cache.minZ === this.minZ
  19373. && this._cache.maxZ === this.maxZ;
  19374. if (!check) {
  19375. return false;
  19376. }
  19377. var engine = this.getEngine();
  19378. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  19379. check = this._cache.fov === this.fov
  19380. && this._cache.fovMode === this.fovMode
  19381. && this._cache.aspectRatio === engine.getAspectRatio(this);
  19382. }
  19383. else {
  19384. check = this._cache.orthoLeft === this.orthoLeft
  19385. && this._cache.orthoRight === this.orthoRight
  19386. && this._cache.orthoBottom === this.orthoBottom
  19387. && this._cache.orthoTop === this.orthoTop
  19388. && this._cache.renderWidth === engine.getRenderWidth()
  19389. && this._cache.renderHeight === engine.getRenderHeight();
  19390. }
  19391. return check;
  19392. };
  19393. // Controls
  19394. Camera.prototype.attachControl = function (element, noPreventDefault) {
  19395. };
  19396. Camera.prototype.detachControl = function (element) {
  19397. };
  19398. Camera.prototype.update = function () {
  19399. this._checkInputs();
  19400. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  19401. this._updateRigCameras();
  19402. }
  19403. };
  19404. Camera.prototype._checkInputs = function () {
  19405. this.onAfterCheckInputsObservable.notifyObservers(this);
  19406. };
  19407. Object.defineProperty(Camera.prototype, "rigCameras", {
  19408. get: function () {
  19409. return this._rigCameras;
  19410. },
  19411. enumerable: true,
  19412. configurable: true
  19413. });
  19414. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  19415. get: function () {
  19416. return this._rigPostProcess;
  19417. },
  19418. enumerable: true,
  19419. configurable: true
  19420. });
  19421. Camera.prototype._cascadePostProcessesToRigCams = function () {
  19422. // invalidate framebuffer
  19423. if (this._postProcesses.length > 0) {
  19424. this._postProcesses[0].markTextureDirty();
  19425. }
  19426. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  19427. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  19428. var cam = this._rigCameras[i];
  19429. var rigPostProcess = cam._rigPostProcess;
  19430. // for VR rig, there does not have to be a post process
  19431. if (rigPostProcess) {
  19432. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  19433. if (isPass) {
  19434. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  19435. cam.isIntermediate = this._postProcesses.length === 0;
  19436. }
  19437. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  19438. rigPostProcess.markTextureDirty();
  19439. }
  19440. else {
  19441. cam._postProcesses = this._postProcesses.slice(0);
  19442. }
  19443. }
  19444. };
  19445. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  19446. if (insertAt === void 0) { insertAt = null; }
  19447. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  19448. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  19449. return 0;
  19450. }
  19451. if (insertAt == null || insertAt < 0) {
  19452. this._postProcesses.push(postProcess);
  19453. }
  19454. else {
  19455. this._postProcesses.splice(insertAt, 0, postProcess);
  19456. }
  19457. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  19458. return this._postProcesses.indexOf(postProcess);
  19459. };
  19460. Camera.prototype.detachPostProcess = function (postProcess) {
  19461. var idx = this._postProcesses.indexOf(postProcess);
  19462. if (idx !== -1) {
  19463. this._postProcesses.splice(idx, 1);
  19464. }
  19465. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  19466. };
  19467. Camera.prototype.getWorldMatrix = function () {
  19468. if (!this._worldMatrix) {
  19469. this._worldMatrix = BABYLON.Matrix.Identity();
  19470. }
  19471. var viewMatrix = this.getViewMatrix();
  19472. viewMatrix.invertToRef(this._worldMatrix);
  19473. return this._worldMatrix;
  19474. };
  19475. Camera.prototype._getViewMatrix = function () {
  19476. return BABYLON.Matrix.Identity();
  19477. };
  19478. Camera.prototype.getViewMatrix = function (force) {
  19479. if (!force && this._isSynchronizedViewMatrix()) {
  19480. return this._computedViewMatrix;
  19481. }
  19482. this.updateCache();
  19483. this._computedViewMatrix = this._getViewMatrix();
  19484. this._currentRenderId = this.getScene().getRenderId();
  19485. this._refreshFrustumPlanes = true;
  19486. if (!this.parent || !this.parent.getWorldMatrix) {
  19487. this._globalPosition.copyFrom(this.position);
  19488. }
  19489. else {
  19490. if (!this._worldMatrix) {
  19491. this._worldMatrix = BABYLON.Matrix.Identity();
  19492. }
  19493. this._computedViewMatrix.invertToRef(this._worldMatrix);
  19494. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  19495. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  19496. this._computedViewMatrix.invert();
  19497. this._markSyncedWithParent();
  19498. }
  19499. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  19500. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  19501. }
  19502. this.onViewMatrixChangedObservable.notifyObservers(this);
  19503. return this._computedViewMatrix;
  19504. };
  19505. Camera.prototype.freezeProjectionMatrix = function (projection) {
  19506. this._doNotComputeProjectionMatrix = true;
  19507. if (projection !== undefined) {
  19508. this._projectionMatrix = projection;
  19509. }
  19510. };
  19511. ;
  19512. Camera.prototype.unfreezeProjectionMatrix = function () {
  19513. this._doNotComputeProjectionMatrix = false;
  19514. };
  19515. ;
  19516. Camera.prototype.getProjectionMatrix = function (force) {
  19517. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  19518. return this._projectionMatrix;
  19519. }
  19520. // Cache
  19521. this._cache.mode = this.mode;
  19522. this._cache.minZ = this.minZ;
  19523. this._cache.maxZ = this.maxZ;
  19524. // Matrix
  19525. this._refreshFrustumPlanes = true;
  19526. var engine = this.getEngine();
  19527. var scene = this.getScene();
  19528. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  19529. this._cache.fov = this.fov;
  19530. this._cache.fovMode = this.fovMode;
  19531. this._cache.aspectRatio = engine.getAspectRatio(this);
  19532. if (this.minZ <= 0) {
  19533. this.minZ = 0.1;
  19534. }
  19535. if (scene.useRightHandedSystem) {
  19536. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  19537. }
  19538. else {
  19539. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  19540. }
  19541. }
  19542. else {
  19543. var halfWidth = engine.getRenderWidth() / 2.0;
  19544. var halfHeight = engine.getRenderHeight() / 2.0;
  19545. if (scene.useRightHandedSystem) {
  19546. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  19547. }
  19548. else {
  19549. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  19550. }
  19551. this._cache.orthoLeft = this.orthoLeft;
  19552. this._cache.orthoRight = this.orthoRight;
  19553. this._cache.orthoBottom = this.orthoBottom;
  19554. this._cache.orthoTop = this.orthoTop;
  19555. this._cache.renderWidth = engine.getRenderWidth();
  19556. this._cache.renderHeight = engine.getRenderHeight();
  19557. }
  19558. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  19559. return this._projectionMatrix;
  19560. };
  19561. Camera.prototype.getTranformationMatrix = function () {
  19562. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  19563. return this._transformMatrix;
  19564. };
  19565. Camera.prototype.updateFrustumPlanes = function () {
  19566. if (!this._refreshFrustumPlanes) {
  19567. return;
  19568. }
  19569. this.getTranformationMatrix();
  19570. if (!this._frustumPlanes) {
  19571. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  19572. }
  19573. else {
  19574. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  19575. }
  19576. this._refreshFrustumPlanes = false;
  19577. };
  19578. Camera.prototype.isInFrustum = function (target) {
  19579. this.updateFrustumPlanes();
  19580. return target.isInFrustum(this._frustumPlanes);
  19581. };
  19582. Camera.prototype.isCompletelyInFrustum = function (target) {
  19583. this.updateFrustumPlanes();
  19584. return target.isCompletelyInFrustum(this._frustumPlanes);
  19585. };
  19586. Camera.prototype.getForwardRay = function (length, transform, origin) {
  19587. if (length === void 0) { length = 100; }
  19588. if (!transform) {
  19589. transform = this.getWorldMatrix();
  19590. }
  19591. if (!origin) {
  19592. origin = this.position;
  19593. }
  19594. var forward = new BABYLON.Vector3(0, 0, 1);
  19595. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  19596. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  19597. return new BABYLON.Ray(origin, direction, length);
  19598. };
  19599. Camera.prototype.dispose = function () {
  19600. // Observables
  19601. this.onViewMatrixChangedObservable.clear();
  19602. this.onProjectionMatrixChangedObservable.clear();
  19603. this.onAfterCheckInputsObservable.clear();
  19604. this.onRestoreStateObservable.clear();
  19605. // Inputs
  19606. if (this.inputs) {
  19607. this.inputs.clear();
  19608. }
  19609. // Animations
  19610. this.getScene().stopAnimation(this);
  19611. // Remove from scene
  19612. this.getScene().removeCamera(this);
  19613. while (this._rigCameras.length > 0) {
  19614. var camera = this._rigCameras.pop();
  19615. if (camera) {
  19616. camera.dispose();
  19617. }
  19618. }
  19619. // Postprocesses
  19620. if (this._rigPostProcess) {
  19621. this._rigPostProcess.dispose(this);
  19622. this._rigPostProcess = null;
  19623. this._postProcesses = [];
  19624. }
  19625. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  19626. this._rigPostProcess = null;
  19627. this._postProcesses = [];
  19628. }
  19629. else {
  19630. var i = this._postProcesses.length;
  19631. while (--i >= 0) {
  19632. this._postProcesses[i].dispose(this);
  19633. }
  19634. }
  19635. // Render targets
  19636. var i = this.customRenderTargets.length;
  19637. while (--i >= 0) {
  19638. this.customRenderTargets[i].dispose();
  19639. }
  19640. this.customRenderTargets = [];
  19641. // Active Meshes
  19642. this._activeMeshes.dispose();
  19643. _super.prototype.dispose.call(this);
  19644. };
  19645. Object.defineProperty(Camera.prototype, "leftCamera", {
  19646. // ---- Camera rigs section ----
  19647. get: function () {
  19648. if (this._rigCameras.length < 1) {
  19649. return null;
  19650. }
  19651. return this._rigCameras[0];
  19652. },
  19653. enumerable: true,
  19654. configurable: true
  19655. });
  19656. Object.defineProperty(Camera.prototype, "rightCamera", {
  19657. get: function () {
  19658. if (this._rigCameras.length < 2) {
  19659. return null;
  19660. }
  19661. return this._rigCameras[1];
  19662. },
  19663. enumerable: true,
  19664. configurable: true
  19665. });
  19666. Camera.prototype.getLeftTarget = function () {
  19667. if (this._rigCameras.length < 1) {
  19668. return null;
  19669. }
  19670. return this._rigCameras[0].getTarget();
  19671. };
  19672. Camera.prototype.getRightTarget = function () {
  19673. if (this._rigCameras.length < 2) {
  19674. return null;
  19675. }
  19676. return this._rigCameras[1].getTarget();
  19677. };
  19678. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  19679. if (this.cameraRigMode === mode) {
  19680. return;
  19681. }
  19682. while (this._rigCameras.length > 0) {
  19683. var camera = this._rigCameras.pop();
  19684. if (camera) {
  19685. camera.dispose();
  19686. }
  19687. }
  19688. this.cameraRigMode = mode;
  19689. this._cameraRigParams = {};
  19690. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  19691. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  19692. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  19693. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  19694. // create the rig cameras, unless none
  19695. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  19696. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  19697. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  19698. if (leftCamera && rightCamera) {
  19699. this._rigCameras.push(leftCamera);
  19700. this._rigCameras.push(rightCamera);
  19701. }
  19702. }
  19703. switch (this.cameraRigMode) {
  19704. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  19705. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  19706. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  19707. break;
  19708. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  19709. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  19710. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  19711. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  19712. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  19713. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  19714. break;
  19715. case Camera.RIG_MODE_VR:
  19716. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  19717. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  19718. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  19719. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  19720. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  19721. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  19722. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  19723. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  19724. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  19725. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  19726. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  19727. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  19728. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  19729. if (metrics.compensateDistortion) {
  19730. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  19731. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  19732. }
  19733. break;
  19734. case Camera.RIG_MODE_WEBVR:
  19735. if (rigParams.vrDisplay) {
  19736. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  19737. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  19738. //Left eye
  19739. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  19740. this._rigCameras[0].setCameraRigParameter("left", true);
  19741. //leaving this for future reference
  19742. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  19743. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  19744. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  19745. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  19746. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  19747. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  19748. this._rigCameras[0].parent = this;
  19749. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  19750. //Right eye
  19751. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  19752. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  19753. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  19754. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  19755. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  19756. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  19757. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  19758. this._rigCameras[1].parent = this;
  19759. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  19760. if (Camera.UseAlternateWebVRRendering) {
  19761. this._rigCameras[1]._skipRendering = true;
  19762. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  19763. }
  19764. }
  19765. break;
  19766. }
  19767. this._cascadePostProcessesToRigCams();
  19768. this.update();
  19769. };
  19770. Camera.prototype._getVRProjectionMatrix = function () {
  19771. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  19772. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  19773. return this._projectionMatrix;
  19774. };
  19775. Camera.prototype._updateCameraRotationMatrix = function () {
  19776. //Here for WebVR
  19777. };
  19778. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  19779. //Here for WebVR
  19780. };
  19781. /**
  19782. * This function MUST be overwritten by the different WebVR cameras available.
  19783. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  19784. */
  19785. Camera.prototype._getWebVRProjectionMatrix = function () {
  19786. return BABYLON.Matrix.Identity();
  19787. };
  19788. /**
  19789. * This function MUST be overwritten by the different WebVR cameras available.
  19790. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  19791. */
  19792. Camera.prototype._getWebVRViewMatrix = function () {
  19793. return BABYLON.Matrix.Identity();
  19794. };
  19795. Camera.prototype.setCameraRigParameter = function (name, value) {
  19796. if (!this._cameraRigParams) {
  19797. this._cameraRigParams = {};
  19798. }
  19799. this._cameraRigParams[name] = value;
  19800. //provisionnally:
  19801. if (name === "interaxialDistance") {
  19802. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  19803. }
  19804. };
  19805. /**
  19806. * needs to be overridden by children so sub has required properties to be copied
  19807. */
  19808. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  19809. return null;
  19810. };
  19811. /**
  19812. * May need to be overridden by children
  19813. */
  19814. Camera.prototype._updateRigCameras = function () {
  19815. for (var i = 0; i < this._rigCameras.length; i++) {
  19816. this._rigCameras[i].minZ = this.minZ;
  19817. this._rigCameras[i].maxZ = this.maxZ;
  19818. this._rigCameras[i].fov = this.fov;
  19819. }
  19820. // only update viewport when ANAGLYPH
  19821. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  19822. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  19823. }
  19824. };
  19825. Camera.prototype._setupInputs = function () {
  19826. };
  19827. Camera.prototype.serialize = function () {
  19828. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  19829. // Type
  19830. serializationObject.type = this.getClassName();
  19831. // Parent
  19832. if (this.parent) {
  19833. serializationObject.parentId = this.parent.id;
  19834. }
  19835. if (this.inputs) {
  19836. this.inputs.serialize(serializationObject);
  19837. }
  19838. // Animations
  19839. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  19840. serializationObject.ranges = this.serializeAnimationRanges();
  19841. return serializationObject;
  19842. };
  19843. Camera.prototype.clone = function (name) {
  19844. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  19845. };
  19846. Camera.prototype.getDirection = function (localAxis) {
  19847. var result = BABYLON.Vector3.Zero();
  19848. this.getDirectionToRef(localAxis, result);
  19849. return result;
  19850. };
  19851. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  19852. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  19853. };
  19854. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  19855. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  19856. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  19857. switch (type) {
  19858. case "ArcRotateCamera":
  19859. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  19860. case "DeviceOrientationCamera":
  19861. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  19862. case "FollowCamera":
  19863. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  19864. case "ArcFollowCamera":
  19865. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  19866. case "GamepadCamera":
  19867. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  19868. case "TouchCamera":
  19869. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  19870. case "VirtualJoysticksCamera":
  19871. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  19872. case "WebVRFreeCamera":
  19873. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  19874. case "WebVRGamepadCamera":
  19875. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  19876. case "VRDeviceOrientationFreeCamera":
  19877. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  19878. case "VRDeviceOrientationGamepadCamera":
  19879. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  19880. case "AnaglyphArcRotateCamera":
  19881. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  19882. case "AnaglyphFreeCamera":
  19883. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  19884. case "AnaglyphGamepadCamera":
  19885. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  19886. case "AnaglyphUniversalCamera":
  19887. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  19888. case "StereoscopicArcRotateCamera":
  19889. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  19890. case "StereoscopicFreeCamera":
  19891. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  19892. case "StereoscopicGamepadCamera":
  19893. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  19894. case "StereoscopicUniversalCamera":
  19895. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  19896. case "FreeCamera":// Forcing Universal here
  19897. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  19898. default:// Universal Camera is the default value
  19899. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  19900. }
  19901. };
  19902. Camera.prototype.computeWorldMatrix = function () {
  19903. return this.getWorldMatrix();
  19904. };
  19905. Camera.Parse = function (parsedCamera, scene) {
  19906. var type = parsedCamera.type;
  19907. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  19908. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  19909. // Parent
  19910. if (parsedCamera.parentId) {
  19911. camera._waitingParentId = parsedCamera.parentId;
  19912. }
  19913. //If camera has an input manager, let it parse inputs settings
  19914. if (camera.inputs) {
  19915. camera.inputs.parse(parsedCamera);
  19916. camera._setupInputs();
  19917. }
  19918. if (camera.setPosition) {
  19919. camera.position.copyFromFloats(0, 0, 0);
  19920. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  19921. }
  19922. // Target
  19923. if (parsedCamera.target) {
  19924. if (camera.setTarget) {
  19925. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  19926. }
  19927. }
  19928. // Apply 3d rig, when found
  19929. if (parsedCamera.cameraRigMode) {
  19930. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  19931. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  19932. }
  19933. // Animations
  19934. if (parsedCamera.animations) {
  19935. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  19936. var parsedAnimation = parsedCamera.animations[animationIndex];
  19937. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  19938. }
  19939. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  19940. }
  19941. if (parsedCamera.autoAnimate) {
  19942. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  19943. }
  19944. return camera;
  19945. };
  19946. // Statics
  19947. Camera._PERSPECTIVE_CAMERA = 0;
  19948. Camera._ORTHOGRAPHIC_CAMERA = 1;
  19949. Camera._FOVMODE_VERTICAL_FIXED = 0;
  19950. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  19951. Camera._RIG_MODE_NONE = 0;
  19952. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  19953. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  19954. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  19955. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  19956. Camera._RIG_MODE_VR = 20;
  19957. Camera._RIG_MODE_WEBVR = 21;
  19958. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  19959. Camera.UseAlternateWebVRRendering = false;
  19960. __decorate([
  19961. BABYLON.serializeAsVector3()
  19962. ], Camera.prototype, "position", void 0);
  19963. __decorate([
  19964. BABYLON.serializeAsVector3()
  19965. ], Camera.prototype, "upVector", void 0);
  19966. __decorate([
  19967. BABYLON.serialize()
  19968. ], Camera.prototype, "orthoLeft", void 0);
  19969. __decorate([
  19970. BABYLON.serialize()
  19971. ], Camera.prototype, "orthoRight", void 0);
  19972. __decorate([
  19973. BABYLON.serialize()
  19974. ], Camera.prototype, "orthoBottom", void 0);
  19975. __decorate([
  19976. BABYLON.serialize()
  19977. ], Camera.prototype, "orthoTop", void 0);
  19978. __decorate([
  19979. BABYLON.serialize()
  19980. ], Camera.prototype, "fov", void 0);
  19981. __decorate([
  19982. BABYLON.serialize()
  19983. ], Camera.prototype, "minZ", void 0);
  19984. __decorate([
  19985. BABYLON.serialize()
  19986. ], Camera.prototype, "maxZ", void 0);
  19987. __decorate([
  19988. BABYLON.serialize()
  19989. ], Camera.prototype, "inertia", void 0);
  19990. __decorate([
  19991. BABYLON.serialize()
  19992. ], Camera.prototype, "mode", void 0);
  19993. __decorate([
  19994. BABYLON.serialize()
  19995. ], Camera.prototype, "layerMask", void 0);
  19996. __decorate([
  19997. BABYLON.serialize()
  19998. ], Camera.prototype, "fovMode", void 0);
  19999. __decorate([
  20000. BABYLON.serialize()
  20001. ], Camera.prototype, "cameraRigMode", void 0);
  20002. __decorate([
  20003. BABYLON.serialize()
  20004. ], Camera.prototype, "interaxialDistance", void 0);
  20005. __decorate([
  20006. BABYLON.serialize()
  20007. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  20008. return Camera;
  20009. }(BABYLON.Node));
  20010. BABYLON.Camera = Camera;
  20011. })(BABYLON || (BABYLON = {}));
  20012. //# sourceMappingURL=babylon.camera.js.map
  20013. var BABYLON;
  20014. (function (BABYLON) {
  20015. var RenderingManager = /** @class */ (function () {
  20016. function RenderingManager(scene) {
  20017. this._renderingGroups = new Array();
  20018. this._autoClearDepthStencil = {};
  20019. this._customOpaqueSortCompareFn = {};
  20020. this._customAlphaTestSortCompareFn = {};
  20021. this._customTransparentSortCompareFn = {};
  20022. this._renderinGroupInfo = null;
  20023. this._scene = scene;
  20024. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  20025. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  20026. }
  20027. }
  20028. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  20029. if (depth === void 0) { depth = true; }
  20030. if (stencil === void 0) { stencil = true; }
  20031. if (this._depthStencilBufferAlreadyCleaned) {
  20032. return;
  20033. }
  20034. this._scene.getEngine().clear(null, false, depth, stencil);
  20035. this._depthStencilBufferAlreadyCleaned = true;
  20036. };
  20037. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  20038. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  20039. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  20040. var info = null;
  20041. if (observable) {
  20042. if (!this._renderinGroupInfo) {
  20043. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  20044. }
  20045. info = this._renderinGroupInfo;
  20046. info.scene = this._scene;
  20047. info.camera = this._scene.activeCamera;
  20048. }
  20049. // Dispatch sprites
  20050. if (renderSprites) {
  20051. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  20052. var manager = this._scene.spriteManagers[index];
  20053. this.dispatchSprites(manager);
  20054. }
  20055. }
  20056. // Render
  20057. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  20058. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  20059. var renderingGroup = this._renderingGroups[index];
  20060. if (!renderingGroup && !observable)
  20061. continue;
  20062. var renderingGroupMask = 0;
  20063. // Fire PRECLEAR stage
  20064. if (observable && info) {
  20065. renderingGroupMask = Math.pow(2, index);
  20066. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  20067. info.renderingGroupId = index;
  20068. observable.notifyObservers(info, renderingGroupMask);
  20069. }
  20070. // Clear depth/stencil if needed
  20071. if (RenderingManager.AUTOCLEAR) {
  20072. var autoClear = this._autoClearDepthStencil[index];
  20073. if (autoClear && autoClear.autoClear) {
  20074. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  20075. }
  20076. }
  20077. if (observable && info) {
  20078. // Fire PREOPAQUE stage
  20079. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  20080. observable.notifyObservers(info, renderingGroupMask);
  20081. // Fire PRETRANSPARENT stage
  20082. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  20083. observable.notifyObservers(info, renderingGroupMask);
  20084. }
  20085. if (renderingGroup)
  20086. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  20087. // Fire POSTTRANSPARENT stage
  20088. if (observable && info) {
  20089. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  20090. observable.notifyObservers(info, renderingGroupMask);
  20091. }
  20092. }
  20093. };
  20094. RenderingManager.prototype.reset = function () {
  20095. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  20096. var renderingGroup = this._renderingGroups[index];
  20097. if (renderingGroup) {
  20098. renderingGroup.prepare();
  20099. }
  20100. }
  20101. };
  20102. RenderingManager.prototype.dispose = function () {
  20103. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  20104. var renderingGroup = this._renderingGroups[index];
  20105. if (renderingGroup) {
  20106. renderingGroup.dispose();
  20107. }
  20108. }
  20109. this._renderingGroups.length = 0;
  20110. };
  20111. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  20112. if (this._renderingGroups[renderingGroupId] === undefined) {
  20113. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  20114. }
  20115. };
  20116. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  20117. var renderingGroupId = spriteManager.renderingGroupId || 0;
  20118. this._prepareRenderingGroup(renderingGroupId);
  20119. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  20120. };
  20121. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  20122. var renderingGroupId = particleSystem.renderingGroupId || 0;
  20123. this._prepareRenderingGroup(renderingGroupId);
  20124. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  20125. };
  20126. /**
  20127. * @param subMesh The submesh to dispatch
  20128. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  20129. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  20130. */
  20131. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  20132. if (mesh === undefined) {
  20133. mesh = subMesh.getMesh();
  20134. }
  20135. var renderingGroupId = mesh.renderingGroupId || 0;
  20136. this._prepareRenderingGroup(renderingGroupId);
  20137. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  20138. };
  20139. /**
  20140. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  20141. * This allowed control for front to back rendering or reversly depending of the special needs.
  20142. *
  20143. * @param renderingGroupId The rendering group id corresponding to its index
  20144. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  20145. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  20146. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  20147. */
  20148. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  20149. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  20150. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  20151. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  20152. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  20153. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  20154. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  20155. if (this._renderingGroups[renderingGroupId]) {
  20156. var group = this._renderingGroups[renderingGroupId];
  20157. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  20158. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  20159. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  20160. }
  20161. };
  20162. /**
  20163. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  20164. *
  20165. * @param renderingGroupId The rendering group id corresponding to its index
  20166. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  20167. * @param depth Automatically clears depth between groups if true and autoClear is true.
  20168. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  20169. */
  20170. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  20171. if (depth === void 0) { depth = true; }
  20172. if (stencil === void 0) { stencil = true; }
  20173. this._autoClearDepthStencil[renderingGroupId] = {
  20174. autoClear: autoClearDepthStencil,
  20175. depth: depth,
  20176. stencil: stencil
  20177. };
  20178. };
  20179. /**
  20180. * The max id used for rendering groups (not included)
  20181. */
  20182. RenderingManager.MAX_RENDERINGGROUPS = 4;
  20183. /**
  20184. * The min id used for rendering groups (included)
  20185. */
  20186. RenderingManager.MIN_RENDERINGGROUPS = 0;
  20187. /**
  20188. * Used to globally prevent autoclearing scenes.
  20189. */
  20190. RenderingManager.AUTOCLEAR = true;
  20191. return RenderingManager;
  20192. }());
  20193. BABYLON.RenderingManager = RenderingManager;
  20194. })(BABYLON || (BABYLON = {}));
  20195. //# sourceMappingURL=babylon.renderingManager.js.map
  20196. var BABYLON;
  20197. (function (BABYLON) {
  20198. var RenderingGroup = /** @class */ (function () {
  20199. /**
  20200. * Creates a new rendering group.
  20201. * @param index The rendering group index
  20202. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  20203. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  20204. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  20205. */
  20206. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  20207. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  20208. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  20209. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  20210. this.index = index;
  20211. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  20212. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  20213. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  20214. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  20215. this._particleSystems = new BABYLON.SmartArray(256);
  20216. this._spriteManagers = new BABYLON.SmartArray(256);
  20217. this._edgesRenderers = new BABYLON.SmartArray(16);
  20218. this._scene = scene;
  20219. this.opaqueSortCompareFn = opaqueSortCompareFn;
  20220. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  20221. this.transparentSortCompareFn = transparentSortCompareFn;
  20222. }
  20223. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  20224. /**
  20225. * Set the opaque sort comparison function.
  20226. * If null the sub meshes will be render in the order they were created
  20227. */
  20228. set: function (value) {
  20229. this._opaqueSortCompareFn = value;
  20230. if (value) {
  20231. this._renderOpaque = this.renderOpaqueSorted;
  20232. }
  20233. else {
  20234. this._renderOpaque = RenderingGroup.renderUnsorted;
  20235. }
  20236. },
  20237. enumerable: true,
  20238. configurable: true
  20239. });
  20240. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  20241. /**
  20242. * Set the alpha test sort comparison function.
  20243. * If null the sub meshes will be render in the order they were created
  20244. */
  20245. set: function (value) {
  20246. this._alphaTestSortCompareFn = value;
  20247. if (value) {
  20248. this._renderAlphaTest = this.renderAlphaTestSorted;
  20249. }
  20250. else {
  20251. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  20252. }
  20253. },
  20254. enumerable: true,
  20255. configurable: true
  20256. });
  20257. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  20258. /**
  20259. * Set the transparent sort comparison function.
  20260. * If null the sub meshes will be render in the order they were created
  20261. */
  20262. set: function (value) {
  20263. if (value) {
  20264. this._transparentSortCompareFn = value;
  20265. }
  20266. else {
  20267. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  20268. }
  20269. this._renderTransparent = this.renderTransparentSorted;
  20270. },
  20271. enumerable: true,
  20272. configurable: true
  20273. });
  20274. /**
  20275. * Render all the sub meshes contained in the group.
  20276. * @param customRenderFunction Used to override the default render behaviour of the group.
  20277. * @returns true if rendered some submeshes.
  20278. */
  20279. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  20280. if (customRenderFunction) {
  20281. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  20282. return;
  20283. }
  20284. var engine = this._scene.getEngine();
  20285. // Depth only
  20286. if (this._depthOnlySubMeshes.length !== 0) {
  20287. engine.setColorWrite(false);
  20288. this._renderAlphaTest(this._depthOnlySubMeshes);
  20289. engine.setColorWrite(true);
  20290. }
  20291. // Opaque
  20292. if (this._opaqueSubMeshes.length !== 0) {
  20293. this._renderOpaque(this._opaqueSubMeshes);
  20294. }
  20295. // Alpha test
  20296. if (this._alphaTestSubMeshes.length !== 0) {
  20297. this._renderAlphaTest(this._alphaTestSubMeshes);
  20298. }
  20299. var stencilState = engine.getStencilBuffer();
  20300. engine.setStencilBuffer(false);
  20301. // Sprites
  20302. if (renderSprites) {
  20303. this._renderSprites();
  20304. }
  20305. // Particles
  20306. if (renderParticles) {
  20307. this._renderParticles(activeMeshes);
  20308. }
  20309. if (this.onBeforeTransparentRendering) {
  20310. this.onBeforeTransparentRendering();
  20311. }
  20312. // Transparent
  20313. if (this._transparentSubMeshes.length !== 0) {
  20314. this._renderTransparent(this._transparentSubMeshes);
  20315. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  20316. }
  20317. // Set back stencil to false in case it changes before the edge renderer.
  20318. engine.setStencilBuffer(false);
  20319. // Edges
  20320. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  20321. this._edgesRenderers.data[edgesRendererIndex].render();
  20322. }
  20323. // Restore Stencil state.
  20324. engine.setStencilBuffer(stencilState);
  20325. };
  20326. /**
  20327. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  20328. * @param subMeshes The submeshes to render
  20329. */
  20330. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  20331. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  20332. };
  20333. /**
  20334. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  20335. * @param subMeshes The submeshes to render
  20336. */
  20337. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  20338. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  20339. };
  20340. /**
  20341. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  20342. * @param subMeshes The submeshes to render
  20343. */
  20344. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  20345. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  20346. };
  20347. /**
  20348. * Renders the submeshes in a specified order.
  20349. * @param subMeshes The submeshes to sort before render
  20350. * @param sortCompareFn The comparison function use to sort
  20351. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  20352. * @param transparent Specifies to activate blending if true
  20353. */
  20354. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  20355. var subIndex = 0;
  20356. var subMesh;
  20357. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  20358. for (; subIndex < subMeshes.length; subIndex++) {
  20359. subMesh = subMeshes.data[subIndex];
  20360. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  20361. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  20362. }
  20363. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  20364. if (sortCompareFn) {
  20365. sortedArray.sort(sortCompareFn);
  20366. }
  20367. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  20368. subMesh = sortedArray[subIndex];
  20369. if (transparent) {
  20370. var material = subMesh.getMaterial();
  20371. if (material && material.needDepthPrePass) {
  20372. var engine = material.getScene().getEngine();
  20373. engine.setColorWrite(false);
  20374. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  20375. subMesh.render(false);
  20376. engine.setColorWrite(true);
  20377. }
  20378. }
  20379. subMesh.render(transparent);
  20380. }
  20381. };
  20382. /**
  20383. * Renders the submeshes in the order they were dispatched (no sort applied).
  20384. * @param subMeshes The submeshes to render
  20385. */
  20386. RenderingGroup.renderUnsorted = function (subMeshes) {
  20387. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  20388. var submesh = subMeshes.data[subIndex];
  20389. submesh.render(false);
  20390. }
  20391. };
  20392. /**
  20393. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  20394. * are rendered back to front if in the same alpha index.
  20395. *
  20396. * @param a The first submesh
  20397. * @param b The second submesh
  20398. * @returns The result of the comparison
  20399. */
  20400. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  20401. // Alpha index first
  20402. if (a._alphaIndex > b._alphaIndex) {
  20403. return 1;
  20404. }
  20405. if (a._alphaIndex < b._alphaIndex) {
  20406. return -1;
  20407. }
  20408. // Then distance to camera
  20409. return RenderingGroup.backToFrontSortCompare(a, b);
  20410. };
  20411. /**
  20412. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  20413. * are rendered back to front.
  20414. *
  20415. * @param a The first submesh
  20416. * @param b The second submesh
  20417. * @returns The result of the comparison
  20418. */
  20419. RenderingGroup.backToFrontSortCompare = function (a, b) {
  20420. // Then distance to camera
  20421. if (a._distanceToCamera < b._distanceToCamera) {
  20422. return 1;
  20423. }
  20424. if (a._distanceToCamera > b._distanceToCamera) {
  20425. return -1;
  20426. }
  20427. return 0;
  20428. };
  20429. /**
  20430. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  20431. * are rendered front to back (prevent overdraw).
  20432. *
  20433. * @param a The first submesh
  20434. * @param b The second submesh
  20435. * @returns The result of the comparison
  20436. */
  20437. RenderingGroup.frontToBackSortCompare = function (a, b) {
  20438. // Then distance to camera
  20439. if (a._distanceToCamera < b._distanceToCamera) {
  20440. return -1;
  20441. }
  20442. if (a._distanceToCamera > b._distanceToCamera) {
  20443. return 1;
  20444. }
  20445. return 0;
  20446. };
  20447. /**
  20448. * Resets the different lists of submeshes to prepare a new frame.
  20449. */
  20450. RenderingGroup.prototype.prepare = function () {
  20451. this._opaqueSubMeshes.reset();
  20452. this._transparentSubMeshes.reset();
  20453. this._alphaTestSubMeshes.reset();
  20454. this._depthOnlySubMeshes.reset();
  20455. this._particleSystems.reset();
  20456. this._spriteManagers.reset();
  20457. this._edgesRenderers.reset();
  20458. };
  20459. RenderingGroup.prototype.dispose = function () {
  20460. this._opaqueSubMeshes.dispose();
  20461. this._transparentSubMeshes.dispose();
  20462. this._alphaTestSubMeshes.dispose();
  20463. this._depthOnlySubMeshes.dispose();
  20464. this._particleSystems.dispose();
  20465. this._spriteManagers.dispose();
  20466. this._edgesRenderers.dispose();
  20467. };
  20468. /**
  20469. * Inserts the submesh in its correct queue depending on its material.
  20470. * @param subMesh The submesh to dispatch
  20471. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  20472. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  20473. */
  20474. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  20475. // Get mesh and materials if not provided
  20476. if (mesh === undefined) {
  20477. mesh = subMesh.getMesh();
  20478. }
  20479. if (material === undefined) {
  20480. material = subMesh.getMaterial();
  20481. }
  20482. if (material === null || material === undefined) {
  20483. return;
  20484. }
  20485. if (material.needAlphaBlendingForMesh(mesh)) {
  20486. this._transparentSubMeshes.push(subMesh);
  20487. }
  20488. else if (material.needAlphaTesting()) {
  20489. if (material.needDepthPrePass) {
  20490. this._depthOnlySubMeshes.push(subMesh);
  20491. }
  20492. this._alphaTestSubMeshes.push(subMesh);
  20493. }
  20494. else {
  20495. if (material.needDepthPrePass) {
  20496. this._depthOnlySubMeshes.push(subMesh);
  20497. }
  20498. this._opaqueSubMeshes.push(subMesh); // Opaque
  20499. }
  20500. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined) {
  20501. this._edgesRenderers.push(mesh._edgesRenderer);
  20502. }
  20503. };
  20504. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  20505. this._spriteManagers.push(spriteManager);
  20506. };
  20507. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  20508. this._particleSystems.push(particleSystem);
  20509. };
  20510. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  20511. if (this._particleSystems.length === 0) {
  20512. return;
  20513. }
  20514. // Particles
  20515. var activeCamera = this._scene.activeCamera;
  20516. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  20517. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  20518. var particleSystem = this._particleSystems.data[particleIndex];
  20519. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  20520. continue;
  20521. }
  20522. var emitter = particleSystem.emitter;
  20523. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  20524. this._scene._activeParticles.addCount(particleSystem.render(), false);
  20525. }
  20526. }
  20527. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  20528. };
  20529. RenderingGroup.prototype._renderSprites = function () {
  20530. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  20531. return;
  20532. }
  20533. // Sprites
  20534. var activeCamera = this._scene.activeCamera;
  20535. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  20536. for (var id = 0; id < this._spriteManagers.length; id++) {
  20537. var spriteManager = this._spriteManagers.data[id];
  20538. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  20539. spriteManager.render();
  20540. }
  20541. }
  20542. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  20543. };
  20544. return RenderingGroup;
  20545. }());
  20546. BABYLON.RenderingGroup = RenderingGroup;
  20547. })(BABYLON || (BABYLON = {}));
  20548. //# sourceMappingURL=babylon.renderingGroup.js.map
  20549. var BABYLON;
  20550. (function (BABYLON) {
  20551. var ClickInfo = /** @class */ (function () {
  20552. function ClickInfo() {
  20553. this._singleClick = false;
  20554. this._doubleClick = false;
  20555. this._hasSwiped = false;
  20556. this._ignore = false;
  20557. }
  20558. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  20559. get: function () {
  20560. return this._singleClick;
  20561. },
  20562. set: function (b) {
  20563. this._singleClick = b;
  20564. },
  20565. enumerable: true,
  20566. configurable: true
  20567. });
  20568. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  20569. get: function () {
  20570. return this._doubleClick;
  20571. },
  20572. set: function (b) {
  20573. this._doubleClick = b;
  20574. },
  20575. enumerable: true,
  20576. configurable: true
  20577. });
  20578. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  20579. get: function () {
  20580. return this._hasSwiped;
  20581. },
  20582. set: function (b) {
  20583. this._hasSwiped = b;
  20584. },
  20585. enumerable: true,
  20586. configurable: true
  20587. });
  20588. Object.defineProperty(ClickInfo.prototype, "ignore", {
  20589. get: function () {
  20590. return this._ignore;
  20591. },
  20592. set: function (b) {
  20593. this._ignore = b;
  20594. },
  20595. enumerable: true,
  20596. configurable: true
  20597. });
  20598. return ClickInfo;
  20599. }());
  20600. /**
  20601. * This class is used by the onRenderingGroupObservable
  20602. */
  20603. var RenderingGroupInfo = /** @class */ (function () {
  20604. function RenderingGroupInfo() {
  20605. }
  20606. /**
  20607. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  20608. * This stage will be fired no matter what
  20609. */
  20610. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  20611. /**
  20612. * Called before opaque object are rendered.
  20613. * This stage will be fired only if there's 3D Opaque content to render
  20614. */
  20615. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  20616. /**
  20617. * Called after the opaque objects are rendered and before the transparent ones
  20618. * This stage will be fired only if there's 3D transparent content to render
  20619. */
  20620. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  20621. /**
  20622. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  20623. * This stage will be fired no matter what
  20624. */
  20625. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  20626. return RenderingGroupInfo;
  20627. }());
  20628. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  20629. /**
  20630. * Represents a scene to be rendered by the engine.
  20631. * @see http://doc.babylonjs.com/page.php?p=21911
  20632. */
  20633. var Scene = /** @class */ (function () {
  20634. /**
  20635. * @constructor
  20636. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  20637. */
  20638. function Scene(engine) {
  20639. // Members
  20640. this.autoClear = true;
  20641. this.autoClearDepthAndStencil = true;
  20642. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  20643. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  20644. this.forceWireframe = false;
  20645. this._forcePointsCloud = false;
  20646. this.forceShowBoundingBoxes = false;
  20647. this.animationsEnabled = true;
  20648. this.useConstantAnimationDeltaTime = false;
  20649. this.constantlyUpdateMeshUnderPointer = false;
  20650. this.hoverCursor = "pointer";
  20651. this.defaultCursor = "";
  20652. /**
  20653. * This is used to call preventDefault() on pointer down
  20654. * in order to block unwanted artifacts like system double clicks
  20655. */
  20656. this.preventDefaultOnPointerDown = true;
  20657. // Metadata
  20658. this.metadata = null;
  20659. /**
  20660. * An event triggered when the scene is disposed.
  20661. * @type {BABYLON.Observable}
  20662. */
  20663. this.onDisposeObservable = new BABYLON.Observable();
  20664. /**
  20665. * An event triggered before rendering the scene (right after animations and physics)
  20666. * @type {BABYLON.Observable}
  20667. */
  20668. this.onBeforeRenderObservable = new BABYLON.Observable();
  20669. /**
  20670. * An event triggered after rendering the scene
  20671. * @type {BABYLON.Observable}
  20672. */
  20673. this.onAfterRenderObservable = new BABYLON.Observable();
  20674. /**
  20675. * An event triggered before animating the scene
  20676. * @type {BABYLON.Observable}
  20677. */
  20678. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  20679. /**
  20680. * An event triggered after animations processing
  20681. * @type {BABYLON.Observable}
  20682. */
  20683. this.onAfterAnimationsObservable = new BABYLON.Observable();
  20684. /**
  20685. * An event triggered before draw calls are ready to be sent
  20686. * @type {BABYLON.Observable}
  20687. */
  20688. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  20689. /**
  20690. * An event triggered after draw calls have been sent
  20691. * @type {BABYLON.Observable}
  20692. */
  20693. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  20694. /**
  20695. * An event triggered when physic simulation is about to be run
  20696. * @type {BABYLON.Observable}
  20697. */
  20698. this.onBeforePhysicsObservable = new BABYLON.Observable();
  20699. /**
  20700. * An event triggered when physic simulation has been done
  20701. * @type {BABYLON.Observable}
  20702. */
  20703. this.onAfterPhysicsObservable = new BABYLON.Observable();
  20704. /**
  20705. * An event triggered when the scene is ready
  20706. * @type {BABYLON.Observable}
  20707. */
  20708. this.onReadyObservable = new BABYLON.Observable();
  20709. /**
  20710. * An event triggered before rendering a camera
  20711. * @type {BABYLON.Observable}
  20712. */
  20713. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  20714. /**
  20715. * An event triggered after rendering a camera
  20716. * @type {BABYLON.Observable}
  20717. */
  20718. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  20719. /**
  20720. * An event triggered when active meshes evaluation is about to start
  20721. * @type {BABYLON.Observable}
  20722. */
  20723. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  20724. /**
  20725. * An event triggered when active meshes evaluation is done
  20726. * @type {BABYLON.Observable}
  20727. */
  20728. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  20729. /**
  20730. * An event triggered when particles rendering is about to start
  20731. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  20732. * @type {BABYLON.Observable}
  20733. */
  20734. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  20735. /**
  20736. * An event triggered when particles rendering is done
  20737. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  20738. * @type {BABYLON.Observable}
  20739. */
  20740. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  20741. /**
  20742. * An event triggered when sprites rendering is about to start
  20743. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  20744. * @type {BABYLON.Observable}
  20745. */
  20746. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  20747. /**
  20748. * An event triggered when sprites rendering is done
  20749. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  20750. * @type {BABYLON.Observable}
  20751. */
  20752. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  20753. /**
  20754. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  20755. * @type {BABYLON.Observable}
  20756. */
  20757. this.onDataLoadedObservable = new BABYLON.Observable();
  20758. /**
  20759. * An event triggered when a camera is created
  20760. * @type {BABYLON.Observable}
  20761. */
  20762. this.onNewCameraAddedObservable = new BABYLON.Observable();
  20763. /**
  20764. * An event triggered when a camera is removed
  20765. * @type {BABYLON.Observable}
  20766. */
  20767. this.onCameraRemovedObservable = new BABYLON.Observable();
  20768. /**
  20769. * An event triggered when a light is created
  20770. * @type {BABYLON.Observable}
  20771. */
  20772. this.onNewLightAddedObservable = new BABYLON.Observable();
  20773. /**
  20774. * An event triggered when a light is removed
  20775. * @type {BABYLON.Observable}
  20776. */
  20777. this.onLightRemovedObservable = new BABYLON.Observable();
  20778. /**
  20779. * An event triggered when a geometry is created
  20780. * @type {BABYLON.Observable}
  20781. */
  20782. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  20783. /**
  20784. * An event triggered when a geometry is removed
  20785. * @type {BABYLON.Observable}
  20786. */
  20787. this.onGeometryRemovedObservable = new BABYLON.Observable();
  20788. /**
  20789. * An event triggered when a transform node is created
  20790. * @type {BABYLON.Observable}
  20791. */
  20792. this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  20793. /**
  20794. * An event triggered when a transform node is removed
  20795. * @type {BABYLON.Observable}
  20796. */
  20797. this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  20798. /**
  20799. * An event triggered when a mesh is created
  20800. * @type {BABYLON.Observable}
  20801. */
  20802. this.onNewMeshAddedObservable = new BABYLON.Observable();
  20803. /**
  20804. * An event triggered when a mesh is removed
  20805. * @type {BABYLON.Observable}
  20806. */
  20807. this.onMeshRemovedObservable = new BABYLON.Observable();
  20808. /**
  20809. * An event triggered when render targets are about to be rendered
  20810. * Can happen multiple times per frame.
  20811. * @type {BABYLON.Observable}
  20812. */
  20813. this.OnBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  20814. /**
  20815. * An event triggered when render targets were rendered.
  20816. * Can happen multiple times per frame.
  20817. * @type {BABYLON.Observable}
  20818. */
  20819. this.OnAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  20820. /**
  20821. * An event triggered before calculating deterministic simulation step
  20822. * @type {BABYLON.Observable}
  20823. */
  20824. this.onBeforeStepObservable = new BABYLON.Observable();
  20825. /**
  20826. * An event triggered after calculating deterministic simulation step
  20827. * @type {BABYLON.Observable}
  20828. */
  20829. this.onAfterStepObservable = new BABYLON.Observable();
  20830. /**
  20831. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  20832. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  20833. * 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)
  20834. */
  20835. this.onRenderingGroupObservable = new BABYLON.Observable();
  20836. // Animations
  20837. this.animations = [];
  20838. /**
  20839. * 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).
  20840. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  20841. */
  20842. this.onPrePointerObservable = new BABYLON.Observable();
  20843. /**
  20844. * Observable event triggered each time an input event is received from the rendering canvas
  20845. */
  20846. this.onPointerObservable = new BABYLON.Observable();
  20847. this._meshPickProceed = false;
  20848. this._currentPickResult = null;
  20849. this._previousPickResult = null;
  20850. this._totalPointersPressed = 0;
  20851. this._doubleClickOccured = false;
  20852. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  20853. this.cameraToUseForPointers = null;
  20854. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  20855. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  20856. this._startingPointerTime = 0;
  20857. this._previousStartingPointerTime = 0;
  20858. // Deterministic lockstep
  20859. this._timeAccumulator = 0;
  20860. this._currentStepId = 0;
  20861. this._currentInternalStep = 0;
  20862. // Keyboard
  20863. /**
  20864. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  20865. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  20866. */
  20867. this.onPreKeyboardObservable = new BABYLON.Observable();
  20868. /**
  20869. * Observable event triggered each time an keyboard event is received from the hosting window
  20870. */
  20871. this.onKeyboardObservable = new BABYLON.Observable();
  20872. // Coordinate system
  20873. /**
  20874. * use right-handed coordinate system on this scene.
  20875. * @type {boolean}
  20876. */
  20877. this._useRightHandedSystem = false;
  20878. // Fog
  20879. this._fogEnabled = true;
  20880. this._fogMode = Scene.FOGMODE_NONE;
  20881. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  20882. this.fogDensity = 0.1;
  20883. this.fogStart = 0;
  20884. this.fogEnd = 1000.0;
  20885. // Lights
  20886. /**
  20887. * is shadow enabled on this scene.
  20888. * @type {boolean}
  20889. */
  20890. this._shadowsEnabled = true;
  20891. /**
  20892. * is light enabled on this scene.
  20893. * @type {boolean}
  20894. */
  20895. this._lightsEnabled = true;
  20896. /**
  20897. * All of the lights added to this scene.
  20898. * @see BABYLON.Light
  20899. * @type {BABYLON.Light[]}
  20900. */
  20901. this.lights = new Array();
  20902. // Cameras
  20903. /** All of the cameras added to this scene. */
  20904. this.cameras = new Array();
  20905. /** All of the active cameras added to this scene. */
  20906. this.activeCameras = new Array();
  20907. // Meshes
  20908. /**
  20909. * All of the tranform nodes added to this scene.
  20910. * @see BABYLON.TransformNode
  20911. * @type {BABYLON.TransformNode[]}
  20912. */
  20913. this.transformNodes = new Array();
  20914. /**
  20915. * All of the (abstract) meshes added to this scene.
  20916. * @see BABYLON.AbstractMesh
  20917. * @type {BABYLON.AbstractMesh[]}
  20918. */
  20919. this.meshes = new Array();
  20920. /**
  20921. * All of the animation groups added to this scene.
  20922. * @see BABYLON.AnimationGroup
  20923. * @type {BABYLON.AnimationGroup[]}
  20924. */
  20925. this.animationGroups = new Array();
  20926. // Geometries
  20927. this._geometries = new Array();
  20928. this.materials = new Array();
  20929. this.multiMaterials = new Array();
  20930. // Textures
  20931. this._texturesEnabled = true;
  20932. this.textures = new Array();
  20933. // Particles
  20934. this.particlesEnabled = true;
  20935. this.particleSystems = new Array();
  20936. // Sprites
  20937. this.spritesEnabled = true;
  20938. this.spriteManagers = new Array();
  20939. /**
  20940. * The list of layers (background and foreground) of the scene.
  20941. */
  20942. this.layers = new Array();
  20943. /**
  20944. * The list of effect layers (highlights/glow) contained in the scene.
  20945. */
  20946. this.effectLayers = new Array();
  20947. // Skeletons
  20948. this._skeletonsEnabled = true;
  20949. this.skeletons = new Array();
  20950. // Morph targets
  20951. this.morphTargetManagers = new Array();
  20952. // Lens flares
  20953. this.lensFlaresEnabled = true;
  20954. this.lensFlareSystems = new Array();
  20955. // Collisions
  20956. this.collisionsEnabled = true;
  20957. /** Defines the gravity applied to this scene */
  20958. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  20959. // Postprocesses
  20960. this.postProcesses = new Array();
  20961. this.postProcessesEnabled = true;
  20962. // Customs render targets
  20963. this.renderTargetsEnabled = true;
  20964. this.dumpNextRenderTargets = false;
  20965. this.customRenderTargets = new Array();
  20966. // Imported meshes
  20967. this.importedMeshesFiles = new Array();
  20968. // Probes
  20969. this.probesEnabled = true;
  20970. this.reflectionProbes = new Array();
  20971. this._actionManagers = new Array();
  20972. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  20973. // Procedural textures
  20974. this.proceduralTexturesEnabled = true;
  20975. this._proceduralTextures = new Array();
  20976. this.soundTracks = new Array();
  20977. this._audioEnabled = true;
  20978. this._headphone = false;
  20979. // Performance counters
  20980. this._totalVertices = new BABYLON.PerfCounter();
  20981. this._activeIndices = new BABYLON.PerfCounter();
  20982. this._activeParticles = new BABYLON.PerfCounter();
  20983. this._activeBones = new BABYLON.PerfCounter();
  20984. this._animationTime = 0;
  20985. this.animationTimeScale = 1;
  20986. this._renderId = 0;
  20987. this._executeWhenReadyTimeoutId = -1;
  20988. this._intermediateRendering = false;
  20989. this._viewUpdateFlag = -1;
  20990. this._projectionUpdateFlag = -1;
  20991. this._alternateViewUpdateFlag = -1;
  20992. this._alternateProjectionUpdateFlag = -1;
  20993. this._toBeDisposed = new BABYLON.SmartArray(256);
  20994. this._activeRequests = new Array();
  20995. this._pendingData = new Array();
  20996. this._isDisposed = false;
  20997. this.dispatchAllSubMeshesOfActiveMeshes = false;
  20998. this._activeMeshes = new BABYLON.SmartArray(256);
  20999. this._processedMaterials = new BABYLON.SmartArray(256);
  21000. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  21001. this._activeParticleSystems = new BABYLON.SmartArray(256);
  21002. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  21003. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  21004. this._activeAnimatables = new Array();
  21005. this._transformMatrix = BABYLON.Matrix.Zero();
  21006. this._useAlternateCameraConfiguration = false;
  21007. this._alternateRendering = false;
  21008. this.requireLightSorting = false;
  21009. this._activeMeshesFrozen = false;
  21010. this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  21011. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  21012. this._engine.scenes.push(this);
  21013. this._uid = null;
  21014. this._renderingManager = new BABYLON.RenderingManager(this);
  21015. this.postProcessManager = new BABYLON.PostProcessManager(this);
  21016. if (BABYLON.OutlineRenderer) {
  21017. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  21018. }
  21019. if (BABYLON.Tools.IsWindowObjectExist()) {
  21020. this.attachControl();
  21021. }
  21022. //simplification queue
  21023. if (BABYLON.SimplificationQueue) {
  21024. this.simplificationQueue = new BABYLON.SimplificationQueue();
  21025. }
  21026. //collision coordinator initialization. For now legacy per default.
  21027. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  21028. // Uniform Buffer
  21029. this._createUbo();
  21030. // Default Image processing definition.
  21031. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  21032. }
  21033. Object.defineProperty(Scene, "FOGMODE_NONE", {
  21034. /** The fog is deactivated */
  21035. get: function () {
  21036. return Scene._FOGMODE_NONE;
  21037. },
  21038. enumerable: true,
  21039. configurable: true
  21040. });
  21041. Object.defineProperty(Scene, "FOGMODE_EXP", {
  21042. /** The fog density is following an exponential function */
  21043. get: function () {
  21044. return Scene._FOGMODE_EXP;
  21045. },
  21046. enumerable: true,
  21047. configurable: true
  21048. });
  21049. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  21050. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  21051. get: function () {
  21052. return Scene._FOGMODE_EXP2;
  21053. },
  21054. enumerable: true,
  21055. configurable: true
  21056. });
  21057. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  21058. /** The fog density is following a linear function. */
  21059. get: function () {
  21060. return Scene._FOGMODE_LINEAR;
  21061. },
  21062. enumerable: true,
  21063. configurable: true
  21064. });
  21065. Object.defineProperty(Scene.prototype, "environmentTexture", {
  21066. /**
  21067. * Texture used in all pbr material as the reflection texture.
  21068. * As in the majority of the scene they are the same (exception for multi room and so on),
  21069. * this is easier to reference from here than from all the materials.
  21070. */
  21071. get: function () {
  21072. return this._environmentTexture;
  21073. },
  21074. /**
  21075. * Texture used in all pbr material as the reflection texture.
  21076. * As in the majority of the scene they are the same (exception for multi room and so on),
  21077. * this is easier to set here than in all the materials.
  21078. */
  21079. set: function (value) {
  21080. if (this._environmentTexture === value) {
  21081. return;
  21082. }
  21083. this._environmentTexture = value;
  21084. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  21085. },
  21086. enumerable: true,
  21087. configurable: true
  21088. });
  21089. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  21090. /**
  21091. * Default image processing configuration used either in the rendering
  21092. * Forward main pass or through the imageProcessingPostProcess if present.
  21093. * As in the majority of the scene they are the same (exception for multi camera),
  21094. * this is easier to reference from here than from all the materials and post process.
  21095. *
  21096. * No setter as we it is a shared configuration, you can set the values instead.
  21097. */
  21098. get: function () {
  21099. return this._imageProcessingConfiguration;
  21100. },
  21101. enumerable: true,
  21102. configurable: true
  21103. });
  21104. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  21105. get: function () {
  21106. return this._forcePointsCloud;
  21107. },
  21108. set: function (value) {
  21109. if (this._forcePointsCloud === value) {
  21110. return;
  21111. }
  21112. this._forcePointsCloud = value;
  21113. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  21114. },
  21115. enumerable: true,
  21116. configurable: true
  21117. });
  21118. Object.defineProperty(Scene.prototype, "onDispose", {
  21119. /** A function to be executed when this scene is disposed. */
  21120. set: function (callback) {
  21121. if (this._onDisposeObserver) {
  21122. this.onDisposeObservable.remove(this._onDisposeObserver);
  21123. }
  21124. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  21125. },
  21126. enumerable: true,
  21127. configurable: true
  21128. });
  21129. Object.defineProperty(Scene.prototype, "beforeRender", {
  21130. /** A function to be executed before rendering this scene */
  21131. set: function (callback) {
  21132. if (this._onBeforeRenderObserver) {
  21133. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  21134. }
  21135. if (callback) {
  21136. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  21137. }
  21138. },
  21139. enumerable: true,
  21140. configurable: true
  21141. });
  21142. Object.defineProperty(Scene.prototype, "afterRender", {
  21143. /** A function to be executed after rendering this scene */
  21144. set: function (callback) {
  21145. if (this._onAfterRenderObserver) {
  21146. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  21147. }
  21148. if (callback) {
  21149. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  21150. }
  21151. },
  21152. enumerable: true,
  21153. configurable: true
  21154. });
  21155. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  21156. set: function (callback) {
  21157. if (this._onBeforeCameraRenderObserver) {
  21158. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  21159. }
  21160. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  21161. },
  21162. enumerable: true,
  21163. configurable: true
  21164. });
  21165. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  21166. set: function (callback) {
  21167. if (this._onAfterCameraRenderObserver) {
  21168. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  21169. }
  21170. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  21171. },
  21172. enumerable: true,
  21173. configurable: true
  21174. });
  21175. Object.defineProperty(Scene.prototype, "gamepadManager", {
  21176. get: function () {
  21177. if (!this._gamepadManager) {
  21178. this._gamepadManager = new BABYLON.GamepadManager(this);
  21179. }
  21180. return this._gamepadManager;
  21181. },
  21182. enumerable: true,
  21183. configurable: true
  21184. });
  21185. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  21186. get: function () {
  21187. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  21188. },
  21189. enumerable: true,
  21190. configurable: true
  21191. });
  21192. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  21193. get: function () {
  21194. return this._useRightHandedSystem;
  21195. },
  21196. set: function (value) {
  21197. if (this._useRightHandedSystem === value) {
  21198. return;
  21199. }
  21200. this._useRightHandedSystem = value;
  21201. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  21202. },
  21203. enumerable: true,
  21204. configurable: true
  21205. });
  21206. Scene.prototype.setStepId = function (newStepId) {
  21207. this._currentStepId = newStepId;
  21208. };
  21209. ;
  21210. Scene.prototype.getStepId = function () {
  21211. return this._currentStepId;
  21212. };
  21213. ;
  21214. Scene.prototype.getInternalStep = function () {
  21215. return this._currentInternalStep;
  21216. };
  21217. ;
  21218. Object.defineProperty(Scene.prototype, "fogEnabled", {
  21219. get: function () {
  21220. return this._fogEnabled;
  21221. },
  21222. /**
  21223. * is fog enabled on this scene.
  21224. */
  21225. set: function (value) {
  21226. if (this._fogEnabled === value) {
  21227. return;
  21228. }
  21229. this._fogEnabled = value;
  21230. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  21231. },
  21232. enumerable: true,
  21233. configurable: true
  21234. });
  21235. Object.defineProperty(Scene.prototype, "fogMode", {
  21236. get: function () {
  21237. return this._fogMode;
  21238. },
  21239. set: function (value) {
  21240. if (this._fogMode === value) {
  21241. return;
  21242. }
  21243. this._fogMode = value;
  21244. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  21245. },
  21246. enumerable: true,
  21247. configurable: true
  21248. });
  21249. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  21250. get: function () {
  21251. return this._shadowsEnabled;
  21252. },
  21253. set: function (value) {
  21254. if (this._shadowsEnabled === value) {
  21255. return;
  21256. }
  21257. this._shadowsEnabled = value;
  21258. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  21259. },
  21260. enumerable: true,
  21261. configurable: true
  21262. });
  21263. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  21264. get: function () {
  21265. return this._lightsEnabled;
  21266. },
  21267. set: function (value) {
  21268. if (this._lightsEnabled === value) {
  21269. return;
  21270. }
  21271. this._lightsEnabled = value;
  21272. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  21273. },
  21274. enumerable: true,
  21275. configurable: true
  21276. });
  21277. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  21278. /** The default material used on meshes when no material is affected */
  21279. get: function () {
  21280. if (!this._defaultMaterial) {
  21281. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  21282. }
  21283. return this._defaultMaterial;
  21284. },
  21285. /** The default material used on meshes when no material is affected */
  21286. set: function (value) {
  21287. this._defaultMaterial = value;
  21288. },
  21289. enumerable: true,
  21290. configurable: true
  21291. });
  21292. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  21293. get: function () {
  21294. return this._texturesEnabled;
  21295. },
  21296. set: function (value) {
  21297. if (this._texturesEnabled === value) {
  21298. return;
  21299. }
  21300. this._texturesEnabled = value;
  21301. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  21302. },
  21303. enumerable: true,
  21304. configurable: true
  21305. });
  21306. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  21307. get: function () {
  21308. return this._skeletonsEnabled;
  21309. },
  21310. set: function (value) {
  21311. if (this._skeletonsEnabled === value) {
  21312. return;
  21313. }
  21314. this._skeletonsEnabled = value;
  21315. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  21316. },
  21317. enumerable: true,
  21318. configurable: true
  21319. });
  21320. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  21321. get: function () {
  21322. if (!this._postProcessRenderPipelineManager) {
  21323. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  21324. }
  21325. return this._postProcessRenderPipelineManager;
  21326. },
  21327. enumerable: true,
  21328. configurable: true
  21329. });
  21330. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  21331. get: function () {
  21332. if (!this._mainSoundTrack) {
  21333. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  21334. }
  21335. return this._mainSoundTrack;
  21336. },
  21337. enumerable: true,
  21338. configurable: true
  21339. });
  21340. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  21341. get: function () {
  21342. return this._alternateRendering;
  21343. },
  21344. enumerable: true,
  21345. configurable: true
  21346. });
  21347. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  21348. get: function () {
  21349. return this._frustumPlanes;
  21350. },
  21351. enumerable: true,
  21352. configurable: true
  21353. });
  21354. Object.defineProperty(Scene.prototype, "geometryBufferRenderer", {
  21355. /**
  21356. * Gets the current geometry buffer associated to the scene.
  21357. */
  21358. get: function () {
  21359. return this._geometryBufferRenderer;
  21360. },
  21361. /**
  21362. * Sets the current geometry buffer for the scene.
  21363. */
  21364. set: function (geometryBufferRenderer) {
  21365. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  21366. this._geometryBufferRenderer = geometryBufferRenderer;
  21367. }
  21368. },
  21369. enumerable: true,
  21370. configurable: true
  21371. });
  21372. Object.defineProperty(Scene.prototype, "debugLayer", {
  21373. // Properties
  21374. get: function () {
  21375. if (!this._debugLayer) {
  21376. this._debugLayer = new BABYLON.DebugLayer(this);
  21377. }
  21378. return this._debugLayer;
  21379. },
  21380. enumerable: true,
  21381. configurable: true
  21382. });
  21383. Object.defineProperty(Scene.prototype, "workerCollisions", {
  21384. get: function () {
  21385. return this._workerCollisions;
  21386. },
  21387. set: function (enabled) {
  21388. if (!BABYLON.CollisionCoordinatorLegacy) {
  21389. return;
  21390. }
  21391. enabled = (enabled && !!Worker);
  21392. this._workerCollisions = enabled;
  21393. if (this.collisionCoordinator) {
  21394. this.collisionCoordinator.destroy();
  21395. }
  21396. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  21397. this.collisionCoordinator.init(this);
  21398. },
  21399. enumerable: true,
  21400. configurable: true
  21401. });
  21402. Object.defineProperty(Scene.prototype, "selectionOctree", {
  21403. get: function () {
  21404. return this._selectionOctree;
  21405. },
  21406. enumerable: true,
  21407. configurable: true
  21408. });
  21409. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  21410. /**
  21411. * The mesh that is currently under the pointer.
  21412. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  21413. */
  21414. get: function () {
  21415. return this._pointerOverMesh;
  21416. },
  21417. enumerable: true,
  21418. configurable: true
  21419. });
  21420. Object.defineProperty(Scene.prototype, "pointerX", {
  21421. /**
  21422. * Current on-screen X position of the pointer
  21423. * @return {number} X position of the pointer
  21424. */
  21425. get: function () {
  21426. return this._pointerX;
  21427. },
  21428. enumerable: true,
  21429. configurable: true
  21430. });
  21431. Object.defineProperty(Scene.prototype, "pointerY", {
  21432. /**
  21433. * Current on-screen Y position of the pointer
  21434. * @return {number} Y position of the pointer
  21435. */
  21436. get: function () {
  21437. return this._pointerY;
  21438. },
  21439. enumerable: true,
  21440. configurable: true
  21441. });
  21442. Scene.prototype.getCachedMaterial = function () {
  21443. return this._cachedMaterial;
  21444. };
  21445. Scene.prototype.getCachedEffect = function () {
  21446. return this._cachedEffect;
  21447. };
  21448. Scene.prototype.getCachedVisibility = function () {
  21449. return this._cachedVisibility;
  21450. };
  21451. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  21452. if (visibility === void 0) { visibility = 1; }
  21453. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  21454. };
  21455. Scene.prototype.getBoundingBoxRenderer = function () {
  21456. if (!this._boundingBoxRenderer) {
  21457. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  21458. }
  21459. return this._boundingBoxRenderer;
  21460. };
  21461. Scene.prototype.getOutlineRenderer = function () {
  21462. return this._outlineRenderer;
  21463. };
  21464. Scene.prototype.getEngine = function () {
  21465. return this._engine;
  21466. };
  21467. Scene.prototype.getTotalVertices = function () {
  21468. return this._totalVertices.current;
  21469. };
  21470. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  21471. get: function () {
  21472. return this._totalVertices;
  21473. },
  21474. enumerable: true,
  21475. configurable: true
  21476. });
  21477. Scene.prototype.getActiveIndices = function () {
  21478. return this._activeIndices.current;
  21479. };
  21480. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  21481. get: function () {
  21482. return this._activeIndices;
  21483. },
  21484. enumerable: true,
  21485. configurable: true
  21486. });
  21487. Scene.prototype.getActiveParticles = function () {
  21488. return this._activeParticles.current;
  21489. };
  21490. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  21491. get: function () {
  21492. return this._activeParticles;
  21493. },
  21494. enumerable: true,
  21495. configurable: true
  21496. });
  21497. Scene.prototype.getActiveBones = function () {
  21498. return this._activeBones.current;
  21499. };
  21500. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  21501. get: function () {
  21502. return this._activeBones;
  21503. },
  21504. enumerable: true,
  21505. configurable: true
  21506. });
  21507. // Stats
  21508. Scene.prototype.getInterFramePerfCounter = function () {
  21509. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  21510. return 0;
  21511. };
  21512. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  21513. get: function () {
  21514. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  21515. return null;
  21516. },
  21517. enumerable: true,
  21518. configurable: true
  21519. });
  21520. Scene.prototype.getLastFrameDuration = function () {
  21521. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  21522. return 0;
  21523. };
  21524. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  21525. get: function () {
  21526. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  21527. return null;
  21528. },
  21529. enumerable: true,
  21530. configurable: true
  21531. });
  21532. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  21533. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  21534. return 0;
  21535. };
  21536. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  21537. get: function () {
  21538. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  21539. return null;
  21540. },
  21541. enumerable: true,
  21542. configurable: true
  21543. });
  21544. Scene.prototype.getActiveMeshes = function () {
  21545. return this._activeMeshes;
  21546. };
  21547. Scene.prototype.getRenderTargetsDuration = function () {
  21548. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  21549. return 0;
  21550. };
  21551. Scene.prototype.getRenderDuration = function () {
  21552. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  21553. return 0;
  21554. };
  21555. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  21556. get: function () {
  21557. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  21558. return null;
  21559. },
  21560. enumerable: true,
  21561. configurable: true
  21562. });
  21563. Scene.prototype.getParticlesDuration = function () {
  21564. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  21565. return 0;
  21566. };
  21567. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  21568. get: function () {
  21569. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  21570. return null;
  21571. },
  21572. enumerable: true,
  21573. configurable: true
  21574. });
  21575. Scene.prototype.getSpritesDuration = function () {
  21576. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  21577. return 0;
  21578. };
  21579. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  21580. get: function () {
  21581. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  21582. return null;
  21583. },
  21584. enumerable: true,
  21585. configurable: true
  21586. });
  21587. Scene.prototype.getAnimationRatio = function () {
  21588. return this._animationRatio;
  21589. };
  21590. Scene.prototype.getRenderId = function () {
  21591. return this._renderId;
  21592. };
  21593. Scene.prototype.incrementRenderId = function () {
  21594. this._renderId++;
  21595. };
  21596. Scene.prototype._updatePointerPosition = function (evt) {
  21597. var canvasRect = this._engine.getRenderingCanvasClientRect();
  21598. if (!canvasRect) {
  21599. return;
  21600. }
  21601. this._pointerX = evt.clientX - canvasRect.left;
  21602. this._pointerY = evt.clientY - canvasRect.top;
  21603. this._unTranslatedPointerX = this._pointerX;
  21604. this._unTranslatedPointerY = this._pointerY;
  21605. };
  21606. Scene.prototype._createUbo = function () {
  21607. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  21608. this._sceneUbo.addUniform("viewProjection", 16);
  21609. this._sceneUbo.addUniform("view", 16);
  21610. };
  21611. Scene.prototype._createAlternateUbo = function () {
  21612. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  21613. this._alternateSceneUbo.addUniform("viewProjection", 16);
  21614. this._alternateSceneUbo.addUniform("view", 16);
  21615. };
  21616. // Pointers handling
  21617. /**
  21618. * Use this method to simulate a pointer move on a mesh
  21619. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  21620. */
  21621. Scene.prototype.simulatePointerMove = function (pickResult) {
  21622. var evt = new PointerEvent("pointermove");
  21623. return this._processPointerMove(pickResult, evt);
  21624. };
  21625. Scene.prototype._processPointerMove = function (pickResult, evt) {
  21626. var canvas = this._engine.getRenderingCanvas();
  21627. if (!canvas) {
  21628. return this;
  21629. }
  21630. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  21631. this.setPointerOverSprite(null);
  21632. this.setPointerOverMesh(pickResult.pickedMesh);
  21633. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  21634. if (this._pointerOverMesh.actionManager.hoverCursor) {
  21635. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  21636. }
  21637. else {
  21638. canvas.style.cursor = this.hoverCursor;
  21639. }
  21640. }
  21641. else {
  21642. canvas.style.cursor = this.defaultCursor;
  21643. }
  21644. }
  21645. else {
  21646. this.setPointerOverMesh(null);
  21647. // Sprites
  21648. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  21649. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  21650. this.setPointerOverSprite(pickResult.pickedSprite);
  21651. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  21652. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  21653. }
  21654. else {
  21655. canvas.style.cursor = this.hoverCursor;
  21656. }
  21657. }
  21658. else {
  21659. this.setPointerOverSprite(null);
  21660. // Restore pointer
  21661. canvas.style.cursor = this.defaultCursor;
  21662. }
  21663. }
  21664. if (pickResult) {
  21665. if (this.onPointerMove) {
  21666. this.onPointerMove(evt, pickResult);
  21667. }
  21668. if (this.onPointerObservable.hasObservers()) {
  21669. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  21670. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  21671. this.onPointerObservable.notifyObservers(pi, type);
  21672. }
  21673. }
  21674. return this;
  21675. };
  21676. /**
  21677. * Use this method to simulate a pointer down on a mesh
  21678. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  21679. */
  21680. Scene.prototype.simulatePointerDown = function (pickResult) {
  21681. var evt = new PointerEvent("pointerdown");
  21682. return this._processPointerDown(pickResult, evt);
  21683. };
  21684. Scene.prototype._processPointerDown = function (pickResult, evt) {
  21685. var _this = this;
  21686. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  21687. this._pickedDownMesh = pickResult.pickedMesh;
  21688. var actionManager = pickResult.pickedMesh.actionManager;
  21689. if (actionManager) {
  21690. if (actionManager.hasPickTriggers) {
  21691. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  21692. switch (evt.button) {
  21693. case 0:
  21694. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  21695. break;
  21696. case 1:
  21697. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  21698. break;
  21699. case 2:
  21700. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  21701. break;
  21702. }
  21703. }
  21704. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  21705. window.setTimeout(function () {
  21706. 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);
  21707. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  21708. if (_this._totalPointersPressed !== 0 &&
  21709. ((new Date().getTime() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  21710. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  21711. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  21712. _this._startingPointerTime = 0;
  21713. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  21714. }
  21715. }
  21716. }, Scene.LongPressDelay);
  21717. }
  21718. }
  21719. }
  21720. if (pickResult) {
  21721. if (this.onPointerDown) {
  21722. this.onPointerDown(evt, pickResult);
  21723. }
  21724. if (this.onPointerObservable.hasObservers()) {
  21725. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  21726. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  21727. this.onPointerObservable.notifyObservers(pi, type);
  21728. }
  21729. }
  21730. return this;
  21731. };
  21732. /**
  21733. * Use this method to simulate a pointer up on a mesh
  21734. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  21735. */
  21736. Scene.prototype.simulatePointerUp = function (pickResult) {
  21737. var evt = new PointerEvent("pointerup");
  21738. var clickInfo = new ClickInfo();
  21739. clickInfo.singleClick = true;
  21740. clickInfo.ignore = true;
  21741. return this._processPointerUp(pickResult, evt, clickInfo);
  21742. };
  21743. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  21744. if (pickResult && pickResult && pickResult.pickedMesh) {
  21745. this._pickedUpMesh = pickResult.pickedMesh;
  21746. if (this._pickedDownMesh === this._pickedUpMesh) {
  21747. if (this.onPointerPick) {
  21748. this.onPointerPick(evt, pickResult);
  21749. }
  21750. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  21751. var type = BABYLON.PointerEventTypes.POINTERPICK;
  21752. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  21753. this.onPointerObservable.notifyObservers(pi, type);
  21754. }
  21755. }
  21756. if (pickResult.pickedMesh.actionManager) {
  21757. if (clickInfo.ignore) {
  21758. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  21759. }
  21760. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  21761. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  21762. }
  21763. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  21764. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  21765. }
  21766. }
  21767. }
  21768. if (this._pickedDownMesh &&
  21769. this._pickedDownMesh.actionManager &&
  21770. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  21771. this._pickedDownMesh !== this._pickedUpMesh) {
  21772. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  21773. }
  21774. if (this.onPointerUp) {
  21775. this.onPointerUp(evt, pickResult);
  21776. }
  21777. if (this.onPointerObservable.hasObservers()) {
  21778. if (!clickInfo.ignore) {
  21779. if (!clickInfo.hasSwiped) {
  21780. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  21781. var type = BABYLON.PointerEventTypes.POINTERTAP;
  21782. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  21783. this.onPointerObservable.notifyObservers(pi, type);
  21784. }
  21785. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  21786. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  21787. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  21788. this.onPointerObservable.notifyObservers(pi, type);
  21789. }
  21790. }
  21791. }
  21792. else {
  21793. var type = BABYLON.PointerEventTypes.POINTERUP;
  21794. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  21795. this.onPointerObservable.notifyObservers(pi, type);
  21796. }
  21797. }
  21798. return this;
  21799. };
  21800. /**
  21801. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  21802. * @param attachUp defines if you want to attach events to pointerup
  21803. * @param attachDown defines if you want to attach events to pointerdown
  21804. * @param attachMove defines if you want to attach events to pointermove
  21805. */
  21806. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  21807. var _this = this;
  21808. if (attachUp === void 0) { attachUp = true; }
  21809. if (attachDown === void 0) { attachDown = true; }
  21810. if (attachMove === void 0) { attachMove = true; }
  21811. this._initActionManager = function (act, clickInfo) {
  21812. if (!_this._meshPickProceed) {
  21813. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  21814. _this._currentPickResult = pickResult;
  21815. if (pickResult) {
  21816. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  21817. }
  21818. _this._meshPickProceed = true;
  21819. }
  21820. return act;
  21821. };
  21822. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  21823. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  21824. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  21825. btn !== _this._previousButtonPressed) {
  21826. _this._doubleClickOccured = false;
  21827. clickInfo.singleClick = true;
  21828. clickInfo.ignore = false;
  21829. cb(clickInfo, _this._currentPickResult);
  21830. }
  21831. };
  21832. this._initClickEvent = function (obs1, obs2, evt, cb) {
  21833. var clickInfo = new ClickInfo();
  21834. _this._currentPickResult = null;
  21835. var act = null;
  21836. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  21837. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  21838. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  21839. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  21840. act = _this._initActionManager(act, clickInfo);
  21841. if (act)
  21842. checkPicking = act.hasPickTriggers;
  21843. }
  21844. if (checkPicking) {
  21845. var btn = evt.button;
  21846. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  21847. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  21848. if (!clickInfo.hasSwiped) {
  21849. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  21850. if (!checkSingleClickImmediately) {
  21851. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  21852. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  21853. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  21854. act = _this._initActionManager(act, clickInfo);
  21855. if (act)
  21856. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  21857. }
  21858. }
  21859. if (checkSingleClickImmediately) {
  21860. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  21861. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  21862. btn !== _this._previousButtonPressed) {
  21863. clickInfo.singleClick = true;
  21864. cb(clickInfo, _this._currentPickResult);
  21865. }
  21866. }
  21867. else {
  21868. // wait that no double click has been raised during the double click delay
  21869. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  21870. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  21871. }
  21872. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  21873. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  21874. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  21875. act = _this._initActionManager(act, clickInfo);
  21876. if (act)
  21877. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  21878. }
  21879. if (checkDoubleClick) {
  21880. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  21881. if (btn === _this._previousButtonPressed &&
  21882. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  21883. !_this._doubleClickOccured) {
  21884. // pointer has not moved for 2 clicks, it's a double click
  21885. if (!clickInfo.hasSwiped &&
  21886. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  21887. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  21888. _this._previousStartingPointerTime = 0;
  21889. _this._doubleClickOccured = true;
  21890. clickInfo.doubleClick = true;
  21891. clickInfo.ignore = false;
  21892. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  21893. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  21894. }
  21895. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  21896. cb(clickInfo, _this._currentPickResult);
  21897. }
  21898. else {
  21899. _this._doubleClickOccured = false;
  21900. _this._previousStartingPointerTime = _this._startingPointerTime;
  21901. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  21902. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  21903. _this._previousButtonPressed = btn;
  21904. if (Scene.ExclusiveDoubleClickMode) {
  21905. if (_this._previousDelayedSimpleClickTimeout) {
  21906. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  21907. }
  21908. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  21909. cb(clickInfo, _this._previousPickResult);
  21910. }
  21911. else {
  21912. cb(clickInfo, _this._currentPickResult);
  21913. }
  21914. }
  21915. }
  21916. else {
  21917. _this._doubleClickOccured = false;
  21918. _this._previousStartingPointerTime = _this._startingPointerTime;
  21919. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  21920. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  21921. _this._previousButtonPressed = btn;
  21922. }
  21923. }
  21924. }
  21925. }
  21926. clickInfo.ignore = true;
  21927. cb(clickInfo, _this._currentPickResult);
  21928. };
  21929. this._spritePredicate = function (sprite) {
  21930. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  21931. };
  21932. this._onPointerMove = function (evt) {
  21933. _this._updatePointerPosition(evt);
  21934. // PreObservable support
  21935. if (_this.onPrePointerObservable.hasObservers()) {
  21936. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  21937. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  21938. _this.onPrePointerObservable.notifyObservers(pi, type);
  21939. if (pi.skipOnPointerObservable) {
  21940. return;
  21941. }
  21942. }
  21943. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  21944. return;
  21945. }
  21946. if (!_this.pointerMovePredicate) {
  21947. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  21948. }
  21949. // Meshes
  21950. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  21951. _this._processPointerMove(pickResult, evt);
  21952. };
  21953. this._onPointerDown = function (evt) {
  21954. _this._totalPointersPressed++;
  21955. _this._pickedDownMesh = null;
  21956. _this._meshPickProceed = false;
  21957. _this._updatePointerPosition(evt);
  21958. if (_this.preventDefaultOnPointerDown && canvas) {
  21959. evt.preventDefault();
  21960. canvas.focus();
  21961. }
  21962. // PreObservable support
  21963. if (_this.onPrePointerObservable.hasObservers()) {
  21964. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  21965. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  21966. _this.onPrePointerObservable.notifyObservers(pi, type);
  21967. if (pi.skipOnPointerObservable) {
  21968. return;
  21969. }
  21970. }
  21971. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  21972. return;
  21973. }
  21974. _this._startingPointerPosition.x = _this._pointerX;
  21975. _this._startingPointerPosition.y = _this._pointerY;
  21976. _this._startingPointerTime = new Date().getTime();
  21977. if (!_this.pointerDownPredicate) {
  21978. _this.pointerDownPredicate = function (mesh) {
  21979. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  21980. };
  21981. }
  21982. // Meshes
  21983. _this._pickedDownMesh = null;
  21984. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  21985. _this._processPointerDown(pickResult, evt);
  21986. // Sprites
  21987. _this._pickedDownSprite = null;
  21988. if (_this.spriteManagers.length > 0) {
  21989. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  21990. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  21991. if (pickResult.pickedSprite.actionManager) {
  21992. _this._pickedDownSprite = pickResult.pickedSprite;
  21993. switch (evt.button) {
  21994. case 0:
  21995. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  21996. break;
  21997. case 1:
  21998. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  21999. break;
  22000. case 2:
  22001. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22002. break;
  22003. }
  22004. if (pickResult.pickedSprite.actionManager) {
  22005. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22006. }
  22007. }
  22008. }
  22009. }
  22010. };
  22011. this._onPointerUp = function (evt) {
  22012. if (_this._totalPointersPressed === 0) {
  22013. return; // So we need to test it the pointer down was pressed before.
  22014. }
  22015. _this._totalPointersPressed--;
  22016. _this._pickedUpMesh = null;
  22017. _this._meshPickProceed = false;
  22018. _this._updatePointerPosition(evt);
  22019. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  22020. // PreObservable support
  22021. if (_this.onPrePointerObservable.hasObservers()) {
  22022. if (!clickInfo.ignore) {
  22023. if (!clickInfo.hasSwiped) {
  22024. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  22025. var type = BABYLON.PointerEventTypes.POINTERTAP;
  22026. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22027. _this.onPrePointerObservable.notifyObservers(pi, type);
  22028. if (pi.skipOnPointerObservable) {
  22029. return;
  22030. }
  22031. }
  22032. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  22033. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  22034. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22035. _this.onPrePointerObservable.notifyObservers(pi, type);
  22036. if (pi.skipOnPointerObservable) {
  22037. return;
  22038. }
  22039. }
  22040. }
  22041. }
  22042. else {
  22043. var type = BABYLON.PointerEventTypes.POINTERUP;
  22044. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22045. _this.onPrePointerObservable.notifyObservers(pi, type);
  22046. if (pi.skipOnPointerObservable) {
  22047. return;
  22048. }
  22049. }
  22050. }
  22051. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  22052. return;
  22053. }
  22054. if (!_this.pointerUpPredicate) {
  22055. _this.pointerUpPredicate = function (mesh) {
  22056. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  22057. };
  22058. }
  22059. // Meshes
  22060. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  22061. _this._initActionManager(null, clickInfo);
  22062. }
  22063. if (!pickResult) {
  22064. pickResult = _this._currentPickResult;
  22065. }
  22066. _this._processPointerUp(pickResult, evt, clickInfo);
  22067. // Sprites
  22068. if (_this.spriteManagers.length > 0) {
  22069. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  22070. if (spritePickResult) {
  22071. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  22072. if (spritePickResult.pickedSprite.actionManager) {
  22073. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  22074. if (spritePickResult.pickedSprite.actionManager) {
  22075. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  22076. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  22077. }
  22078. }
  22079. }
  22080. }
  22081. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  22082. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  22083. }
  22084. }
  22085. }
  22086. _this._previousPickResult = _this._currentPickResult;
  22087. });
  22088. };
  22089. this._onKeyDown = function (evt) {
  22090. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  22091. if (_this.onPreKeyboardObservable.hasObservers()) {
  22092. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  22093. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  22094. if (pi.skipOnPointerObservable) {
  22095. return;
  22096. }
  22097. }
  22098. if (_this.onKeyboardObservable.hasObservers()) {
  22099. var pi = new BABYLON.KeyboardInfo(type, evt);
  22100. _this.onKeyboardObservable.notifyObservers(pi, type);
  22101. }
  22102. if (_this.actionManager) {
  22103. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  22104. }
  22105. };
  22106. this._onKeyUp = function (evt) {
  22107. var type = BABYLON.KeyboardEventTypes.KEYUP;
  22108. if (_this.onPreKeyboardObservable.hasObservers()) {
  22109. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  22110. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  22111. if (pi.skipOnPointerObservable) {
  22112. return;
  22113. }
  22114. }
  22115. if (_this.onKeyboardObservable.hasObservers()) {
  22116. var pi = new BABYLON.KeyboardInfo(type, evt);
  22117. _this.onKeyboardObservable.notifyObservers(pi, type);
  22118. }
  22119. if (_this.actionManager) {
  22120. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  22121. }
  22122. };
  22123. var engine = this.getEngine();
  22124. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  22125. if (!canvas) {
  22126. return;
  22127. }
  22128. canvas.addEventListener("keydown", _this._onKeyDown, false);
  22129. canvas.addEventListener("keyup", _this._onKeyUp, false);
  22130. });
  22131. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  22132. if (!canvas) {
  22133. return;
  22134. }
  22135. canvas.removeEventListener("keydown", _this._onKeyDown);
  22136. canvas.removeEventListener("keyup", _this._onKeyUp);
  22137. });
  22138. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  22139. var canvas = this._engine.getRenderingCanvas();
  22140. if (!canvas) {
  22141. return;
  22142. }
  22143. if (attachMove) {
  22144. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  22145. // Wheel
  22146. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  22147. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  22148. }
  22149. if (attachDown) {
  22150. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  22151. }
  22152. if (attachUp) {
  22153. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  22154. }
  22155. canvas.tabIndex = 1;
  22156. };
  22157. Scene.prototype.detachControl = function () {
  22158. var engine = this.getEngine();
  22159. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  22160. var canvas = engine.getRenderingCanvas();
  22161. if (!canvas) {
  22162. return;
  22163. }
  22164. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  22165. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  22166. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  22167. if (this._onCanvasBlurObserver) {
  22168. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  22169. }
  22170. if (this._onCanvasFocusObserver) {
  22171. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  22172. }
  22173. // Wheel
  22174. canvas.removeEventListener('mousewheel', this._onPointerMove);
  22175. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  22176. // Keyboard
  22177. canvas.removeEventListener("keydown", this._onKeyDown);
  22178. canvas.removeEventListener("keyup", this._onKeyUp);
  22179. // Observables
  22180. this.onKeyboardObservable.clear();
  22181. this.onPreKeyboardObservable.clear();
  22182. this.onPointerObservable.clear();
  22183. this.onPrePointerObservable.clear();
  22184. };
  22185. /**
  22186. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  22187. * Delay loaded resources are not taking in account
  22188. * @return true if all required resources are ready
  22189. */
  22190. Scene.prototype.isReady = function () {
  22191. if (this._isDisposed) {
  22192. return false;
  22193. }
  22194. if (this._pendingData.length > 0) {
  22195. return false;
  22196. }
  22197. var index;
  22198. var engine = this.getEngine();
  22199. // Geometries
  22200. for (index = 0; index < this._geometries.length; index++) {
  22201. var geometry = this._geometries[index];
  22202. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  22203. return false;
  22204. }
  22205. }
  22206. // Meshes
  22207. for (index = 0; index < this.meshes.length; index++) {
  22208. var mesh = this.meshes[index];
  22209. if (!mesh.isEnabled()) {
  22210. continue;
  22211. }
  22212. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  22213. continue;
  22214. }
  22215. if (!mesh.isReady()) {
  22216. return false;
  22217. }
  22218. // Effect layers
  22219. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  22220. for (var _i = 0, _a = this.effectLayers; _i < _a.length; _i++) {
  22221. var layer = _a[_i];
  22222. if (!layer.hasMesh(mesh)) {
  22223. continue;
  22224. }
  22225. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  22226. var subMesh = _c[_b];
  22227. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  22228. return false;
  22229. }
  22230. }
  22231. }
  22232. }
  22233. return true;
  22234. };
  22235. Scene.prototype.resetCachedMaterial = function () {
  22236. this._cachedMaterial = null;
  22237. this._cachedEffect = null;
  22238. this._cachedVisibility = null;
  22239. };
  22240. Scene.prototype.registerBeforeRender = function (func) {
  22241. this.onBeforeRenderObservable.add(func);
  22242. };
  22243. Scene.prototype.unregisterBeforeRender = function (func) {
  22244. this.onBeforeRenderObservable.removeCallback(func);
  22245. };
  22246. Scene.prototype.registerAfterRender = function (func) {
  22247. this.onAfterRenderObservable.add(func);
  22248. };
  22249. Scene.prototype.unregisterAfterRender = function (func) {
  22250. this.onAfterRenderObservable.removeCallback(func);
  22251. };
  22252. Scene.prototype._executeOnceBeforeRender = function (func) {
  22253. var _this = this;
  22254. var execFunc = function () {
  22255. func();
  22256. setTimeout(function () {
  22257. _this.unregisterBeforeRender(execFunc);
  22258. });
  22259. };
  22260. this.registerBeforeRender(execFunc);
  22261. };
  22262. /**
  22263. * The provided function will run before render once and will be disposed afterwards.
  22264. * A timeout delay can be provided so that the function will be executed in N ms.
  22265. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  22266. * @param func The function to be executed.
  22267. * @param timeout optional delay in ms
  22268. */
  22269. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  22270. var _this = this;
  22271. if (timeout !== undefined) {
  22272. setTimeout(function () {
  22273. _this._executeOnceBeforeRender(func);
  22274. }, timeout);
  22275. }
  22276. else {
  22277. this._executeOnceBeforeRender(func);
  22278. }
  22279. };
  22280. Scene.prototype._addPendingData = function (data) {
  22281. this._pendingData.push(data);
  22282. };
  22283. Scene.prototype._removePendingData = function (data) {
  22284. var wasLoading = this.isLoading;
  22285. var index = this._pendingData.indexOf(data);
  22286. if (index !== -1) {
  22287. this._pendingData.splice(index, 1);
  22288. }
  22289. if (wasLoading && !this.isLoading) {
  22290. this.onDataLoadedObservable.notifyObservers(this);
  22291. }
  22292. };
  22293. Scene.prototype.getWaitingItemsCount = function () {
  22294. return this._pendingData.length;
  22295. };
  22296. Object.defineProperty(Scene.prototype, "isLoading", {
  22297. get: function () {
  22298. return this._pendingData.length > 0;
  22299. },
  22300. enumerable: true,
  22301. configurable: true
  22302. });
  22303. /**
  22304. * Registers a function to be executed when the scene is ready.
  22305. * @param {Function} func - the function to be executed.
  22306. */
  22307. Scene.prototype.executeWhenReady = function (func) {
  22308. var _this = this;
  22309. this.onReadyObservable.add(func);
  22310. if (this._executeWhenReadyTimeoutId !== -1) {
  22311. return;
  22312. }
  22313. this._executeWhenReadyTimeoutId = setTimeout(function () {
  22314. _this._checkIsReady();
  22315. }, 150);
  22316. };
  22317. /**
  22318. * Returns a promise that resolves when the scene is ready.
  22319. * @returns A promise that resolves when the scene is ready.
  22320. */
  22321. Scene.prototype.whenReadyAsync = function () {
  22322. var _this = this;
  22323. return new Promise(function (resolve) {
  22324. _this.executeWhenReady(function () {
  22325. resolve();
  22326. });
  22327. });
  22328. };
  22329. Scene.prototype._checkIsReady = function () {
  22330. var _this = this;
  22331. if (this.isReady()) {
  22332. this.onReadyObservable.notifyObservers(this);
  22333. this.onReadyObservable.clear();
  22334. this._executeWhenReadyTimeoutId = -1;
  22335. return;
  22336. }
  22337. this._executeWhenReadyTimeoutId = setTimeout(function () {
  22338. _this._checkIsReady();
  22339. }, 150);
  22340. };
  22341. // Animations
  22342. /**
  22343. * Will start the animation sequence of a given target
  22344. * @param target - the target
  22345. * @param {number} from - from which frame should animation start
  22346. * @param {number} to - till which frame should animation run.
  22347. * @param {boolean} [loop] - should the animation loop
  22348. * @param {number} [speedRatio] - the speed in which to run the animation
  22349. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  22350. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  22351. * Returns {BABYLON.Animatable} the animatable object created for this animation
  22352. * See BABYLON.Animatable
  22353. */
  22354. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  22355. if (speedRatio === void 0) { speedRatio = 1.0; }
  22356. if (from > to && speedRatio > 0) {
  22357. speedRatio *= -1;
  22358. }
  22359. this.stopAnimation(target);
  22360. if (!animatable) {
  22361. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  22362. }
  22363. // Local animations
  22364. if (target.animations) {
  22365. animatable.appendAnimations(target, target.animations);
  22366. }
  22367. // Children animations
  22368. if (target.getAnimatables) {
  22369. var animatables = target.getAnimatables();
  22370. for (var index = 0; index < animatables.length; index++) {
  22371. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  22372. }
  22373. }
  22374. animatable.reset();
  22375. return animatable;
  22376. };
  22377. /**
  22378. * Begin a new animation on a given node
  22379. * @param {BABYLON.Node} node defines the root node where the animation will take place
  22380. * @param {BABYLON.Animation[]} defines the list of animations to start
  22381. * @param {number} from defines the initial value
  22382. * @param {number} to defines the final value
  22383. * @param {boolean} loop defines if you want animation to loop (off by default)
  22384. * @param {number} speedRatio defines the speed ratio to apply to all animations
  22385. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  22386. * @returns the list of created animatables
  22387. */
  22388. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  22389. if (speedRatio === undefined) {
  22390. speedRatio = 1.0;
  22391. }
  22392. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  22393. return animatable;
  22394. };
  22395. /**
  22396. * Begin a new animation on a given node and its hierarchy
  22397. * @param {BABYLON.Node} node defines the root node where the animation will take place
  22398. * @param {boolean} 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.
  22399. * @param {BABYLON.Animation[]} defines the list of animations to start
  22400. * @param {number} from defines the initial value
  22401. * @param {number} to defines the final value
  22402. * @param {boolean} loop defines if you want animation to loop (off by default)
  22403. * @param {number} speedRatio defines the speed ratio to apply to all animations
  22404. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  22405. * @returns the list of animatables created for all nodes
  22406. */
  22407. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  22408. var children = target.getDescendants(directDescendantsOnly);
  22409. var result = [];
  22410. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  22411. var child = children_1[_i];
  22412. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  22413. }
  22414. return result;
  22415. };
  22416. Scene.prototype.getAnimatableByTarget = function (target) {
  22417. for (var index = 0; index < this._activeAnimatables.length; index++) {
  22418. if (this._activeAnimatables[index].target === target) {
  22419. return this._activeAnimatables[index];
  22420. }
  22421. }
  22422. return null;
  22423. };
  22424. Object.defineProperty(Scene.prototype, "animatables", {
  22425. get: function () {
  22426. return this._activeAnimatables;
  22427. },
  22428. enumerable: true,
  22429. configurable: true
  22430. });
  22431. /**
  22432. * Will stop the animation of the given target
  22433. * @param target - the target
  22434. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  22435. * @see beginAnimation
  22436. */
  22437. Scene.prototype.stopAnimation = function (target, animationName) {
  22438. var animatable = this.getAnimatableByTarget(target);
  22439. if (animatable) {
  22440. animatable.stop(animationName);
  22441. }
  22442. };
  22443. /**
  22444. * Stops and removes all animations that have been applied to the scene
  22445. */
  22446. Scene.prototype.stopAllAnimations = function () {
  22447. if (this._activeAnimatables) {
  22448. for (var i = 0; i < this._activeAnimatables.length; i++) {
  22449. this._activeAnimatables[i].stop();
  22450. }
  22451. this._activeAnimatables = [];
  22452. }
  22453. };
  22454. Scene.prototype._animate = function () {
  22455. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  22456. return;
  22457. }
  22458. // Getting time
  22459. var now = BABYLON.Tools.Now;
  22460. if (!this._animationTimeLast) {
  22461. if (this._pendingData.length > 0) {
  22462. return;
  22463. }
  22464. this._animationTimeLast = now;
  22465. }
  22466. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  22467. this._animationTime += deltaTime;
  22468. this._animationTimeLast = now;
  22469. for (var index = 0; index < this._activeAnimatables.length; index++) {
  22470. this._activeAnimatables[index]._animate(this._animationTime);
  22471. }
  22472. };
  22473. // Matrix
  22474. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  22475. this._useAlternateCameraConfiguration = active;
  22476. };
  22477. Scene.prototype.getViewMatrix = function () {
  22478. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  22479. };
  22480. Scene.prototype.getProjectionMatrix = function () {
  22481. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  22482. };
  22483. Scene.prototype.getTransformMatrix = function () {
  22484. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  22485. };
  22486. Scene.prototype.setTransformMatrix = function (view, projection) {
  22487. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  22488. return;
  22489. }
  22490. this._viewUpdateFlag = view.updateFlag;
  22491. this._projectionUpdateFlag = projection.updateFlag;
  22492. this._viewMatrix = view;
  22493. this._projectionMatrix = projection;
  22494. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  22495. // Update frustum
  22496. if (!this._frustumPlanes) {
  22497. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  22498. }
  22499. else {
  22500. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  22501. }
  22502. if (this.activeCamera && this.activeCamera._alternateCamera) {
  22503. var otherCamera = this.activeCamera._alternateCamera;
  22504. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  22505. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  22506. }
  22507. if (this._sceneUbo.useUbo) {
  22508. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  22509. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  22510. this._sceneUbo.update();
  22511. }
  22512. };
  22513. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  22514. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  22515. return;
  22516. }
  22517. this._alternateViewUpdateFlag = view.updateFlag;
  22518. this._alternateProjectionUpdateFlag = projection.updateFlag;
  22519. this._alternateViewMatrix = view;
  22520. this._alternateProjectionMatrix = projection;
  22521. if (!this._alternateTransformMatrix) {
  22522. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  22523. }
  22524. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  22525. if (!this._alternateSceneUbo) {
  22526. this._createAlternateUbo();
  22527. }
  22528. if (this._alternateSceneUbo.useUbo) {
  22529. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  22530. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  22531. this._alternateSceneUbo.update();
  22532. }
  22533. };
  22534. Scene.prototype.getSceneUniformBuffer = function () {
  22535. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  22536. };
  22537. // Methods
  22538. Scene.prototype.getUniqueId = function () {
  22539. var result = Scene._uniqueIdCounter;
  22540. Scene._uniqueIdCounter++;
  22541. return result;
  22542. };
  22543. Scene.prototype.addMesh = function (newMesh) {
  22544. this.meshes.push(newMesh);
  22545. //notify the collision coordinator
  22546. if (this.collisionCoordinator) {
  22547. this.collisionCoordinator.onMeshAdded(newMesh);
  22548. }
  22549. newMesh._resyncLightSources();
  22550. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  22551. };
  22552. Scene.prototype.removeMesh = function (toRemove) {
  22553. var index = this.meshes.indexOf(toRemove);
  22554. if (index !== -1) {
  22555. // Remove from the scene if mesh found
  22556. this.meshes.splice(index, 1);
  22557. }
  22558. this.onMeshRemovedObservable.notifyObservers(toRemove);
  22559. return index;
  22560. };
  22561. Scene.prototype.addTransformNode = function (newTransformNode) {
  22562. this.transformNodes.push(newTransformNode);
  22563. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  22564. };
  22565. Scene.prototype.removeTransformNode = function (toRemove) {
  22566. var index = this.transformNodes.indexOf(toRemove);
  22567. if (index !== -1) {
  22568. // Remove from the scene if found
  22569. this.transformNodes.splice(index, 1);
  22570. }
  22571. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  22572. return index;
  22573. };
  22574. Scene.prototype.removeSkeleton = function (toRemove) {
  22575. var index = this.skeletons.indexOf(toRemove);
  22576. if (index !== -1) {
  22577. // Remove from the scene if found
  22578. this.skeletons.splice(index, 1);
  22579. }
  22580. return index;
  22581. };
  22582. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  22583. var index = this.morphTargetManagers.indexOf(toRemove);
  22584. if (index !== -1) {
  22585. // Remove from the scene if found
  22586. this.morphTargetManagers.splice(index, 1);
  22587. }
  22588. return index;
  22589. };
  22590. Scene.prototype.removeLight = function (toRemove) {
  22591. var index = this.lights.indexOf(toRemove);
  22592. if (index !== -1) {
  22593. // Remove from meshes
  22594. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  22595. var mesh = _a[_i];
  22596. mesh._removeLightSource(toRemove);
  22597. }
  22598. // Remove from the scene if mesh found
  22599. this.lights.splice(index, 1);
  22600. this.sortLightsByPriority();
  22601. }
  22602. this.onLightRemovedObservable.notifyObservers(toRemove);
  22603. return index;
  22604. };
  22605. Scene.prototype.removeCamera = function (toRemove) {
  22606. var index = this.cameras.indexOf(toRemove);
  22607. if (index !== -1) {
  22608. // Remove from the scene if mesh found
  22609. this.cameras.splice(index, 1);
  22610. }
  22611. // Remove from activeCameras
  22612. var index2 = this.activeCameras.indexOf(toRemove);
  22613. if (index2 !== -1) {
  22614. // Remove from the scene if mesh found
  22615. this.activeCameras.splice(index2, 1);
  22616. }
  22617. // Reset the activeCamera
  22618. if (this.activeCamera === toRemove) {
  22619. if (this.cameras.length > 0) {
  22620. this.activeCamera = this.cameras[0];
  22621. }
  22622. else {
  22623. this.activeCamera = null;
  22624. }
  22625. }
  22626. this.onCameraRemovedObservable.notifyObservers(toRemove);
  22627. return index;
  22628. };
  22629. Scene.prototype.removeParticleSystem = function (toRemove) {
  22630. var index = this.particleSystems.indexOf(toRemove);
  22631. if (index !== -1) {
  22632. this.particleSystems.splice(index, 1);
  22633. }
  22634. return index;
  22635. };
  22636. ;
  22637. Scene.prototype.removeAnimation = function (toRemove) {
  22638. var index = this.animations.indexOf(toRemove);
  22639. if (index !== -1) {
  22640. this.animations.splice(index, 1);
  22641. }
  22642. return index;
  22643. };
  22644. ;
  22645. Scene.prototype.removeMultiMaterial = function (toRemove) {
  22646. var index = this.multiMaterials.indexOf(toRemove);
  22647. if (index !== -1) {
  22648. this.multiMaterials.splice(index, 1);
  22649. }
  22650. return index;
  22651. };
  22652. ;
  22653. Scene.prototype.removeMaterial = function (toRemove) {
  22654. var index = this.materials.indexOf(toRemove);
  22655. if (index !== -1) {
  22656. this.materials.splice(index, 1);
  22657. }
  22658. return index;
  22659. };
  22660. ;
  22661. Scene.prototype.removeLensFlareSystem = function (toRemove) {
  22662. var index = this.lensFlareSystems.indexOf(toRemove);
  22663. if (index !== -1) {
  22664. this.lensFlareSystems.splice(index, 1);
  22665. }
  22666. return index;
  22667. };
  22668. ;
  22669. Scene.prototype.removeActionManager = function (toRemove) {
  22670. var index = this._actionManagers.indexOf(toRemove);
  22671. if (index !== -1) {
  22672. this._actionManagers.splice(index, 1);
  22673. }
  22674. return index;
  22675. };
  22676. ;
  22677. Scene.prototype.addLight = function (newLight) {
  22678. this.lights.push(newLight);
  22679. this.sortLightsByPriority();
  22680. // Add light to all meshes (To support if the light is removed and then readded)
  22681. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  22682. var mesh = _a[_i];
  22683. if (mesh._lightSources.indexOf(newLight) === -1) {
  22684. mesh._lightSources.push(newLight);
  22685. mesh._resyncLightSources();
  22686. }
  22687. }
  22688. this.onNewLightAddedObservable.notifyObservers(newLight);
  22689. };
  22690. Scene.prototype.sortLightsByPriority = function () {
  22691. if (this.requireLightSorting) {
  22692. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  22693. }
  22694. };
  22695. Scene.prototype.addCamera = function (newCamera) {
  22696. this.cameras.push(newCamera);
  22697. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  22698. };
  22699. Scene.prototype.addSkeleton = function (newSkeleton) {
  22700. this.skeletons.push(newSkeleton);
  22701. };
  22702. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  22703. this.particleSystems.push(newParticleSystem);
  22704. };
  22705. Scene.prototype.addAnimation = function (newAnimation) {
  22706. this.animations.push(newAnimation);
  22707. };
  22708. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  22709. this.multiMaterials.push(newMultiMaterial);
  22710. };
  22711. Scene.prototype.addMaterial = function (newMaterial) {
  22712. this.materials.push(newMaterial);
  22713. };
  22714. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  22715. this.morphTargetManagers.push(newMorphTargetManager);
  22716. };
  22717. Scene.prototype.addGeometry = function (newGeometrie) {
  22718. this._geometries.push(newGeometrie);
  22719. };
  22720. Scene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  22721. this.lensFlareSystems.push(newLensFlareSystem);
  22722. };
  22723. Scene.prototype.addActionManager = function (newActionManager) {
  22724. this._actionManagers.push(newActionManager);
  22725. };
  22726. /**
  22727. * Switch active camera
  22728. * @param {Camera} newCamera - new active camera
  22729. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  22730. */
  22731. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  22732. if (attachControl === void 0) { attachControl = true; }
  22733. var canvas = this._engine.getRenderingCanvas();
  22734. if (!canvas) {
  22735. return;
  22736. }
  22737. if (this.activeCamera) {
  22738. this.activeCamera.detachControl(canvas);
  22739. }
  22740. this.activeCamera = newCamera;
  22741. if (attachControl) {
  22742. newCamera.attachControl(canvas);
  22743. }
  22744. };
  22745. /**
  22746. * sets the active camera of the scene using its ID
  22747. * @param {string} id - the camera's ID
  22748. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  22749. * @see activeCamera
  22750. */
  22751. Scene.prototype.setActiveCameraByID = function (id) {
  22752. var camera = this.getCameraByID(id);
  22753. if (camera) {
  22754. this.activeCamera = camera;
  22755. return camera;
  22756. }
  22757. return null;
  22758. };
  22759. /**
  22760. * sets the active camera of the scene using its name
  22761. * @param {string} name - the camera's name
  22762. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  22763. * @see activeCamera
  22764. */
  22765. Scene.prototype.setActiveCameraByName = function (name) {
  22766. var camera = this.getCameraByName(name);
  22767. if (camera) {
  22768. this.activeCamera = camera;
  22769. return camera;
  22770. }
  22771. return null;
  22772. };
  22773. /**
  22774. * get an animation group using its name
  22775. * @param {string} the material's name
  22776. * @return {BABYLON.AnimationGroup|null} the animation group or null if none found.
  22777. */
  22778. Scene.prototype.getAnimationGroupByName = function (name) {
  22779. for (var index = 0; index < this.animationGroups.length; index++) {
  22780. if (this.animationGroups[index].name === name) {
  22781. return this.animationGroups[index];
  22782. }
  22783. }
  22784. return null;
  22785. };
  22786. /**
  22787. * get a material using its id
  22788. * @param {string} the material's ID
  22789. * @return {BABYLON.Material|null} the material or null if none found.
  22790. */
  22791. Scene.prototype.getMaterialByID = function (id) {
  22792. for (var index = 0; index < this.materials.length; index++) {
  22793. if (this.materials[index].id === id) {
  22794. return this.materials[index];
  22795. }
  22796. }
  22797. return null;
  22798. };
  22799. /**
  22800. * get a material using its name
  22801. * @param {string} the material's name
  22802. * @return {BABYLON.Material|null} the material or null if none found.
  22803. */
  22804. Scene.prototype.getMaterialByName = function (name) {
  22805. for (var index = 0; index < this.materials.length; index++) {
  22806. if (this.materials[index].name === name) {
  22807. return this.materials[index];
  22808. }
  22809. }
  22810. return null;
  22811. };
  22812. Scene.prototype.getLensFlareSystemByName = function (name) {
  22813. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  22814. if (this.lensFlareSystems[index].name === name) {
  22815. return this.lensFlareSystems[index];
  22816. }
  22817. }
  22818. return null;
  22819. };
  22820. Scene.prototype.getLensFlareSystemByID = function (id) {
  22821. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  22822. if (this.lensFlareSystems[index].id === id) {
  22823. return this.lensFlareSystems[index];
  22824. }
  22825. }
  22826. return null;
  22827. };
  22828. Scene.prototype.getCameraByID = function (id) {
  22829. for (var index = 0; index < this.cameras.length; index++) {
  22830. if (this.cameras[index].id === id) {
  22831. return this.cameras[index];
  22832. }
  22833. }
  22834. return null;
  22835. };
  22836. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  22837. for (var index = 0; index < this.cameras.length; index++) {
  22838. if (this.cameras[index].uniqueId === uniqueId) {
  22839. return this.cameras[index];
  22840. }
  22841. }
  22842. return null;
  22843. };
  22844. /**
  22845. * get a camera using its name
  22846. * @param {string} the camera's name
  22847. * @return {BABYLON.Camera|null} the camera or null if none found.
  22848. */
  22849. Scene.prototype.getCameraByName = function (name) {
  22850. for (var index = 0; index < this.cameras.length; index++) {
  22851. if (this.cameras[index].name === name) {
  22852. return this.cameras[index];
  22853. }
  22854. }
  22855. return null;
  22856. };
  22857. /**
  22858. * get a bone using its id
  22859. * @param {string} the bone's id
  22860. * @return {BABYLON.Bone|null} the bone or null if not found
  22861. */
  22862. Scene.prototype.getBoneByID = function (id) {
  22863. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  22864. var skeleton = this.skeletons[skeletonIndex];
  22865. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  22866. if (skeleton.bones[boneIndex].id === id) {
  22867. return skeleton.bones[boneIndex];
  22868. }
  22869. }
  22870. }
  22871. return null;
  22872. };
  22873. /**
  22874. * get a bone using its id
  22875. * @param {string} the bone's name
  22876. * @return {BABYLON.Bone|null} the bone or null if not found
  22877. */
  22878. Scene.prototype.getBoneByName = function (name) {
  22879. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  22880. var skeleton = this.skeletons[skeletonIndex];
  22881. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  22882. if (skeleton.bones[boneIndex].name === name) {
  22883. return skeleton.bones[boneIndex];
  22884. }
  22885. }
  22886. }
  22887. return null;
  22888. };
  22889. /**
  22890. * get a light node using its name
  22891. * @param {string} the light's name
  22892. * @return {BABYLON.Light|null} the light or null if none found.
  22893. */
  22894. Scene.prototype.getLightByName = function (name) {
  22895. for (var index = 0; index < this.lights.length; index++) {
  22896. if (this.lights[index].name === name) {
  22897. return this.lights[index];
  22898. }
  22899. }
  22900. return null;
  22901. };
  22902. /**
  22903. * get a light node using its ID
  22904. * @param {string} the light's id
  22905. * @return {BABYLON.Light|null} the light or null if none found.
  22906. */
  22907. Scene.prototype.getLightByID = function (id) {
  22908. for (var index = 0; index < this.lights.length; index++) {
  22909. if (this.lights[index].id === id) {
  22910. return this.lights[index];
  22911. }
  22912. }
  22913. return null;
  22914. };
  22915. /**
  22916. * get a light node using its scene-generated unique ID
  22917. * @param {number} the light's unique id
  22918. * @return {BABYLON.Light|null} the light or null if none found.
  22919. */
  22920. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  22921. for (var index = 0; index < this.lights.length; index++) {
  22922. if (this.lights[index].uniqueId === uniqueId) {
  22923. return this.lights[index];
  22924. }
  22925. }
  22926. return null;
  22927. };
  22928. /**
  22929. * get a particle system by id
  22930. * @param id {number} the particle system id
  22931. * @return {BABYLON.IParticleSystem|null} the corresponding system or null if none found.
  22932. */
  22933. Scene.prototype.getParticleSystemByID = function (id) {
  22934. for (var index = 0; index < this.particleSystems.length; index++) {
  22935. if (this.particleSystems[index].id === id) {
  22936. return this.particleSystems[index];
  22937. }
  22938. }
  22939. return null;
  22940. };
  22941. /**
  22942. * get a geometry using its ID
  22943. * @param {string} the geometry's id
  22944. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  22945. */
  22946. Scene.prototype.getGeometryByID = function (id) {
  22947. for (var index = 0; index < this._geometries.length; index++) {
  22948. if (this._geometries[index].id === id) {
  22949. return this._geometries[index];
  22950. }
  22951. }
  22952. return null;
  22953. };
  22954. /**
  22955. * add a new geometry to this scene.
  22956. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  22957. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  22958. * @return {boolean} was the geometry added or not
  22959. */
  22960. Scene.prototype.pushGeometry = function (geometry, force) {
  22961. if (!force && this.getGeometryByID(geometry.id)) {
  22962. return false;
  22963. }
  22964. this._geometries.push(geometry);
  22965. //notify the collision coordinator
  22966. if (this.collisionCoordinator) {
  22967. this.collisionCoordinator.onGeometryAdded(geometry);
  22968. }
  22969. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  22970. return true;
  22971. };
  22972. /**
  22973. * Removes an existing geometry
  22974. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  22975. * @return {boolean} was the geometry removed or not
  22976. */
  22977. Scene.prototype.removeGeometry = function (geometry) {
  22978. var index = this._geometries.indexOf(geometry);
  22979. if (index > -1) {
  22980. this._geometries.splice(index, 1);
  22981. //notify the collision coordinator
  22982. if (this.collisionCoordinator) {
  22983. this.collisionCoordinator.onGeometryDeleted(geometry);
  22984. }
  22985. this.onGeometryRemovedObservable.notifyObservers(geometry);
  22986. return true;
  22987. }
  22988. return false;
  22989. };
  22990. Scene.prototype.getGeometries = function () {
  22991. return this._geometries;
  22992. };
  22993. /**
  22994. * Get the first added mesh found of a given ID
  22995. * @param {string} id - the id to search for
  22996. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  22997. */
  22998. Scene.prototype.getMeshByID = function (id) {
  22999. for (var index = 0; index < this.meshes.length; index++) {
  23000. if (this.meshes[index].id === id) {
  23001. return this.meshes[index];
  23002. }
  23003. }
  23004. return null;
  23005. };
  23006. Scene.prototype.getMeshesByID = function (id) {
  23007. return this.meshes.filter(function (m) {
  23008. return m.id === id;
  23009. });
  23010. };
  23011. /**
  23012. * Get the first added transform node found of a given ID
  23013. * @param {string} id - the id to search for
  23014. * @return {BABYLON.TransformNode|null} the transform node found or null if not found at all.
  23015. */
  23016. Scene.prototype.getTransformNodeByID = function (id) {
  23017. for (var index = 0; index < this.transformNodes.length; index++) {
  23018. if (this.transformNodes[index].id === id) {
  23019. return this.transformNodes[index];
  23020. }
  23021. }
  23022. return null;
  23023. };
  23024. Scene.prototype.getTransformNodesByID = function (id) {
  23025. return this.transformNodes.filter(function (m) {
  23026. return m.id === id;
  23027. });
  23028. };
  23029. /**
  23030. * Get a mesh with its auto-generated unique id
  23031. * @param {number} uniqueId - the unique id to search for
  23032. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  23033. */
  23034. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  23035. for (var index = 0; index < this.meshes.length; index++) {
  23036. if (this.meshes[index].uniqueId === uniqueId) {
  23037. return this.meshes[index];
  23038. }
  23039. }
  23040. return null;
  23041. };
  23042. /**
  23043. * Get a the last added mesh found of a given ID
  23044. * @param {string} id - the id to search for
  23045. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  23046. */
  23047. Scene.prototype.getLastMeshByID = function (id) {
  23048. for (var index = this.meshes.length - 1; index >= 0; index--) {
  23049. if (this.meshes[index].id === id) {
  23050. return this.meshes[index];
  23051. }
  23052. }
  23053. return null;
  23054. };
  23055. /**
  23056. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  23057. * @param {string} id - the id to search for
  23058. * @return {BABYLON.Node|null} the node found or null if not found at all.
  23059. */
  23060. Scene.prototype.getLastEntryByID = function (id) {
  23061. var index;
  23062. for (index = this.meshes.length - 1; index >= 0; index--) {
  23063. if (this.meshes[index].id === id) {
  23064. return this.meshes[index];
  23065. }
  23066. }
  23067. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  23068. if (this.transformNodes[index].id === id) {
  23069. return this.transformNodes[index];
  23070. }
  23071. }
  23072. for (index = this.cameras.length - 1; index >= 0; index--) {
  23073. if (this.cameras[index].id === id) {
  23074. return this.cameras[index];
  23075. }
  23076. }
  23077. for (index = this.lights.length - 1; index >= 0; index--) {
  23078. if (this.lights[index].id === id) {
  23079. return this.lights[index];
  23080. }
  23081. }
  23082. return null;
  23083. };
  23084. Scene.prototype.getNodeByID = function (id) {
  23085. var mesh = this.getMeshByID(id);
  23086. if (mesh) {
  23087. return mesh;
  23088. }
  23089. var light = this.getLightByID(id);
  23090. if (light) {
  23091. return light;
  23092. }
  23093. var camera = this.getCameraByID(id);
  23094. if (camera) {
  23095. return camera;
  23096. }
  23097. var bone = this.getBoneByID(id);
  23098. return bone;
  23099. };
  23100. Scene.prototype.getNodeByName = function (name) {
  23101. var mesh = this.getMeshByName(name);
  23102. if (mesh) {
  23103. return mesh;
  23104. }
  23105. var light = this.getLightByName(name);
  23106. if (light) {
  23107. return light;
  23108. }
  23109. var camera = this.getCameraByName(name);
  23110. if (camera) {
  23111. return camera;
  23112. }
  23113. var bone = this.getBoneByName(name);
  23114. return bone;
  23115. };
  23116. Scene.prototype.getMeshByName = function (name) {
  23117. for (var index = 0; index < this.meshes.length; index++) {
  23118. if (this.meshes[index].name === name) {
  23119. return this.meshes[index];
  23120. }
  23121. }
  23122. return null;
  23123. };
  23124. Scene.prototype.getTransformNodeByName = function (name) {
  23125. for (var index = 0; index < this.transformNodes.length; index++) {
  23126. if (this.transformNodes[index].name === name) {
  23127. return this.transformNodes[index];
  23128. }
  23129. }
  23130. return null;
  23131. };
  23132. Scene.prototype.getSoundByName = function (name) {
  23133. var index;
  23134. if (BABYLON.AudioEngine) {
  23135. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  23136. if (this.mainSoundTrack.soundCollection[index].name === name) {
  23137. return this.mainSoundTrack.soundCollection[index];
  23138. }
  23139. }
  23140. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  23141. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  23142. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  23143. return this.soundTracks[sdIndex].soundCollection[index];
  23144. }
  23145. }
  23146. }
  23147. }
  23148. return null;
  23149. };
  23150. Scene.prototype.getLastSkeletonByID = function (id) {
  23151. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  23152. if (this.skeletons[index].id === id) {
  23153. return this.skeletons[index];
  23154. }
  23155. }
  23156. return null;
  23157. };
  23158. Scene.prototype.getSkeletonById = function (id) {
  23159. for (var index = 0; index < this.skeletons.length; index++) {
  23160. if (this.skeletons[index].id === id) {
  23161. return this.skeletons[index];
  23162. }
  23163. }
  23164. return null;
  23165. };
  23166. Scene.prototype.getSkeletonByName = function (name) {
  23167. for (var index = 0; index < this.skeletons.length; index++) {
  23168. if (this.skeletons[index].name === name) {
  23169. return this.skeletons[index];
  23170. }
  23171. }
  23172. return null;
  23173. };
  23174. Scene.prototype.getMorphTargetManagerById = function (id) {
  23175. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  23176. if (this.morphTargetManagers[index].uniqueId === id) {
  23177. return this.morphTargetManagers[index];
  23178. }
  23179. }
  23180. return null;
  23181. };
  23182. Scene.prototype.isActiveMesh = function (mesh) {
  23183. return (this._activeMeshes.indexOf(mesh) !== -1);
  23184. };
  23185. /**
  23186. * Return a the first highlight layer of the scene with a given name.
  23187. * @param name The name of the highlight layer to look for.
  23188. * @return The highlight layer if found otherwise null.
  23189. */
  23190. Scene.prototype.getHighlightLayerByName = function (name) {
  23191. for (var index = 0; index < this.effectLayers.length; index++) {
  23192. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.HighlightLayer.EffectName) {
  23193. return this.effectLayers[index];
  23194. }
  23195. }
  23196. return null;
  23197. };
  23198. /**
  23199. * Return a the first highlight layer of the scene with a given name.
  23200. * @param name The name of the highlight layer to look for.
  23201. * @return The highlight layer if found otherwise null.
  23202. */
  23203. Scene.prototype.getGlowLayerByName = function (name) {
  23204. for (var index = 0; index < this.effectLayers.length; index++) {
  23205. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.GlowLayer.EffectName) {
  23206. return this.effectLayers[index];
  23207. }
  23208. }
  23209. return null;
  23210. };
  23211. Object.defineProperty(Scene.prototype, "uid", {
  23212. /**
  23213. * Return a unique id as a string which can serve as an identifier for the scene
  23214. */
  23215. get: function () {
  23216. if (!this._uid) {
  23217. this._uid = BABYLON.Tools.RandomId();
  23218. }
  23219. return this._uid;
  23220. },
  23221. enumerable: true,
  23222. configurable: true
  23223. });
  23224. /**
  23225. * Add an externaly attached data from its key.
  23226. * This method call will fail and return false, if such key already exists.
  23227. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  23228. * @param key the unique key that identifies the data
  23229. * @param data the data object to associate to the key for this Engine instance
  23230. * @return true if no such key were already present and the data was added successfully, false otherwise
  23231. */
  23232. Scene.prototype.addExternalData = function (key, data) {
  23233. if (!this._externalData) {
  23234. this._externalData = new BABYLON.StringDictionary();
  23235. }
  23236. return this._externalData.add(key, data);
  23237. };
  23238. /**
  23239. * Get an externaly attached data from its key
  23240. * @param key the unique key that identifies the data
  23241. * @return the associated data, if present (can be null), or undefined if not present
  23242. */
  23243. Scene.prototype.getExternalData = function (key) {
  23244. if (!this._externalData) {
  23245. return null;
  23246. }
  23247. return this._externalData.get(key);
  23248. };
  23249. /**
  23250. * Get an externaly attached data from its key, create it using a factory if it's not already present
  23251. * @param key the unique key that identifies the data
  23252. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  23253. * @return the associated data, can be null if the factory returned null.
  23254. */
  23255. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  23256. if (!this._externalData) {
  23257. this._externalData = new BABYLON.StringDictionary();
  23258. }
  23259. return this._externalData.getOrAddWithFactory(key, factory);
  23260. };
  23261. /**
  23262. * Remove an externaly attached data from the Engine instance
  23263. * @param key the unique key that identifies the data
  23264. * @return true if the data was successfully removed, false if it doesn't exist
  23265. */
  23266. Scene.prototype.removeExternalData = function (key) {
  23267. return this._externalData.remove(key);
  23268. };
  23269. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  23270. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  23271. if (mesh.showSubMeshesBoundingBox) {
  23272. var boundingInfo = subMesh.getBoundingInfo();
  23273. if (boundingInfo !== null && boundingInfo !== undefined) {
  23274. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  23275. }
  23276. }
  23277. var material = subMesh.getMaterial();
  23278. if (material !== null && material !== undefined) {
  23279. // Render targets
  23280. if (material.getRenderTargetTextures !== undefined) {
  23281. if (this._processedMaterials.indexOf(material) === -1) {
  23282. this._processedMaterials.push(material);
  23283. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  23284. }
  23285. }
  23286. // Dispatch
  23287. this._activeIndices.addCount(subMesh.indexCount, false);
  23288. this._renderingManager.dispatch(subMesh, mesh, material);
  23289. }
  23290. }
  23291. };
  23292. Scene.prototype._isInIntermediateRendering = function () {
  23293. return this._intermediateRendering;
  23294. };
  23295. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  23296. this._activeMeshCandidateProvider = provider;
  23297. };
  23298. Scene.prototype.getActiveMeshCandidateProvider = function () {
  23299. return this._activeMeshCandidateProvider;
  23300. };
  23301. /**
  23302. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  23303. */
  23304. Scene.prototype.freezeActiveMeshes = function () {
  23305. this._evaluateActiveMeshes();
  23306. this._activeMeshesFrozen = true;
  23307. return this;
  23308. };
  23309. /**
  23310. * Use this function to restart evaluating active meshes on every frame
  23311. */
  23312. Scene.prototype.unfreezeActiveMeshes = function () {
  23313. this._activeMeshesFrozen = false;
  23314. return this;
  23315. };
  23316. Scene.prototype._evaluateActiveMeshes = function () {
  23317. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  23318. return;
  23319. }
  23320. if (!this.activeCamera) {
  23321. return;
  23322. }
  23323. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  23324. this.activeCamera._activeMeshes.reset();
  23325. this._activeMeshes.reset();
  23326. this._renderingManager.reset();
  23327. this._processedMaterials.reset();
  23328. this._activeParticleSystems.reset();
  23329. this._activeSkeletons.reset();
  23330. this._softwareSkinnedMeshes.reset();
  23331. if (this._boundingBoxRenderer) {
  23332. this._boundingBoxRenderer.reset();
  23333. }
  23334. // Meshes
  23335. var meshes;
  23336. var len;
  23337. var checkIsEnabled = true;
  23338. // Determine mesh candidates
  23339. if (this._activeMeshCandidateProvider !== undefined) {
  23340. // Use _activeMeshCandidateProvider
  23341. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  23342. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  23343. if (meshes !== undefined) {
  23344. len = meshes.length;
  23345. }
  23346. else {
  23347. len = 0;
  23348. }
  23349. }
  23350. else if (this._selectionOctree !== undefined) {
  23351. // Octree
  23352. var selection = this._selectionOctree.select(this._frustumPlanes);
  23353. meshes = selection.data;
  23354. len = selection.length;
  23355. }
  23356. else {
  23357. // Full scene traversal
  23358. len = this.meshes.length;
  23359. meshes = this.meshes;
  23360. }
  23361. // Check each mesh
  23362. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  23363. mesh = meshes[meshIndex];
  23364. if (mesh.isBlocked) {
  23365. continue;
  23366. }
  23367. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  23368. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  23369. continue;
  23370. }
  23371. mesh.computeWorldMatrix();
  23372. // Intersections
  23373. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  23374. this._meshesForIntersections.pushNoDuplicate(mesh);
  23375. }
  23376. // Switch to current LOD
  23377. meshLOD = mesh.getLOD(this.activeCamera);
  23378. if (meshLOD === undefined || meshLOD === null) {
  23379. continue;
  23380. }
  23381. mesh._preActivate();
  23382. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  23383. this._activeMeshes.push(mesh);
  23384. this.activeCamera._activeMeshes.push(mesh);
  23385. mesh._activate(this._renderId);
  23386. if (meshLOD !== mesh) {
  23387. meshLOD._activate(this._renderId);
  23388. }
  23389. this._activeMesh(mesh, meshLOD);
  23390. }
  23391. }
  23392. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  23393. // Particle systems
  23394. if (this.particlesEnabled) {
  23395. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  23396. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  23397. var particleSystem = this.particleSystems[particleIndex];
  23398. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  23399. continue;
  23400. }
  23401. var emitter = particleSystem.emitter;
  23402. if (!emitter.position || emitter.isEnabled()) {
  23403. this._activeParticleSystems.push(particleSystem);
  23404. particleSystem.animate();
  23405. this._renderingManager.dispatchParticles(particleSystem);
  23406. }
  23407. }
  23408. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  23409. }
  23410. };
  23411. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  23412. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  23413. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  23414. mesh.skeleton.prepare();
  23415. }
  23416. if (!mesh.computeBonesUsingShaders) {
  23417. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  23418. }
  23419. }
  23420. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  23421. var boundingInfo = sourceMesh.getBoundingInfo();
  23422. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  23423. }
  23424. if (mesh !== undefined && mesh !== null
  23425. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  23426. // Submeshes Octrees
  23427. var len;
  23428. var subMeshes;
  23429. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  23430. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  23431. len = intersections.length;
  23432. subMeshes = intersections.data;
  23433. }
  23434. else {
  23435. subMeshes = mesh.subMeshes;
  23436. len = subMeshes.length;
  23437. }
  23438. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  23439. subMesh = subMeshes[subIndex];
  23440. this._evaluateSubMesh(subMesh, mesh);
  23441. }
  23442. }
  23443. };
  23444. Scene.prototype.updateTransformMatrix = function (force) {
  23445. if (!this.activeCamera) {
  23446. return;
  23447. }
  23448. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  23449. };
  23450. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  23451. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  23452. };
  23453. Scene.prototype._renderForCamera = function (camera) {
  23454. if (camera && camera._skipRendering) {
  23455. return;
  23456. }
  23457. var engine = this._engine;
  23458. this.activeCamera = camera;
  23459. if (!this.activeCamera)
  23460. throw new Error("Active camera not set");
  23461. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  23462. // Viewport
  23463. engine.setViewport(this.activeCamera.viewport);
  23464. // Camera
  23465. this.resetCachedMaterial();
  23466. this._renderId++;
  23467. this.activeCamera.update();
  23468. this.updateTransformMatrix();
  23469. if (camera._alternateCamera) {
  23470. this.updateAlternateTransformMatrix(camera._alternateCamera);
  23471. this._alternateRendering = true;
  23472. }
  23473. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  23474. // Meshes
  23475. this._evaluateActiveMeshes();
  23476. // Software skinning
  23477. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  23478. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  23479. mesh.applySkeleton(mesh.skeleton);
  23480. }
  23481. // Render targets
  23482. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  23483. var needsRestoreFrameBuffer = false;
  23484. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  23485. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  23486. }
  23487. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  23488. this._intermediateRendering = true;
  23489. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  23490. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  23491. var renderTarget = this._renderTargets.data[renderIndex];
  23492. if (renderTarget._shouldRender()) {
  23493. this._renderId++;
  23494. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  23495. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  23496. }
  23497. }
  23498. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  23499. this._intermediateRendering = false;
  23500. this._renderId++;
  23501. needsRestoreFrameBuffer = true; // Restore back buffer
  23502. }
  23503. // Render EffecttLayer Texture
  23504. var stencilState = this._engine.getStencilBuffer();
  23505. var renderEffects = false;
  23506. var needStencil = false;
  23507. if (this.renderTargetsEnabled && this.effectLayers && this.effectLayers.length > 0) {
  23508. this._intermediateRendering = true;
  23509. for (var i = 0; i < this.effectLayers.length; i++) {
  23510. var effectLayer = this.effectLayers[i];
  23511. if (effectLayer.shouldRender() &&
  23512. (!effectLayer.camera ||
  23513. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  23514. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  23515. renderEffects = true;
  23516. needStencil = needStencil || effectLayer.needStencil();
  23517. var renderTarget = effectLayer._mainTexture;
  23518. if (renderTarget._shouldRender()) {
  23519. this._renderId++;
  23520. renderTarget.render(false, false);
  23521. needsRestoreFrameBuffer = true;
  23522. }
  23523. }
  23524. }
  23525. this._intermediateRendering = false;
  23526. this._renderId++;
  23527. }
  23528. if (needsRestoreFrameBuffer) {
  23529. engine.restoreDefaultFramebuffer(); // Restore back buffer
  23530. }
  23531. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  23532. // Prepare Frame
  23533. this.postProcessManager._prepareFrame();
  23534. // Backgrounds
  23535. var layerIndex;
  23536. var layer;
  23537. if (this.layers.length) {
  23538. engine.setDepthBuffer(false);
  23539. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  23540. layer = this.layers[layerIndex];
  23541. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  23542. layer.render();
  23543. }
  23544. }
  23545. engine.setDepthBuffer(true);
  23546. }
  23547. // Activate effect Layer stencil
  23548. if (needStencil) {
  23549. this._engine.setStencilBuffer(true);
  23550. }
  23551. // Render
  23552. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  23553. this._renderingManager.render(null, null, true, true);
  23554. this.onAfterDrawPhaseObservable.notifyObservers(this);
  23555. // Restore effect Layer stencil
  23556. if (needStencil) {
  23557. this._engine.setStencilBuffer(stencilState);
  23558. }
  23559. // Bounding boxes
  23560. if (this._boundingBoxRenderer) {
  23561. this._boundingBoxRenderer.render();
  23562. }
  23563. // Lens flares
  23564. if (this.lensFlaresEnabled) {
  23565. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  23566. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  23567. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  23568. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  23569. lensFlareSystem.render();
  23570. }
  23571. }
  23572. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  23573. }
  23574. // Foregrounds
  23575. if (this.layers.length) {
  23576. engine.setDepthBuffer(false);
  23577. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  23578. layer = this.layers[layerIndex];
  23579. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  23580. layer.render();
  23581. }
  23582. }
  23583. engine.setDepthBuffer(true);
  23584. }
  23585. // Effect Layer
  23586. if (renderEffects) {
  23587. engine.setDepthBuffer(false);
  23588. for (var i = 0; i < this.effectLayers.length; i++) {
  23589. if (this.effectLayers[i].shouldRender()) {
  23590. this.effectLayers[i].render();
  23591. }
  23592. }
  23593. engine.setDepthBuffer(true);
  23594. }
  23595. // Finalize frame
  23596. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  23597. // Reset some special arrays
  23598. this._renderTargets.reset();
  23599. this._alternateRendering = false;
  23600. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  23601. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  23602. };
  23603. Scene.prototype._processSubCameras = function (camera) {
  23604. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  23605. this._renderForCamera(camera);
  23606. return;
  23607. }
  23608. // Update camera
  23609. if (this.activeCamera) {
  23610. this.activeCamera.update();
  23611. }
  23612. // rig cameras
  23613. for (var index = 0; index < camera._rigCameras.length; index++) {
  23614. this._renderForCamera(camera._rigCameras[index]);
  23615. }
  23616. this.activeCamera = camera;
  23617. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  23618. };
  23619. Scene.prototype._checkIntersections = function () {
  23620. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  23621. var sourceMesh = this._meshesForIntersections.data[index];
  23622. if (!sourceMesh.actionManager) {
  23623. continue;
  23624. }
  23625. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  23626. var action = sourceMesh.actionManager.actions[actionIndex];
  23627. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  23628. var parameters = action.getTriggerParameter();
  23629. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  23630. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  23631. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  23632. if (areIntersecting && currentIntersectionInProgress === -1) {
  23633. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  23634. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  23635. sourceMesh._intersectionsInProgress.push(otherMesh);
  23636. }
  23637. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  23638. sourceMesh._intersectionsInProgress.push(otherMesh);
  23639. }
  23640. }
  23641. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  23642. //They intersected, and now they don't.
  23643. //is this trigger an exit trigger? execute an event.
  23644. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  23645. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  23646. }
  23647. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  23648. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  23649. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  23650. }
  23651. }
  23652. }
  23653. }
  23654. }
  23655. };
  23656. Scene.prototype.render = function () {
  23657. if (this.isDisposed) {
  23658. return;
  23659. }
  23660. this._activeParticles.fetchNewFrame();
  23661. this._totalVertices.fetchNewFrame();
  23662. this._activeIndices.fetchNewFrame();
  23663. this._activeBones.fetchNewFrame();
  23664. this._meshesForIntersections.reset();
  23665. this.resetCachedMaterial();
  23666. this.onBeforeAnimationsObservable.notifyObservers(this);
  23667. // Actions
  23668. if (this.actionManager) {
  23669. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  23670. }
  23671. //Simplification Queue
  23672. if (this.simplificationQueue && !this.simplificationQueue.running) {
  23673. this.simplificationQueue.executeNext();
  23674. }
  23675. if (this._engine.isDeterministicLockStep()) {
  23676. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  23677. var defaultFPS = (60.0 / 1000.0);
  23678. var defaultFrameTime = 1000 / 60; // frame time in MS
  23679. if (this._physicsEngine) {
  23680. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  23681. }
  23682. var stepsTaken = 0;
  23683. var maxSubSteps = this._engine.getLockstepMaxSteps();
  23684. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  23685. internalSteps = Math.min(internalSteps, maxSubSteps);
  23686. do {
  23687. this.onBeforeStepObservable.notifyObservers(this);
  23688. // Animations
  23689. this._animationRatio = defaultFrameTime * defaultFPS;
  23690. this._animate();
  23691. this.onAfterAnimationsObservable.notifyObservers(this);
  23692. // Physics
  23693. if (this._physicsEngine) {
  23694. this.onBeforePhysicsObservable.notifyObservers(this);
  23695. this._physicsEngine._step(defaultFrameTime / 1000);
  23696. this.onAfterPhysicsObservable.notifyObservers(this);
  23697. }
  23698. this.onAfterStepObservable.notifyObservers(this);
  23699. this._currentStepId++;
  23700. stepsTaken++;
  23701. deltaTime -= defaultFrameTime;
  23702. } while (deltaTime > 0 && stepsTaken < internalSteps);
  23703. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  23704. }
  23705. else {
  23706. // Animations
  23707. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  23708. this._animationRatio = deltaTime * (60.0 / 1000.0);
  23709. this._animate();
  23710. this.onAfterAnimationsObservable.notifyObservers(this);
  23711. // Physics
  23712. if (this._physicsEngine) {
  23713. this.onBeforePhysicsObservable.notifyObservers(this);
  23714. this._physicsEngine._step(deltaTime / 1000.0);
  23715. this.onAfterPhysicsObservable.notifyObservers(this);
  23716. }
  23717. }
  23718. // update gamepad manager
  23719. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  23720. this._gamepadManager._checkGamepadsStatus();
  23721. }
  23722. // Before render
  23723. this.onBeforeRenderObservable.notifyObservers(this);
  23724. // Customs render targets
  23725. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  23726. var engine = this.getEngine();
  23727. var currentActiveCamera = this.activeCamera;
  23728. if (this.renderTargetsEnabled) {
  23729. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  23730. this._intermediateRendering = true;
  23731. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  23732. var renderTarget = this.customRenderTargets[customIndex];
  23733. if (renderTarget._shouldRender()) {
  23734. this._renderId++;
  23735. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  23736. if (!this.activeCamera)
  23737. throw new Error("Active camera not set");
  23738. // Viewport
  23739. engine.setViewport(this.activeCamera.viewport);
  23740. // Camera
  23741. this.updateTransformMatrix();
  23742. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  23743. }
  23744. }
  23745. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  23746. this._intermediateRendering = false;
  23747. this._renderId++;
  23748. }
  23749. // Restore back buffer
  23750. if (this.customRenderTargets.length > 0) {
  23751. engine.restoreDefaultFramebuffer();
  23752. }
  23753. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  23754. this.activeCamera = currentActiveCamera;
  23755. // Procedural textures
  23756. if (this.proceduralTexturesEnabled) {
  23757. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  23758. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  23759. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  23760. if (proceduralTexture._shouldRender()) {
  23761. proceduralTexture.render();
  23762. }
  23763. }
  23764. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  23765. }
  23766. // Clear
  23767. if (this.autoClearDepthAndStencil || this.autoClear) {
  23768. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  23769. }
  23770. // Shadows
  23771. if (this.shadowsEnabled) {
  23772. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  23773. var light = this.lights[lightIndex];
  23774. var shadowGenerator = light.getShadowGenerator();
  23775. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  23776. var shadowMap = (shadowGenerator.getShadowMap());
  23777. if (this.textures.indexOf(shadowMap) !== -1) {
  23778. this._renderTargets.push(shadowMap);
  23779. }
  23780. }
  23781. }
  23782. }
  23783. // Depth renderer
  23784. if (this._depthRenderer) {
  23785. this._renderTargets.push(this._depthRenderer.getDepthMap());
  23786. }
  23787. // Geometry renderer
  23788. if (this._geometryBufferRenderer) {
  23789. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  23790. }
  23791. // RenderPipeline
  23792. if (this._postProcessRenderPipelineManager) {
  23793. this._postProcessRenderPipelineManager.update();
  23794. }
  23795. // Multi-cameras?
  23796. if (this.activeCameras.length > 0) {
  23797. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  23798. if (cameraIndex > 0) {
  23799. this._engine.clear(null, false, true, true);
  23800. }
  23801. this._processSubCameras(this.activeCameras[cameraIndex]);
  23802. }
  23803. }
  23804. else {
  23805. if (!this.activeCamera) {
  23806. throw new Error("No camera defined");
  23807. }
  23808. this._processSubCameras(this.activeCamera);
  23809. }
  23810. // Intersection checks
  23811. this._checkIntersections();
  23812. // Update the audio listener attached to the camera
  23813. if (BABYLON.AudioEngine) {
  23814. this._updateAudioParameters();
  23815. }
  23816. // After render
  23817. if (this.afterRender) {
  23818. this.afterRender();
  23819. }
  23820. this.onAfterRenderObservable.notifyObservers(this);
  23821. // Cleaning
  23822. for (var index = 0; index < this._toBeDisposed.length; index++) {
  23823. var data = this._toBeDisposed.data[index];
  23824. if (data) {
  23825. data.dispose();
  23826. }
  23827. this._toBeDisposed[index] = null;
  23828. }
  23829. this._toBeDisposed.reset();
  23830. if (this.dumpNextRenderTargets) {
  23831. this.dumpNextRenderTargets = false;
  23832. }
  23833. this._activeBones.addCount(0, true);
  23834. this._activeIndices.addCount(0, true);
  23835. this._activeParticles.addCount(0, true);
  23836. };
  23837. Scene.prototype._updateAudioParameters = function () {
  23838. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  23839. return;
  23840. }
  23841. var listeningCamera;
  23842. var audioEngine = BABYLON.Engine.audioEngine;
  23843. if (this.activeCameras.length > 0) {
  23844. listeningCamera = this.activeCameras[0];
  23845. }
  23846. else {
  23847. listeningCamera = this.activeCamera;
  23848. }
  23849. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  23850. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  23851. // for VR cameras
  23852. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  23853. listeningCamera = listeningCamera.rigCameras[0];
  23854. }
  23855. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  23856. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  23857. cameraDirection.normalize();
  23858. // To avoid some errors on GearVR
  23859. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  23860. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  23861. }
  23862. var i;
  23863. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  23864. var sound = this.mainSoundTrack.soundCollection[i];
  23865. if (sound.useCustomAttenuation) {
  23866. sound.updateDistanceFromListener();
  23867. }
  23868. }
  23869. for (i = 0; i < this.soundTracks.length; i++) {
  23870. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  23871. sound = this.soundTracks[i].soundCollection[j];
  23872. if (sound.useCustomAttenuation) {
  23873. sound.updateDistanceFromListener();
  23874. }
  23875. }
  23876. }
  23877. }
  23878. };
  23879. Object.defineProperty(Scene.prototype, "audioEnabled", {
  23880. // Audio
  23881. get: function () {
  23882. return this._audioEnabled;
  23883. },
  23884. set: function (value) {
  23885. this._audioEnabled = value;
  23886. if (BABYLON.AudioEngine) {
  23887. if (this._audioEnabled) {
  23888. this._enableAudio();
  23889. }
  23890. else {
  23891. this._disableAudio();
  23892. }
  23893. }
  23894. },
  23895. enumerable: true,
  23896. configurable: true
  23897. });
  23898. Scene.prototype._disableAudio = function () {
  23899. var i;
  23900. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  23901. this.mainSoundTrack.soundCollection[i].pause();
  23902. }
  23903. for (i = 0; i < this.soundTracks.length; i++) {
  23904. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  23905. this.soundTracks[i].soundCollection[j].pause();
  23906. }
  23907. }
  23908. };
  23909. Scene.prototype._enableAudio = function () {
  23910. var i;
  23911. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  23912. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  23913. this.mainSoundTrack.soundCollection[i].play();
  23914. }
  23915. }
  23916. for (i = 0; i < this.soundTracks.length; i++) {
  23917. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  23918. if (this.soundTracks[i].soundCollection[j].isPaused) {
  23919. this.soundTracks[i].soundCollection[j].play();
  23920. }
  23921. }
  23922. }
  23923. };
  23924. Object.defineProperty(Scene.prototype, "headphone", {
  23925. get: function () {
  23926. return this._headphone;
  23927. },
  23928. set: function (value) {
  23929. this._headphone = value;
  23930. if (BABYLON.AudioEngine) {
  23931. if (this._headphone) {
  23932. this._switchAudioModeForHeadphones();
  23933. }
  23934. else {
  23935. this._switchAudioModeForNormalSpeakers();
  23936. }
  23937. }
  23938. },
  23939. enumerable: true,
  23940. configurable: true
  23941. });
  23942. Scene.prototype._switchAudioModeForHeadphones = function () {
  23943. this.mainSoundTrack.switchPanningModelToHRTF();
  23944. for (var i = 0; i < this.soundTracks.length; i++) {
  23945. this.soundTracks[i].switchPanningModelToHRTF();
  23946. }
  23947. };
  23948. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  23949. this.mainSoundTrack.switchPanningModelToEqualPower();
  23950. for (var i = 0; i < this.soundTracks.length; i++) {
  23951. this.soundTracks[i].switchPanningModelToEqualPower();
  23952. }
  23953. };
  23954. Scene.prototype.enableDepthRenderer = function () {
  23955. if (this._depthRenderer) {
  23956. return this._depthRenderer;
  23957. }
  23958. this._depthRenderer = new BABYLON.DepthRenderer(this);
  23959. return this._depthRenderer;
  23960. };
  23961. Scene.prototype.disableDepthRenderer = function () {
  23962. if (!this._depthRenderer) {
  23963. return;
  23964. }
  23965. this._depthRenderer.dispose();
  23966. this._depthRenderer = null;
  23967. };
  23968. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  23969. if (ratio === void 0) { ratio = 1; }
  23970. if (this._geometryBufferRenderer) {
  23971. return this._geometryBufferRenderer;
  23972. }
  23973. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  23974. if (!this._geometryBufferRenderer.isSupported) {
  23975. this._geometryBufferRenderer = null;
  23976. }
  23977. return this._geometryBufferRenderer;
  23978. };
  23979. Scene.prototype.disableGeometryBufferRenderer = function () {
  23980. if (!this._geometryBufferRenderer) {
  23981. return;
  23982. }
  23983. this._geometryBufferRenderer.dispose();
  23984. this._geometryBufferRenderer = null;
  23985. };
  23986. Scene.prototype.freezeMaterials = function () {
  23987. for (var i = 0; i < this.materials.length; i++) {
  23988. this.materials[i].freeze();
  23989. }
  23990. };
  23991. Scene.prototype.unfreezeMaterials = function () {
  23992. for (var i = 0; i < this.materials.length; i++) {
  23993. this.materials[i].unfreeze();
  23994. }
  23995. };
  23996. Scene.prototype.dispose = function () {
  23997. this.beforeRender = null;
  23998. this.afterRender = null;
  23999. this.skeletons = [];
  24000. this.morphTargetManagers = [];
  24001. this.importedMeshesFiles = new Array();
  24002. this.stopAllAnimations();
  24003. this.resetCachedMaterial();
  24004. if (this._depthRenderer) {
  24005. this._depthRenderer.dispose();
  24006. }
  24007. if (this._gamepadManager) {
  24008. this._gamepadManager.dispose();
  24009. this._gamepadManager = null;
  24010. }
  24011. // Smart arrays
  24012. if (this.activeCamera) {
  24013. this.activeCamera._activeMeshes.dispose();
  24014. this.activeCamera = null;
  24015. }
  24016. this._activeMeshes.dispose();
  24017. this._renderingManager.dispose();
  24018. this._processedMaterials.dispose();
  24019. this._activeParticleSystems.dispose();
  24020. this._activeSkeletons.dispose();
  24021. this._softwareSkinnedMeshes.dispose();
  24022. this._renderTargets.dispose();
  24023. if (this._boundingBoxRenderer) {
  24024. this._boundingBoxRenderer.dispose();
  24025. }
  24026. this._meshesForIntersections.dispose();
  24027. this._toBeDisposed.dispose();
  24028. // Abort active requests
  24029. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  24030. var request = _a[_i];
  24031. request.abort();
  24032. }
  24033. // Debug layer
  24034. if (this._debugLayer) {
  24035. this._debugLayer.hide();
  24036. }
  24037. // Events
  24038. this.onDisposeObservable.notifyObservers(this);
  24039. this.onDisposeObservable.clear();
  24040. this.onBeforeRenderObservable.clear();
  24041. this.onAfterRenderObservable.clear();
  24042. this.OnBeforeRenderTargetsRenderObservable.clear();
  24043. this.OnAfterRenderTargetsRenderObservable.clear();
  24044. this.onAfterStepObservable.clear();
  24045. this.onBeforeStepObservable.clear();
  24046. this.onBeforeActiveMeshesEvaluationObservable.clear();
  24047. this.onAfterActiveMeshesEvaluationObservable.clear();
  24048. this.onBeforeParticlesRenderingObservable.clear();
  24049. this.onAfterParticlesRenderingObservable.clear();
  24050. this.onBeforeSpritesRenderingObservable.clear();
  24051. this.onAfterSpritesRenderingObservable.clear();
  24052. this.onBeforeDrawPhaseObservable.clear();
  24053. this.onAfterDrawPhaseObservable.clear();
  24054. this.onBeforePhysicsObservable.clear();
  24055. this.onAfterPhysicsObservable.clear();
  24056. this.onBeforeAnimationsObservable.clear();
  24057. this.onAfterAnimationsObservable.clear();
  24058. this.onDataLoadedObservable.clear();
  24059. this.detachControl();
  24060. // Release sounds & sounds tracks
  24061. if (BABYLON.AudioEngine) {
  24062. this.disposeSounds();
  24063. }
  24064. // VR Helper
  24065. if (this.VRHelper) {
  24066. this.VRHelper.dispose();
  24067. }
  24068. // Detach cameras
  24069. var canvas = this._engine.getRenderingCanvas();
  24070. if (canvas) {
  24071. var index;
  24072. for (index = 0; index < this.cameras.length; index++) {
  24073. this.cameras[index].detachControl(canvas);
  24074. }
  24075. }
  24076. // Release animation groups
  24077. while (this.animationGroups.length) {
  24078. this.animationGroups[0].dispose();
  24079. }
  24080. // Release lights
  24081. while (this.lights.length) {
  24082. this.lights[0].dispose();
  24083. }
  24084. // Release meshes
  24085. while (this.meshes.length) {
  24086. this.meshes[0].dispose(true);
  24087. }
  24088. while (this.transformNodes.length) {
  24089. this.removeTransformNode(this.transformNodes[0]);
  24090. }
  24091. // Release cameras
  24092. while (this.cameras.length) {
  24093. this.cameras[0].dispose();
  24094. }
  24095. // Release materials
  24096. if (this.defaultMaterial) {
  24097. this.defaultMaterial.dispose();
  24098. }
  24099. while (this.multiMaterials.length) {
  24100. this.multiMaterials[0].dispose();
  24101. }
  24102. while (this.materials.length) {
  24103. this.materials[0].dispose();
  24104. }
  24105. // Release particles
  24106. while (this.particleSystems.length) {
  24107. this.particleSystems[0].dispose();
  24108. }
  24109. // Release sprites
  24110. while (this.spriteManagers.length) {
  24111. this.spriteManagers[0].dispose();
  24112. }
  24113. // Release postProcesses
  24114. while (this.postProcesses.length) {
  24115. this.postProcesses[0].dispose();
  24116. }
  24117. // Release layers
  24118. while (this.layers.length) {
  24119. this.layers[0].dispose();
  24120. }
  24121. while (this.effectLayers.length) {
  24122. this.effectLayers[0].dispose();
  24123. }
  24124. // Release textures
  24125. while (this.textures.length) {
  24126. this.textures[0].dispose();
  24127. }
  24128. // Release UBO
  24129. this._sceneUbo.dispose();
  24130. if (this._alternateSceneUbo) {
  24131. this._alternateSceneUbo.dispose();
  24132. }
  24133. // Post-processes
  24134. this.postProcessManager.dispose();
  24135. if (this._postProcessRenderPipelineManager) {
  24136. this._postProcessRenderPipelineManager.dispose();
  24137. }
  24138. // Physics
  24139. if (this._physicsEngine) {
  24140. this.disablePhysicsEngine();
  24141. }
  24142. // Remove from engine
  24143. index = this._engine.scenes.indexOf(this);
  24144. if (index > -1) {
  24145. this._engine.scenes.splice(index, 1);
  24146. }
  24147. this._engine.wipeCaches(true);
  24148. this._isDisposed = true;
  24149. };
  24150. Object.defineProperty(Scene.prototype, "isDisposed", {
  24151. get: function () {
  24152. return this._isDisposed;
  24153. },
  24154. enumerable: true,
  24155. configurable: true
  24156. });
  24157. // Release sounds & sounds tracks
  24158. Scene.prototype.disposeSounds = function () {
  24159. if (!this._mainSoundTrack) {
  24160. return;
  24161. }
  24162. this.mainSoundTrack.dispose();
  24163. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  24164. this.soundTracks[scIndex].dispose();
  24165. }
  24166. };
  24167. // Octrees
  24168. Scene.prototype.getWorldExtends = function () {
  24169. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  24170. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  24171. for (var index = 0; index < this.meshes.length; index++) {
  24172. var mesh = this.meshes[index];
  24173. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  24174. continue;
  24175. }
  24176. mesh.computeWorldMatrix(true);
  24177. var boundingInfo = mesh.getBoundingInfo();
  24178. var minBox = boundingInfo.boundingBox.minimumWorld;
  24179. var maxBox = boundingInfo.boundingBox.maximumWorld;
  24180. BABYLON.Tools.CheckExtends(minBox, min, max);
  24181. BABYLON.Tools.CheckExtends(maxBox, min, max);
  24182. }
  24183. return {
  24184. min: min,
  24185. max: max
  24186. };
  24187. };
  24188. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  24189. if (maxCapacity === void 0) { maxCapacity = 64; }
  24190. if (maxDepth === void 0) { maxDepth = 2; }
  24191. if (!this._selectionOctree) {
  24192. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  24193. }
  24194. var worldExtends = this.getWorldExtends();
  24195. // Update octree
  24196. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  24197. return this._selectionOctree;
  24198. };
  24199. // Picking
  24200. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  24201. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  24202. var result = BABYLON.Ray.Zero();
  24203. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  24204. return result;
  24205. };
  24206. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  24207. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  24208. var engine = this._engine;
  24209. if (!camera) {
  24210. if (!this.activeCamera)
  24211. throw new Error("Active camera not set");
  24212. camera = this.activeCamera;
  24213. }
  24214. var cameraViewport = camera.viewport;
  24215. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  24216. // Moving coordinates to local viewport world
  24217. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  24218. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  24219. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  24220. return this;
  24221. };
  24222. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  24223. var result = BABYLON.Ray.Zero();
  24224. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  24225. return result;
  24226. };
  24227. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  24228. if (!BABYLON.PickingInfo) {
  24229. return this;
  24230. }
  24231. var engine = this._engine;
  24232. if (!camera) {
  24233. if (!this.activeCamera)
  24234. throw new Error("Active camera not set");
  24235. camera = this.activeCamera;
  24236. }
  24237. var cameraViewport = camera.viewport;
  24238. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  24239. var identity = BABYLON.Matrix.Identity();
  24240. // Moving coordinates to local viewport world
  24241. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  24242. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  24243. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  24244. return this;
  24245. };
  24246. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  24247. if (!BABYLON.PickingInfo) {
  24248. return null;
  24249. }
  24250. var pickingInfo = null;
  24251. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  24252. var mesh = this.meshes[meshIndex];
  24253. if (predicate) {
  24254. if (!predicate(mesh)) {
  24255. continue;
  24256. }
  24257. }
  24258. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  24259. continue;
  24260. }
  24261. var world = mesh.getWorldMatrix();
  24262. var ray = rayFunction(world);
  24263. var result = mesh.intersects(ray, fastCheck);
  24264. if (!result || !result.hit)
  24265. continue;
  24266. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  24267. continue;
  24268. pickingInfo = result;
  24269. if (fastCheck) {
  24270. break;
  24271. }
  24272. }
  24273. return pickingInfo || new BABYLON.PickingInfo();
  24274. };
  24275. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  24276. if (!BABYLON.PickingInfo) {
  24277. return null;
  24278. }
  24279. var pickingInfos = new Array();
  24280. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  24281. var mesh = this.meshes[meshIndex];
  24282. if (predicate) {
  24283. if (!predicate(mesh)) {
  24284. continue;
  24285. }
  24286. }
  24287. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  24288. continue;
  24289. }
  24290. var world = mesh.getWorldMatrix();
  24291. var ray = rayFunction(world);
  24292. var result = mesh.intersects(ray, false);
  24293. if (!result || !result.hit)
  24294. continue;
  24295. pickingInfos.push(result);
  24296. }
  24297. return pickingInfos;
  24298. };
  24299. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  24300. if (!BABYLON.PickingInfo) {
  24301. return null;
  24302. }
  24303. var pickingInfo = null;
  24304. if (!camera) {
  24305. if (!this.activeCamera) {
  24306. return null;
  24307. }
  24308. camera = this.activeCamera;
  24309. }
  24310. if (this.spriteManagers.length > 0) {
  24311. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  24312. var spriteManager = this.spriteManagers[spriteIndex];
  24313. if (!spriteManager.isPickable) {
  24314. continue;
  24315. }
  24316. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  24317. if (!result || !result.hit)
  24318. continue;
  24319. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  24320. continue;
  24321. pickingInfo = result;
  24322. if (fastCheck) {
  24323. break;
  24324. }
  24325. }
  24326. }
  24327. return pickingInfo || new BABYLON.PickingInfo();
  24328. };
  24329. /** Launch a ray to try to pick a mesh in the scene
  24330. * @param x position on screen
  24331. * @param y position on screen
  24332. * @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
  24333. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  24334. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  24335. */
  24336. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  24337. var _this = this;
  24338. if (!BABYLON.PickingInfo) {
  24339. return null;
  24340. }
  24341. return this._internalPick(function (world) {
  24342. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  24343. return _this._tempPickingRay;
  24344. }, predicate, fastCheck);
  24345. };
  24346. /** Launch a ray to try to pick a sprite in the scene
  24347. * @param x position on screen
  24348. * @param y position on screen
  24349. * @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
  24350. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  24351. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  24352. */
  24353. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  24354. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  24355. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  24356. };
  24357. /** Use the given ray to pick a mesh in the scene
  24358. * @param ray The ray to use to pick meshes
  24359. * @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
  24360. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  24361. */
  24362. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  24363. var _this = this;
  24364. return this._internalPick(function (world) {
  24365. if (!_this._pickWithRayInverseMatrix) {
  24366. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  24367. }
  24368. world.invertToRef(_this._pickWithRayInverseMatrix);
  24369. if (!_this._cachedRayForTransform) {
  24370. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  24371. }
  24372. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  24373. return _this._cachedRayForTransform;
  24374. }, predicate, fastCheck);
  24375. };
  24376. /**
  24377. * Launch a ray to try to pick a mesh in the scene
  24378. * @param x X position on screen
  24379. * @param y Y position on screen
  24380. * @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
  24381. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  24382. */
  24383. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  24384. var _this = this;
  24385. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  24386. };
  24387. /**
  24388. * Launch a ray to try to pick a mesh in the scene
  24389. * @param ray Ray to use
  24390. * @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
  24391. */
  24392. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  24393. var _this = this;
  24394. return this._internalMultiPick(function (world) {
  24395. if (!_this._pickWithRayInverseMatrix) {
  24396. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  24397. }
  24398. world.invertToRef(_this._pickWithRayInverseMatrix);
  24399. if (!_this._cachedRayForTransform) {
  24400. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  24401. }
  24402. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  24403. return _this._cachedRayForTransform;
  24404. }, predicate);
  24405. };
  24406. Scene.prototype.setPointerOverMesh = function (mesh) {
  24407. if (this._pointerOverMesh === mesh) {
  24408. return;
  24409. }
  24410. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  24411. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  24412. }
  24413. this._pointerOverMesh = mesh;
  24414. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  24415. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  24416. }
  24417. };
  24418. Scene.prototype.getPointerOverMesh = function () {
  24419. return this._pointerOverMesh;
  24420. };
  24421. Scene.prototype.setPointerOverSprite = function (sprite) {
  24422. if (this._pointerOverSprite === sprite) {
  24423. return;
  24424. }
  24425. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  24426. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  24427. }
  24428. this._pointerOverSprite = sprite;
  24429. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  24430. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  24431. }
  24432. };
  24433. Scene.prototype.getPointerOverSprite = function () {
  24434. return this._pointerOverSprite;
  24435. };
  24436. // Physics
  24437. Scene.prototype.getPhysicsEngine = function () {
  24438. return this._physicsEngine;
  24439. };
  24440. /**
  24441. * Enables physics to the current scene
  24442. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  24443. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  24444. * @return {boolean} was the physics engine initialized
  24445. */
  24446. Scene.prototype.enablePhysics = function (gravity, plugin) {
  24447. if (gravity === void 0) { gravity = null; }
  24448. if (this._physicsEngine) {
  24449. return true;
  24450. }
  24451. try {
  24452. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  24453. return true;
  24454. }
  24455. catch (e) {
  24456. BABYLON.Tools.Error(e.message);
  24457. return false;
  24458. }
  24459. };
  24460. Scene.prototype.disablePhysicsEngine = function () {
  24461. if (!this._physicsEngine) {
  24462. return;
  24463. }
  24464. this._physicsEngine.dispose();
  24465. this._physicsEngine = null;
  24466. };
  24467. Scene.prototype.isPhysicsEnabled = function () {
  24468. return this._physicsEngine !== undefined;
  24469. };
  24470. Scene.prototype.deleteCompoundImpostor = function (compound) {
  24471. var mesh = compound.parts[0].mesh;
  24472. if (mesh.physicsImpostor) {
  24473. mesh.physicsImpostor.dispose();
  24474. mesh.physicsImpostor = null;
  24475. }
  24476. };
  24477. // Misc.
  24478. Scene.prototype._rebuildGeometries = function () {
  24479. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  24480. var geometry = _a[_i];
  24481. geometry._rebuild();
  24482. }
  24483. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  24484. var mesh = _c[_b];
  24485. mesh._rebuild();
  24486. }
  24487. if (this.postProcessManager) {
  24488. this.postProcessManager._rebuild();
  24489. }
  24490. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  24491. var layer = _e[_d];
  24492. layer._rebuild();
  24493. }
  24494. for (var _f = 0, _g = this.effectLayers; _f < _g.length; _f++) {
  24495. var effectLayer = _g[_f];
  24496. effectLayer._rebuild();
  24497. }
  24498. if (this._boundingBoxRenderer) {
  24499. this._boundingBoxRenderer._rebuild();
  24500. }
  24501. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  24502. var system = _j[_h];
  24503. system.rebuild();
  24504. }
  24505. if (this._postProcessRenderPipelineManager) {
  24506. this._postProcessRenderPipelineManager._rebuild();
  24507. }
  24508. };
  24509. Scene.prototype._rebuildTextures = function () {
  24510. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  24511. var texture = _a[_i];
  24512. texture._rebuild();
  24513. }
  24514. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24515. };
  24516. /**
  24517. * Creates a default light for the scene.
  24518. * @param replace Whether to replace the existing lights in the scene.
  24519. */
  24520. Scene.prototype.createDefaultLight = function (replace) {
  24521. if (replace === void 0) { replace = false; }
  24522. // Dispose existing light in replace mode.
  24523. if (replace) {
  24524. if (this.lights) {
  24525. for (var i = 0; i < this.lights.length; i++) {
  24526. this.lights[i].dispose();
  24527. }
  24528. }
  24529. }
  24530. // Light
  24531. if (this.lights.length === 0) {
  24532. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  24533. }
  24534. };
  24535. /**
  24536. * Creates a default camera for the scene.
  24537. * @param createArcRotateCamera Whether to create an arc rotate or a free camera.
  24538. * @param replace Whether to replace the existing active camera in the scene.
  24539. * @param attachCameraControls Whether to attach camera controls to the canvas.
  24540. */
  24541. Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  24542. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  24543. if (replace === void 0) { replace = false; }
  24544. if (attachCameraControls === void 0) { attachCameraControls = false; }
  24545. // Dispose existing camera in replace mode.
  24546. if (replace) {
  24547. if (this.activeCamera) {
  24548. this.activeCamera.dispose();
  24549. this.activeCamera = null;
  24550. }
  24551. }
  24552. // Camera
  24553. if (!this.activeCamera) {
  24554. var worldExtends = this.getWorldExtends();
  24555. var worldSize = worldExtends.max.subtract(worldExtends.min);
  24556. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  24557. var camera;
  24558. var radius = worldSize.length() * 1.5;
  24559. // empty scene scenario!
  24560. if (!isFinite(radius)) {
  24561. radius = 1;
  24562. worldCenter.copyFromFloats(0, 0, 0);
  24563. }
  24564. if (createArcRotateCamera) {
  24565. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  24566. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  24567. arcRotateCamera.wheelPrecision = 100 / radius;
  24568. camera = arcRotateCamera;
  24569. }
  24570. else {
  24571. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  24572. freeCamera.setTarget(worldCenter);
  24573. camera = freeCamera;
  24574. }
  24575. camera.minZ = radius * 0.01;
  24576. camera.maxZ = radius * 1000;
  24577. camera.speed = radius * 0.2;
  24578. this.activeCamera = camera;
  24579. var canvas = this.getEngine().getRenderingCanvas();
  24580. if (attachCameraControls && canvas) {
  24581. camera.attachControl(canvas);
  24582. }
  24583. }
  24584. };
  24585. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  24586. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  24587. if (replace === void 0) { replace = false; }
  24588. if (attachCameraControls === void 0) { attachCameraControls = false; }
  24589. this.createDefaultLight(replace);
  24590. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  24591. };
  24592. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur) {
  24593. if (pbr === void 0) { pbr = false; }
  24594. if (scale === void 0) { scale = 1000; }
  24595. if (blur === void 0) { blur = 0; }
  24596. if (environmentTexture) {
  24597. this.environmentTexture = environmentTexture;
  24598. }
  24599. if (!this.environmentTexture) {
  24600. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  24601. return null;
  24602. }
  24603. // Skybox
  24604. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  24605. if (pbr) {
  24606. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  24607. hdrSkyboxMaterial.backFaceCulling = false;
  24608. hdrSkyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  24609. if (hdrSkyboxMaterial.reflectionTexture) {
  24610. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  24611. }
  24612. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  24613. hdrSkyboxMaterial.disableLighting = true;
  24614. hdrSkyboxMaterial.twoSidedLighting = true;
  24615. hdrSkybox.infiniteDistance = true;
  24616. hdrSkybox.material = hdrSkyboxMaterial;
  24617. }
  24618. else {
  24619. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  24620. skyboxMaterial.backFaceCulling = false;
  24621. skyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  24622. if (skyboxMaterial.reflectionTexture) {
  24623. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  24624. }
  24625. skyboxMaterial.disableLighting = true;
  24626. hdrSkybox.infiniteDistance = true;
  24627. hdrSkybox.material = skyboxMaterial;
  24628. }
  24629. return hdrSkybox;
  24630. };
  24631. Scene.prototype.createDefaultEnvironment = function (options) {
  24632. if (BABYLON.EnvironmentHelper) {
  24633. return new BABYLON.EnvironmentHelper(options, this);
  24634. }
  24635. return null;
  24636. };
  24637. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  24638. if (webVROptions === void 0) { webVROptions = {}; }
  24639. return new BABYLON.VRExperienceHelper(this, webVROptions);
  24640. };
  24641. // Tags
  24642. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  24643. if (tagsQuery === undefined) {
  24644. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  24645. return list;
  24646. }
  24647. var listByTags = [];
  24648. forEach = forEach || (function (item) { return; });
  24649. for (var i in list) {
  24650. var item = list[i];
  24651. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  24652. listByTags.push(item);
  24653. forEach(item);
  24654. }
  24655. }
  24656. return listByTags;
  24657. };
  24658. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  24659. return this._getByTags(this.meshes, tagsQuery, forEach);
  24660. };
  24661. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  24662. return this._getByTags(this.cameras, tagsQuery, forEach);
  24663. };
  24664. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  24665. return this._getByTags(this.lights, tagsQuery, forEach);
  24666. };
  24667. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  24668. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  24669. };
  24670. /**
  24671. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  24672. * This allowed control for front to back rendering or reversly depending of the special needs.
  24673. *
  24674. * @param renderingGroupId The rendering group id corresponding to its index
  24675. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  24676. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  24677. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  24678. */
  24679. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  24680. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  24681. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  24682. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  24683. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  24684. };
  24685. /**
  24686. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  24687. *
  24688. * @param renderingGroupId The rendering group id corresponding to its index
  24689. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  24690. * @param depth Automatically clears depth between groups if true and autoClear is true.
  24691. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  24692. */
  24693. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  24694. if (depth === void 0) { depth = true; }
  24695. if (stencil === void 0) { stencil = true; }
  24696. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  24697. };
  24698. /**
  24699. * Will flag all materials as dirty to trigger new shader compilation
  24700. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  24701. */
  24702. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  24703. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  24704. var material = _a[_i];
  24705. if (predicate && !predicate(material)) {
  24706. continue;
  24707. }
  24708. material.markAsDirty(flag);
  24709. }
  24710. };
  24711. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  24712. var _this = this;
  24713. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  24714. this._activeRequests.push(request);
  24715. request.onCompleteObservable.add(function (request) {
  24716. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  24717. });
  24718. return request;
  24719. };
  24720. /** @ignore */
  24721. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  24722. var _this = this;
  24723. return new Promise(function (resolve, reject) {
  24724. _this._loadFile(url, function (data) {
  24725. resolve(data);
  24726. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  24727. reject(exception);
  24728. });
  24729. });
  24730. };
  24731. // Statics
  24732. Scene._FOGMODE_NONE = 0;
  24733. Scene._FOGMODE_EXP = 1;
  24734. Scene._FOGMODE_EXP2 = 2;
  24735. Scene._FOGMODE_LINEAR = 3;
  24736. Scene._uniqueIdCounter = 0;
  24737. Scene.MinDeltaTime = 1.0;
  24738. Scene.MaxDeltaTime = 1000.0;
  24739. /** The distance in pixel that you have to move to prevent some events */
  24740. Scene.DragMovementThreshold = 10; // in pixels
  24741. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  24742. Scene.LongPressDelay = 500; // in milliseconds
  24743. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  24744. Scene.DoubleClickDelay = 300; // in milliseconds
  24745. /** If you need to check double click without raising a single click at first click, enable this flag */
  24746. Scene.ExclusiveDoubleClickMode = false;
  24747. return Scene;
  24748. }());
  24749. BABYLON.Scene = Scene;
  24750. })(BABYLON || (BABYLON = {}));
  24751. //# sourceMappingURL=babylon.scene.js.map
  24752. var BABYLON;
  24753. (function (BABYLON) {
  24754. /**
  24755. * Set of assets to keep when moving a scene into an asset container.
  24756. */
  24757. var KeepAssets = /** @class */ (function () {
  24758. function KeepAssets() {
  24759. /**
  24760. * Cameras to keep.
  24761. */
  24762. this.cameras = new Array();
  24763. /**
  24764. * Lights to keep.
  24765. */
  24766. this.lights = new Array();
  24767. /**
  24768. * Meshes to keep.
  24769. */
  24770. this.meshes = new Array();
  24771. /**
  24772. * Skeletons to keep.
  24773. */
  24774. this.skeletons = new Array();
  24775. /**
  24776. * ParticleSystems to keep.
  24777. */
  24778. this.particleSystems = new Array();
  24779. /**
  24780. * Animations to keep.
  24781. */
  24782. this.animations = new Array();
  24783. /**
  24784. * MultiMaterials to keep.
  24785. */
  24786. this.multiMaterials = new Array();
  24787. /**
  24788. * Materials to keep.
  24789. */
  24790. this.materials = new Array();
  24791. /**
  24792. * MorphTargetManagers to keep.
  24793. */
  24794. this.morphTargetManagers = new Array();
  24795. /**
  24796. * Geometries to keep.
  24797. */
  24798. this.geometries = new Array();
  24799. /**
  24800. * TransformNodes to keep.
  24801. */
  24802. this.transformNodes = new Array();
  24803. /**
  24804. * LensFlareSystems to keep.
  24805. */
  24806. this.lensFlareSystems = new Array();
  24807. /**
  24808. * ShadowGenerators to keep.
  24809. */
  24810. this.shadowGenerators = new Array();
  24811. /**
  24812. * ActionManagers to keep.
  24813. */
  24814. this.actionManagers = new Array();
  24815. /**
  24816. * Sounds to keep.
  24817. */
  24818. this.sounds = new Array();
  24819. }
  24820. return KeepAssets;
  24821. }());
  24822. BABYLON.KeepAssets = KeepAssets;
  24823. /**
  24824. * Container with a set of assets that can be added or removed from a scene.
  24825. */
  24826. var AssetContainer = /** @class */ (function () {
  24827. /**
  24828. * Instantiates an AssetContainer.
  24829. * @param scene The scene the AssetContainer belongs to.
  24830. */
  24831. function AssetContainer(scene) {
  24832. // Objects
  24833. /**
  24834. * Cameras populated in the container.
  24835. */
  24836. this.cameras = new Array();
  24837. /**
  24838. * Lights populated in the container.
  24839. */
  24840. this.lights = new Array();
  24841. /**
  24842. * Meshes populated in the container.
  24843. */
  24844. this.meshes = new Array();
  24845. /**
  24846. * Skeletons populated in the container.
  24847. */
  24848. this.skeletons = new Array();
  24849. /**
  24850. * ParticleSystems populated in the container.
  24851. */
  24852. this.particleSystems = new Array();
  24853. /**
  24854. * Animations populated in the container.
  24855. */
  24856. this.animations = new Array();
  24857. /**
  24858. * MultiMaterials populated in the container.
  24859. */
  24860. this.multiMaterials = new Array();
  24861. /**
  24862. * Materials populated in the container.
  24863. */
  24864. this.materials = new Array();
  24865. /**
  24866. * MorphTargetManagers populated in the container.
  24867. */
  24868. this.morphTargetManagers = new Array();
  24869. /**
  24870. * Geometries populated in the container.
  24871. */
  24872. this.geometries = new Array();
  24873. /**
  24874. * TransformNodes populated in the container.
  24875. */
  24876. this.transformNodes = new Array();
  24877. /**
  24878. * LensFlareSystems populated in the container.
  24879. */
  24880. this.lensFlareSystems = new Array();
  24881. /**
  24882. * ShadowGenerators populated in the container.
  24883. */
  24884. this.shadowGenerators = new Array();
  24885. /**
  24886. * ActionManagers populated in the container.
  24887. */
  24888. this.actionManagers = new Array();
  24889. /**
  24890. * Sounds populated in the container.
  24891. */
  24892. this.sounds = new Array();
  24893. this.scene = scene;
  24894. }
  24895. /**
  24896. * Adds all the assets from the container to the scene.
  24897. */
  24898. AssetContainer.prototype.addAllToScene = function () {
  24899. var _this = this;
  24900. this.cameras.forEach(function (o) {
  24901. _this.scene.addCamera(o);
  24902. });
  24903. this.lights.forEach(function (o) {
  24904. _this.scene.addLight(o);
  24905. });
  24906. this.meshes.forEach(function (o) {
  24907. _this.scene.addMesh(o);
  24908. });
  24909. this.skeletons.forEach(function (o) {
  24910. _this.scene.addSkeleton(o);
  24911. });
  24912. this.particleSystems.forEach(function (o) {
  24913. _this.scene.addParticleSystem(o);
  24914. });
  24915. this.animations.forEach(function (o) {
  24916. _this.scene.addAnimation(o);
  24917. });
  24918. this.multiMaterials.forEach(function (o) {
  24919. _this.scene.addMultiMaterial(o);
  24920. });
  24921. this.materials.forEach(function (o) {
  24922. _this.scene.addMaterial(o);
  24923. });
  24924. this.morphTargetManagers.forEach(function (o) {
  24925. _this.scene.addMorphTargetManager(o);
  24926. });
  24927. this.geometries.forEach(function (o) {
  24928. _this.scene.addGeometry(o);
  24929. });
  24930. this.transformNodes.forEach(function (o) {
  24931. _this.scene.addTransformNode(o);
  24932. });
  24933. this.lensFlareSystems.forEach(function (o) {
  24934. _this.scene.addLensFlareSystem(o);
  24935. });
  24936. this.actionManagers.forEach(function (o) {
  24937. _this.scene.addActionManager(o);
  24938. });
  24939. this.sounds.forEach(function (o) {
  24940. o.play();
  24941. o.autoplay = true;
  24942. _this.scene.mainSoundTrack.AddSound(o);
  24943. });
  24944. };
  24945. /**
  24946. * Removes all the assets in the container from the scene
  24947. */
  24948. AssetContainer.prototype.removeAllFromScene = function () {
  24949. var _this = this;
  24950. this.cameras.forEach(function (o) {
  24951. _this.scene.removeCamera(o);
  24952. });
  24953. this.lights.forEach(function (o) {
  24954. _this.scene.removeLight(o);
  24955. });
  24956. this.meshes.forEach(function (o) {
  24957. _this.scene.removeMesh(o);
  24958. });
  24959. this.skeletons.forEach(function (o) {
  24960. _this.scene.removeSkeleton(o);
  24961. });
  24962. this.particleSystems.forEach(function (o) {
  24963. _this.scene.removeParticleSystem(o);
  24964. });
  24965. this.animations.forEach(function (o) {
  24966. _this.scene.removeAnimation(o);
  24967. });
  24968. this.multiMaterials.forEach(function (o) {
  24969. _this.scene.removeMultiMaterial(o);
  24970. });
  24971. this.materials.forEach(function (o) {
  24972. _this.scene.removeMaterial(o);
  24973. });
  24974. this.morphTargetManagers.forEach(function (o) {
  24975. _this.scene.removeMorphTargetManager(o);
  24976. });
  24977. this.geometries.forEach(function (o) {
  24978. _this.scene.removeGeometry(o);
  24979. });
  24980. this.transformNodes.forEach(function (o) {
  24981. _this.scene.removeTransformNode(o);
  24982. });
  24983. this.lensFlareSystems.forEach(function (o) {
  24984. _this.scene.removeLensFlareSystem(o);
  24985. });
  24986. this.actionManagers.forEach(function (o) {
  24987. _this.scene.removeActionManager(o);
  24988. });
  24989. this.sounds.forEach(function (o) {
  24990. o.stop();
  24991. o.autoplay = false;
  24992. _this.scene.mainSoundTrack.RemoveSound(o);
  24993. });
  24994. };
  24995. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  24996. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  24997. var asset = sourceAssets_1[_i];
  24998. var move = true;
  24999. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  25000. var keepAsset = keepAssets_1[_a];
  25001. if (asset === keepAsset) {
  25002. move = false;
  25003. break;
  25004. }
  25005. }
  25006. if (move) {
  25007. targetAssets.push(asset);
  25008. }
  25009. }
  25010. };
  25011. /**
  25012. * Removes all the assets contained in the scene and adds them to the container.
  25013. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  25014. */
  25015. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  25016. if (keepAssets === undefined) {
  25017. keepAssets = new KeepAssets();
  25018. }
  25019. this._moveAssets(this.scene.cameras, this.cameras, keepAssets.cameras);
  25020. this._moveAssets(this.scene.meshes, this.meshes, keepAssets.meshes);
  25021. this._moveAssets(this.scene.getGeometries(), this.geometries, keepAssets.geometries);
  25022. this._moveAssets(this.scene.materials, this.materials, keepAssets.materials);
  25023. this._moveAssets(this.scene._actionManagers, this.actionManagers, keepAssets.actionManagers);
  25024. this._moveAssets(this.scene.animations, this.animations, keepAssets.animations);
  25025. this._moveAssets(this.scene.lensFlareSystems, this.lensFlareSystems, keepAssets.lensFlareSystems);
  25026. this._moveAssets(this.scene.lights, this.lights, keepAssets.lights);
  25027. this._moveAssets(this.scene.morphTargetManagers, this.morphTargetManagers, keepAssets.morphTargetManagers);
  25028. this._moveAssets(this.scene.multiMaterials, this.multiMaterials, keepAssets.multiMaterials);
  25029. this._moveAssets(this.scene.skeletons, this.skeletons, keepAssets.skeletons);
  25030. this._moveAssets(this.scene.particleSystems, this.particleSystems, keepAssets.particleSystems);
  25031. this._moveAssets(this.scene.mainSoundTrack.soundCollection, this.sounds, keepAssets.sounds);
  25032. this._moveAssets(this.scene.transformNodes, this.transformNodes, keepAssets.transformNodes);
  25033. this.removeAllFromScene();
  25034. };
  25035. return AssetContainer;
  25036. }());
  25037. BABYLON.AssetContainer = AssetContainer;
  25038. })(BABYLON || (BABYLON = {}));
  25039. //# sourceMappingURL=babylon.assetContainer.js.map
  25040. var BABYLON;
  25041. (function (BABYLON) {
  25042. var Buffer = /** @class */ (function () {
  25043. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  25044. if (instanced === void 0) { instanced = false; }
  25045. if (engine instanceof BABYLON.Mesh) {
  25046. this._engine = engine.getScene().getEngine();
  25047. }
  25048. else {
  25049. this._engine = engine;
  25050. }
  25051. this._updatable = updatable;
  25052. this._data = data;
  25053. this._strideSize = stride;
  25054. if (!postponeInternalCreation) {
  25055. this.create();
  25056. }
  25057. this._instanced = instanced;
  25058. this._instanceDivisor = instanced ? 1 : 0;
  25059. }
  25060. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
  25061. // a lot of these parameters are ignored as they are overriden by the buffer
  25062. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
  25063. };
  25064. // Properties
  25065. Buffer.prototype.isUpdatable = function () {
  25066. return this._updatable;
  25067. };
  25068. Buffer.prototype.getData = function () {
  25069. return this._data;
  25070. };
  25071. Buffer.prototype.getBuffer = function () {
  25072. return this._buffer;
  25073. };
  25074. Buffer.prototype.getStrideSize = function () {
  25075. return this._strideSize;
  25076. };
  25077. Buffer.prototype.getIsInstanced = function () {
  25078. return this._instanced;
  25079. };
  25080. Object.defineProperty(Buffer.prototype, "instanceDivisor", {
  25081. get: function () {
  25082. return this._instanceDivisor;
  25083. },
  25084. set: function (value) {
  25085. this._instanceDivisor = value;
  25086. if (value == 0) {
  25087. this._instanced = false;
  25088. }
  25089. else {
  25090. this._instanced = true;
  25091. }
  25092. },
  25093. enumerable: true,
  25094. configurable: true
  25095. });
  25096. // Methods
  25097. Buffer.prototype.create = function (data) {
  25098. if (data === void 0) { data = null; }
  25099. if (!data && this._buffer) {
  25100. return; // nothing to do
  25101. }
  25102. data = data || this._data;
  25103. if (!data) {
  25104. return;
  25105. }
  25106. if (!this._buffer) {
  25107. if (this._updatable) {
  25108. this._buffer = this._engine.createDynamicVertexBuffer(data);
  25109. this._data = data;
  25110. }
  25111. else {
  25112. this._buffer = this._engine.createVertexBuffer(data);
  25113. }
  25114. }
  25115. else if (this._updatable) {
  25116. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  25117. this._data = data;
  25118. }
  25119. };
  25120. Buffer.prototype._rebuild = function () {
  25121. this._buffer = null;
  25122. this.create(this._data);
  25123. };
  25124. Buffer.prototype.update = function (data) {
  25125. this.create(data);
  25126. };
  25127. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  25128. if (!this._buffer) {
  25129. return;
  25130. }
  25131. if (this._updatable) {
  25132. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  25133. this._data = null;
  25134. }
  25135. };
  25136. Buffer.prototype.dispose = function () {
  25137. if (!this._buffer) {
  25138. return;
  25139. }
  25140. if (this._engine._releaseBuffer(this._buffer)) {
  25141. this._buffer = null;
  25142. }
  25143. };
  25144. return Buffer;
  25145. }());
  25146. BABYLON.Buffer = Buffer;
  25147. })(BABYLON || (BABYLON = {}));
  25148. //# sourceMappingURL=babylon.buffer.js.map
  25149. var BABYLON;
  25150. (function (BABYLON) {
  25151. var VertexBuffer = /** @class */ (function () {
  25152. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  25153. if (!stride) {
  25154. stride = VertexBuffer.DeduceStride(kind);
  25155. }
  25156. if (data instanceof BABYLON.Buffer) {
  25157. if (!stride) {
  25158. stride = data.getStrideSize();
  25159. }
  25160. this._buffer = data;
  25161. this._ownsBuffer = false;
  25162. }
  25163. else {
  25164. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  25165. this._ownsBuffer = true;
  25166. }
  25167. this._stride = stride;
  25168. this._offset = offset ? offset : 0;
  25169. this._size = size ? size : stride;
  25170. this._kind = kind;
  25171. }
  25172. VertexBuffer.prototype._rebuild = function () {
  25173. if (!this._buffer) {
  25174. return;
  25175. }
  25176. this._buffer._rebuild();
  25177. };
  25178. /**
  25179. * Returns the kind of the VertexBuffer (string).
  25180. */
  25181. VertexBuffer.prototype.getKind = function () {
  25182. return this._kind;
  25183. };
  25184. // Properties
  25185. /**
  25186. * Boolean : is the VertexBuffer updatable ?
  25187. */
  25188. VertexBuffer.prototype.isUpdatable = function () {
  25189. return this._buffer.isUpdatable();
  25190. };
  25191. /**
  25192. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  25193. */
  25194. VertexBuffer.prototype.getData = function () {
  25195. return this._buffer.getData();
  25196. };
  25197. /**
  25198. * Returns the WebGLBuffer associated to the VertexBuffer.
  25199. */
  25200. VertexBuffer.prototype.getBuffer = function () {
  25201. return this._buffer.getBuffer();
  25202. };
  25203. /**
  25204. * Returns the stride of the VertexBuffer (integer).
  25205. */
  25206. VertexBuffer.prototype.getStrideSize = function () {
  25207. return this._stride;
  25208. };
  25209. /**
  25210. * Returns the offset (integer).
  25211. */
  25212. VertexBuffer.prototype.getOffset = function () {
  25213. return this._offset;
  25214. };
  25215. /**
  25216. * Returns the VertexBuffer total size (integer).
  25217. */
  25218. VertexBuffer.prototype.getSize = function () {
  25219. return this._size;
  25220. };
  25221. /**
  25222. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  25223. */
  25224. VertexBuffer.prototype.getIsInstanced = function () {
  25225. return this._buffer.getIsInstanced();
  25226. };
  25227. /**
  25228. * Returns the instancing divisor, zero for non-instanced (integer).
  25229. */
  25230. VertexBuffer.prototype.getInstanceDivisor = function () {
  25231. return this._buffer.instanceDivisor;
  25232. };
  25233. // Methods
  25234. /**
  25235. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  25236. * Returns the created WebGLBuffer.
  25237. */
  25238. VertexBuffer.prototype.create = function (data) {
  25239. return this._buffer.create(data);
  25240. };
  25241. /**
  25242. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  25243. * This function will create a new buffer if the current one is not updatable
  25244. * Returns the updated WebGLBuffer.
  25245. */
  25246. VertexBuffer.prototype.update = function (data) {
  25247. return this._buffer.update(data);
  25248. };
  25249. /**
  25250. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  25251. * Returns the directly updated WebGLBuffer.
  25252. */
  25253. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  25254. return this._buffer.updateDirectly(data, offset);
  25255. };
  25256. /**
  25257. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  25258. */
  25259. VertexBuffer.prototype.dispose = function () {
  25260. if (this._ownsBuffer) {
  25261. this._buffer.dispose();
  25262. }
  25263. };
  25264. Object.defineProperty(VertexBuffer, "PositionKind", {
  25265. get: function () {
  25266. return VertexBuffer._PositionKind;
  25267. },
  25268. enumerable: true,
  25269. configurable: true
  25270. });
  25271. Object.defineProperty(VertexBuffer, "NormalKind", {
  25272. get: function () {
  25273. return VertexBuffer._NormalKind;
  25274. },
  25275. enumerable: true,
  25276. configurable: true
  25277. });
  25278. Object.defineProperty(VertexBuffer, "TangentKind", {
  25279. get: function () {
  25280. return VertexBuffer._TangentKind;
  25281. },
  25282. enumerable: true,
  25283. configurable: true
  25284. });
  25285. Object.defineProperty(VertexBuffer, "UVKind", {
  25286. get: function () {
  25287. return VertexBuffer._UVKind;
  25288. },
  25289. enumerable: true,
  25290. configurable: true
  25291. });
  25292. Object.defineProperty(VertexBuffer, "UV2Kind", {
  25293. get: function () {
  25294. return VertexBuffer._UV2Kind;
  25295. },
  25296. enumerable: true,
  25297. configurable: true
  25298. });
  25299. Object.defineProperty(VertexBuffer, "UV3Kind", {
  25300. get: function () {
  25301. return VertexBuffer._UV3Kind;
  25302. },
  25303. enumerable: true,
  25304. configurable: true
  25305. });
  25306. Object.defineProperty(VertexBuffer, "UV4Kind", {
  25307. get: function () {
  25308. return VertexBuffer._UV4Kind;
  25309. },
  25310. enumerable: true,
  25311. configurable: true
  25312. });
  25313. Object.defineProperty(VertexBuffer, "UV5Kind", {
  25314. get: function () {
  25315. return VertexBuffer._UV5Kind;
  25316. },
  25317. enumerable: true,
  25318. configurable: true
  25319. });
  25320. Object.defineProperty(VertexBuffer, "UV6Kind", {
  25321. get: function () {
  25322. return VertexBuffer._UV6Kind;
  25323. },
  25324. enumerable: true,
  25325. configurable: true
  25326. });
  25327. Object.defineProperty(VertexBuffer, "ColorKind", {
  25328. get: function () {
  25329. return VertexBuffer._ColorKind;
  25330. },
  25331. enumerable: true,
  25332. configurable: true
  25333. });
  25334. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  25335. get: function () {
  25336. return VertexBuffer._MatricesIndicesKind;
  25337. },
  25338. enumerable: true,
  25339. configurable: true
  25340. });
  25341. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  25342. get: function () {
  25343. return VertexBuffer._MatricesWeightsKind;
  25344. },
  25345. enumerable: true,
  25346. configurable: true
  25347. });
  25348. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  25349. get: function () {
  25350. return VertexBuffer._MatricesIndicesExtraKind;
  25351. },
  25352. enumerable: true,
  25353. configurable: true
  25354. });
  25355. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  25356. get: function () {
  25357. return VertexBuffer._MatricesWeightsExtraKind;
  25358. },
  25359. enumerable: true,
  25360. configurable: true
  25361. });
  25362. /**
  25363. * Deduces the stride given a kind.
  25364. * @param kind The kind string to deduce
  25365. * @returns The deduced stride
  25366. */
  25367. VertexBuffer.DeduceStride = function (kind) {
  25368. switch (kind) {
  25369. case VertexBuffer.PositionKind:
  25370. return 3;
  25371. case VertexBuffer.NormalKind:
  25372. return 3;
  25373. case VertexBuffer.UVKind:
  25374. case VertexBuffer.UV2Kind:
  25375. case VertexBuffer.UV3Kind:
  25376. case VertexBuffer.UV4Kind:
  25377. case VertexBuffer.UV5Kind:
  25378. case VertexBuffer.UV6Kind:
  25379. return 2;
  25380. case VertexBuffer.TangentKind:
  25381. case VertexBuffer.ColorKind:
  25382. return 4;
  25383. case VertexBuffer.MatricesIndicesKind:
  25384. case VertexBuffer.MatricesIndicesExtraKind:
  25385. return 4;
  25386. case VertexBuffer.MatricesWeightsKind:
  25387. case VertexBuffer.MatricesWeightsExtraKind:
  25388. return 4;
  25389. default:
  25390. throw new Error("Invalid kind '" + kind + "'");
  25391. }
  25392. };
  25393. // Enums
  25394. VertexBuffer._PositionKind = "position";
  25395. VertexBuffer._NormalKind = "normal";
  25396. VertexBuffer._TangentKind = "tangent";
  25397. VertexBuffer._UVKind = "uv";
  25398. VertexBuffer._UV2Kind = "uv2";
  25399. VertexBuffer._UV3Kind = "uv3";
  25400. VertexBuffer._UV4Kind = "uv4";
  25401. VertexBuffer._UV5Kind = "uv5";
  25402. VertexBuffer._UV6Kind = "uv6";
  25403. VertexBuffer._ColorKind = "color";
  25404. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  25405. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  25406. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  25407. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  25408. return VertexBuffer;
  25409. }());
  25410. BABYLON.VertexBuffer = VertexBuffer;
  25411. })(BABYLON || (BABYLON = {}));
  25412. //# sourceMappingURL=babylon.vertexBuffer.js.map
  25413. var BABYLON;
  25414. (function (BABYLON) {
  25415. /**
  25416. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  25417. */
  25418. var DummyInternalTextureTracker = /** @class */ (function () {
  25419. function DummyInternalTextureTracker() {
  25420. /**
  25421. * Gets or set the previous tracker in the list
  25422. */
  25423. this.previous = null;
  25424. /**
  25425. * Gets or set the next tracker in the list
  25426. */
  25427. this.next = null;
  25428. }
  25429. return DummyInternalTextureTracker;
  25430. }());
  25431. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  25432. })(BABYLON || (BABYLON = {}));
  25433. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  25434. var BABYLON;
  25435. (function (BABYLON) {
  25436. /**
  25437. * Class used to store data associated with WebGL texture data for the engine
  25438. * This class should not be used directly
  25439. */
  25440. var InternalTexture = /** @class */ (function () {
  25441. /**
  25442. * Creates a new InternalTexture
  25443. * @param engine defines the engine to use
  25444. * @param dataSource defines the type of data that will be used
  25445. */
  25446. function InternalTexture(engine, dataSource) {
  25447. /**
  25448. * Observable called when the texture is loaded
  25449. */
  25450. this.onLoadedObservable = new BABYLON.Observable();
  25451. /**
  25452. * Gets or set the previous tracker in the list
  25453. */
  25454. this.previous = null;
  25455. /**
  25456. * Gets or set the next tracker in the list
  25457. */
  25458. this.next = null;
  25459. // Private
  25460. /** @ignore */
  25461. this._initialSlot = -1;
  25462. /** @ignore */
  25463. this._designatedSlot = -1;
  25464. /** @ignore */
  25465. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  25466. /** @ignore */
  25467. this._references = 1;
  25468. this._engine = engine;
  25469. this._dataSource = dataSource;
  25470. this._webGLTexture = engine._createTexture();
  25471. }
  25472. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  25473. /**
  25474. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  25475. */
  25476. get: function () {
  25477. return this._dataSource;
  25478. },
  25479. enumerable: true,
  25480. configurable: true
  25481. });
  25482. /**
  25483. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  25484. */
  25485. InternalTexture.prototype.incrementReferences = function () {
  25486. this._references++;
  25487. };
  25488. /**
  25489. * Change the size of the texture (not the size of the content)
  25490. * @param width defines the new width
  25491. * @param height defines the new height
  25492. * @param depth defines the new depth (1 by default)
  25493. */
  25494. InternalTexture.prototype.updateSize = function (width, height, depth) {
  25495. if (depth === void 0) { depth = 1; }
  25496. this.width = width;
  25497. this.height = height;
  25498. this.depth = depth;
  25499. this.baseWidth = width;
  25500. this.baseHeight = height;
  25501. this.baseDepth = depth;
  25502. this._size = width * height * depth;
  25503. };
  25504. /** @ignore */
  25505. InternalTexture.prototype._rebuild = function () {
  25506. var _this = this;
  25507. var proxy;
  25508. this.isReady = false;
  25509. this._cachedCoordinatesMode = null;
  25510. this._cachedWrapU = null;
  25511. this._cachedWrapV = null;
  25512. this._cachedAnisotropicFilteringLevel = null;
  25513. switch (this._dataSource) {
  25514. case InternalTexture.DATASOURCE_TEMP:
  25515. return;
  25516. case InternalTexture.DATASOURCE_URL:
  25517. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  25518. _this.isReady = true;
  25519. }, null, this._buffer, undefined, this.format);
  25520. proxy._swapAndDie(this);
  25521. return;
  25522. case InternalTexture.DATASOURCE_RAW:
  25523. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  25524. proxy._swapAndDie(this);
  25525. this.isReady = true;
  25526. return;
  25527. case InternalTexture.DATASOURCE_RAW3D:
  25528. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  25529. proxy._swapAndDie(this);
  25530. this.isReady = true;
  25531. return;
  25532. case InternalTexture.DATASOURCE_DYNAMIC:
  25533. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  25534. proxy._swapAndDie(this);
  25535. // The engine will make sure to update content so no need to flag it as isReady = true
  25536. return;
  25537. case InternalTexture.DATASOURCE_RENDERTARGET:
  25538. var options = new BABYLON.RenderTargetCreationOptions();
  25539. options.generateDepthBuffer = this._generateDepthBuffer;
  25540. options.generateMipMaps = this.generateMipMaps;
  25541. options.generateStencilBuffer = this._generateStencilBuffer;
  25542. options.samplingMode = this.samplingMode;
  25543. options.type = this.type;
  25544. if (this.isCube) {
  25545. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  25546. }
  25547. else {
  25548. var size = {
  25549. width: this.width,
  25550. height: this.height
  25551. };
  25552. proxy = this._engine.createRenderTargetTexture(size, options);
  25553. }
  25554. proxy._swapAndDie(this);
  25555. this.isReady = true;
  25556. return;
  25557. case InternalTexture.DATASOURCE_CUBE:
  25558. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  25559. _this.isReady = true;
  25560. }, null, this.format, this._extension);
  25561. proxy._swapAndDie(this);
  25562. return;
  25563. case InternalTexture.DATASOURCE_CUBERAW:
  25564. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  25565. proxy._swapAndDie(this);
  25566. this.isReady = true;
  25567. return;
  25568. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  25569. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  25570. if (proxy) {
  25571. proxy._swapAndDie(_this);
  25572. }
  25573. _this.isReady = true;
  25574. }, null, this.format, this._extension);
  25575. return;
  25576. }
  25577. };
  25578. InternalTexture.prototype._swapAndDie = function (target) {
  25579. target._webGLTexture = this._webGLTexture;
  25580. if (this._framebuffer) {
  25581. target._framebuffer = this._framebuffer;
  25582. }
  25583. if (this._depthStencilBuffer) {
  25584. target._depthStencilBuffer = this._depthStencilBuffer;
  25585. }
  25586. if (this._lodTextureHigh) {
  25587. if (target._lodTextureHigh) {
  25588. target._lodTextureHigh.dispose();
  25589. }
  25590. target._lodTextureHigh = this._lodTextureHigh;
  25591. }
  25592. if (this._lodTextureMid) {
  25593. if (target._lodTextureMid) {
  25594. target._lodTextureMid.dispose();
  25595. }
  25596. target._lodTextureMid = this._lodTextureMid;
  25597. }
  25598. if (this._lodTextureLow) {
  25599. if (target._lodTextureLow) {
  25600. target._lodTextureLow.dispose();
  25601. }
  25602. target._lodTextureLow = this._lodTextureLow;
  25603. }
  25604. var cache = this._engine.getLoadedTexturesCache();
  25605. var index = cache.indexOf(this);
  25606. if (index !== -1) {
  25607. cache.splice(index, 1);
  25608. }
  25609. };
  25610. /**
  25611. * Dispose the current allocated resources
  25612. */
  25613. InternalTexture.prototype.dispose = function () {
  25614. if (!this._webGLTexture) {
  25615. return;
  25616. }
  25617. this._references--;
  25618. if (this._references === 0) {
  25619. this._engine._releaseTexture(this);
  25620. this._webGLTexture = null;
  25621. this.previous = null;
  25622. this.next = null;
  25623. }
  25624. };
  25625. /**
  25626. * The source of the texture data is unknown
  25627. */
  25628. InternalTexture.DATASOURCE_UNKNOWN = 0;
  25629. /**
  25630. * Texture data comes from an URL
  25631. */
  25632. InternalTexture.DATASOURCE_URL = 1;
  25633. /**
  25634. * Texture data is only used for temporary storage
  25635. */
  25636. InternalTexture.DATASOURCE_TEMP = 2;
  25637. /**
  25638. * Texture data comes from raw data (ArrayBuffer)
  25639. */
  25640. InternalTexture.DATASOURCE_RAW = 3;
  25641. /**
  25642. * Texture content is dynamic (video or dynamic texture)
  25643. */
  25644. InternalTexture.DATASOURCE_DYNAMIC = 4;
  25645. /**
  25646. * Texture content is generated by rendering to it
  25647. */
  25648. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  25649. /**
  25650. * Texture content is part of a multi render target process
  25651. */
  25652. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  25653. /**
  25654. * Texture data comes from a cube data file
  25655. */
  25656. InternalTexture.DATASOURCE_CUBE = 7;
  25657. /**
  25658. * Texture data comes from a raw cube data
  25659. */
  25660. InternalTexture.DATASOURCE_CUBERAW = 8;
  25661. /**
  25662. * Texture data come from a prefiltered cube data file
  25663. */
  25664. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  25665. /**
  25666. * Texture content is raw 3D data
  25667. */
  25668. InternalTexture.DATASOURCE_RAW3D = 10;
  25669. return InternalTexture;
  25670. }());
  25671. BABYLON.InternalTexture = InternalTexture;
  25672. })(BABYLON || (BABYLON = {}));
  25673. //# sourceMappingURL=babylon.internalTexture.js.map
  25674. var BABYLON;
  25675. (function (BABYLON) {
  25676. var BaseTexture = /** @class */ (function () {
  25677. function BaseTexture(scene) {
  25678. this._hasAlpha = false;
  25679. this.getAlphaFromRGB = false;
  25680. this.level = 1;
  25681. this.coordinatesIndex = 0;
  25682. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  25683. /*
  25684. * How a texture is mapped.
  25685. *
  25686. * | Value | Type | Description |
  25687. * | ----- | ----------------------------------- | ----------- |
  25688. * | 0 | EXPLICIT_MODE | |
  25689. * | 1 | SPHERICAL_MODE | |
  25690. * | 2 | PLANAR_MODE | |
  25691. * | 3 | CUBIC_MODE | |
  25692. * | 4 | PROJECTION_MODE | |
  25693. * | 5 | SKYBOX_MODE | |
  25694. * | 6 | INVCUBIC_MODE | |
  25695. * | 7 | EQUIRECTANGULAR_MODE | |
  25696. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  25697. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  25698. */
  25699. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  25700. /*
  25701. * | Value | Type | Description |
  25702. * | ----- | ------------------ | ----------- |
  25703. * | 0 | CLAMP_ADDRESSMODE | |
  25704. * | 1 | WRAP_ADDRESSMODE | |
  25705. * | 2 | MIRROR_ADDRESSMODE | |
  25706. */
  25707. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  25708. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  25709. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  25710. this.isCube = false;
  25711. this.is3D = false;
  25712. this.gammaSpace = true;
  25713. this.invertZ = false;
  25714. this.lodLevelInAlpha = false;
  25715. this.lodGenerationOffset = 0.0;
  25716. this.lodGenerationScale = 0.8;
  25717. this.isRenderTarget = false;
  25718. this.animations = new Array();
  25719. /**
  25720. * An event triggered when the texture is disposed.
  25721. * @type {BABYLON.Observable}
  25722. */
  25723. this.onDisposeObservable = new BABYLON.Observable();
  25724. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  25725. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  25726. if (this._scene) {
  25727. this._scene.textures.push(this);
  25728. }
  25729. this._uid = null;
  25730. }
  25731. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  25732. get: function () {
  25733. return this._hasAlpha;
  25734. },
  25735. set: function (value) {
  25736. if (this._hasAlpha === value) {
  25737. return;
  25738. }
  25739. this._hasAlpha = value;
  25740. if (this._scene) {
  25741. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  25742. }
  25743. },
  25744. enumerable: true,
  25745. configurable: true
  25746. });
  25747. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  25748. get: function () {
  25749. return this._coordinatesMode;
  25750. },
  25751. set: function (value) {
  25752. if (this._coordinatesMode === value) {
  25753. return;
  25754. }
  25755. this._coordinatesMode = value;
  25756. if (this._scene) {
  25757. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  25758. }
  25759. },
  25760. enumerable: true,
  25761. configurable: true
  25762. });
  25763. Object.defineProperty(BaseTexture.prototype, "uid", {
  25764. get: function () {
  25765. if (!this._uid) {
  25766. this._uid = BABYLON.Tools.RandomId();
  25767. }
  25768. return this._uid;
  25769. },
  25770. enumerable: true,
  25771. configurable: true
  25772. });
  25773. BaseTexture.prototype.toString = function () {
  25774. return this.name;
  25775. };
  25776. BaseTexture.prototype.getClassName = function () {
  25777. return "BaseTexture";
  25778. };
  25779. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  25780. set: function (callback) {
  25781. if (this._onDisposeObserver) {
  25782. this.onDisposeObservable.remove(this._onDisposeObserver);
  25783. }
  25784. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  25785. },
  25786. enumerable: true,
  25787. configurable: true
  25788. });
  25789. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  25790. get: function () {
  25791. return true;
  25792. },
  25793. enumerable: true,
  25794. configurable: true
  25795. });
  25796. BaseTexture.prototype.getScene = function () {
  25797. return this._scene;
  25798. };
  25799. BaseTexture.prototype.getTextureMatrix = function () {
  25800. return BABYLON.Matrix.IdentityReadOnly;
  25801. };
  25802. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  25803. return BABYLON.Matrix.IdentityReadOnly;
  25804. };
  25805. BaseTexture.prototype.getInternalTexture = function () {
  25806. return this._texture;
  25807. };
  25808. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  25809. return !this.isBlocking || this.isReady();
  25810. };
  25811. BaseTexture.prototype.isReady = function () {
  25812. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  25813. this.delayLoad();
  25814. return false;
  25815. }
  25816. if (this._texture) {
  25817. return this._texture.isReady;
  25818. }
  25819. return false;
  25820. };
  25821. BaseTexture.prototype.getSize = function () {
  25822. if (this._texture && this._texture.width) {
  25823. return new BABYLON.Size(this._texture.width, this._texture.height);
  25824. }
  25825. if (this._texture && this._texture._size) {
  25826. return new BABYLON.Size(this._texture._size, this._texture._size);
  25827. }
  25828. return BABYLON.Size.Zero();
  25829. };
  25830. BaseTexture.prototype.getBaseSize = function () {
  25831. if (!this.isReady() || !this._texture)
  25832. return BABYLON.Size.Zero();
  25833. if (this._texture._size) {
  25834. return new BABYLON.Size(this._texture._size, this._texture._size);
  25835. }
  25836. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  25837. };
  25838. BaseTexture.prototype.scale = function (ratio) {
  25839. };
  25840. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  25841. get: function () {
  25842. return false;
  25843. },
  25844. enumerable: true,
  25845. configurable: true
  25846. });
  25847. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  25848. if (!this._scene) {
  25849. return null;
  25850. }
  25851. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  25852. for (var index = 0; index < texturesCache.length; index++) {
  25853. var texturesCacheEntry = texturesCache[index];
  25854. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  25855. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  25856. texturesCacheEntry.incrementReferences();
  25857. return texturesCacheEntry;
  25858. }
  25859. }
  25860. }
  25861. return null;
  25862. };
  25863. BaseTexture.prototype._rebuild = function () {
  25864. };
  25865. BaseTexture.prototype.delayLoad = function () {
  25866. };
  25867. BaseTexture.prototype.clone = function () {
  25868. return null;
  25869. };
  25870. Object.defineProperty(BaseTexture.prototype, "textureType", {
  25871. get: function () {
  25872. if (!this._texture) {
  25873. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  25874. }
  25875. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  25876. },
  25877. enumerable: true,
  25878. configurable: true
  25879. });
  25880. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  25881. get: function () {
  25882. if (!this._texture) {
  25883. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  25884. }
  25885. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  25886. },
  25887. enumerable: true,
  25888. configurable: true
  25889. });
  25890. BaseTexture.prototype.readPixels = function (faceIndex) {
  25891. if (faceIndex === void 0) { faceIndex = 0; }
  25892. if (!this._texture) {
  25893. return null;
  25894. }
  25895. var size = this.getSize();
  25896. var scene = this.getScene();
  25897. if (!scene) {
  25898. return null;
  25899. }
  25900. var engine = scene.getEngine();
  25901. if (this._texture.isCube) {
  25902. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  25903. }
  25904. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  25905. };
  25906. BaseTexture.prototype.releaseInternalTexture = function () {
  25907. if (this._texture) {
  25908. this._texture.dispose();
  25909. this._texture = null;
  25910. }
  25911. };
  25912. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  25913. get: function () {
  25914. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  25915. return null;
  25916. }
  25917. if (!this._texture._sphericalPolynomial) {
  25918. this._texture._sphericalPolynomial =
  25919. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  25920. }
  25921. return this._texture._sphericalPolynomial;
  25922. },
  25923. set: function (value) {
  25924. if (this._texture) {
  25925. this._texture._sphericalPolynomial = value;
  25926. }
  25927. },
  25928. enumerable: true,
  25929. configurable: true
  25930. });
  25931. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  25932. get: function () {
  25933. if (this._texture) {
  25934. return this._texture._lodTextureHigh;
  25935. }
  25936. return null;
  25937. },
  25938. enumerable: true,
  25939. configurable: true
  25940. });
  25941. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  25942. get: function () {
  25943. if (this._texture) {
  25944. return this._texture._lodTextureMid;
  25945. }
  25946. return null;
  25947. },
  25948. enumerable: true,
  25949. configurable: true
  25950. });
  25951. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  25952. get: function () {
  25953. if (this._texture) {
  25954. return this._texture._lodTextureLow;
  25955. }
  25956. return null;
  25957. },
  25958. enumerable: true,
  25959. configurable: true
  25960. });
  25961. BaseTexture.prototype.dispose = function () {
  25962. if (!this._scene) {
  25963. return;
  25964. }
  25965. // Animations
  25966. this._scene.stopAnimation(this);
  25967. // Remove from scene
  25968. this._scene._removePendingData(this);
  25969. var index = this._scene.textures.indexOf(this);
  25970. if (index >= 0) {
  25971. this._scene.textures.splice(index, 1);
  25972. }
  25973. if (this._texture === undefined) {
  25974. return;
  25975. }
  25976. // Release
  25977. this.releaseInternalTexture();
  25978. // Callback
  25979. this.onDisposeObservable.notifyObservers(this);
  25980. this.onDisposeObservable.clear();
  25981. };
  25982. BaseTexture.prototype.serialize = function () {
  25983. if (!this.name) {
  25984. return null;
  25985. }
  25986. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  25987. // Animations
  25988. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  25989. return serializationObject;
  25990. };
  25991. BaseTexture.WhenAllReady = function (textures, callback) {
  25992. var numRemaining = textures.length;
  25993. if (numRemaining === 0) {
  25994. callback();
  25995. return;
  25996. }
  25997. var _loop_1 = function () {
  25998. texture = textures[i];
  25999. if (texture.isReady()) {
  26000. if (--numRemaining === 0) {
  26001. callback();
  26002. }
  26003. }
  26004. else {
  26005. onLoadObservable = texture.onLoadObservable;
  26006. var onLoadCallback_1 = function () {
  26007. onLoadObservable.removeCallback(onLoadCallback_1);
  26008. if (--numRemaining === 0) {
  26009. callback();
  26010. }
  26011. };
  26012. onLoadObservable.add(onLoadCallback_1);
  26013. }
  26014. };
  26015. var texture, onLoadObservable;
  26016. for (var i = 0; i < textures.length; i++) {
  26017. _loop_1();
  26018. }
  26019. };
  26020. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  26021. __decorate([
  26022. BABYLON.serialize()
  26023. ], BaseTexture.prototype, "name", void 0);
  26024. __decorate([
  26025. BABYLON.serialize("hasAlpha")
  26026. ], BaseTexture.prototype, "_hasAlpha", void 0);
  26027. __decorate([
  26028. BABYLON.serialize()
  26029. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  26030. __decorate([
  26031. BABYLON.serialize()
  26032. ], BaseTexture.prototype, "level", void 0);
  26033. __decorate([
  26034. BABYLON.serialize()
  26035. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  26036. __decorate([
  26037. BABYLON.serialize("coordinatesMode")
  26038. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  26039. __decorate([
  26040. BABYLON.serialize()
  26041. ], BaseTexture.prototype, "wrapU", void 0);
  26042. __decorate([
  26043. BABYLON.serialize()
  26044. ], BaseTexture.prototype, "wrapV", void 0);
  26045. __decorate([
  26046. BABYLON.serialize()
  26047. ], BaseTexture.prototype, "wrapR", void 0);
  26048. __decorate([
  26049. BABYLON.serialize()
  26050. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  26051. __decorate([
  26052. BABYLON.serialize()
  26053. ], BaseTexture.prototype, "isCube", void 0);
  26054. __decorate([
  26055. BABYLON.serialize()
  26056. ], BaseTexture.prototype, "is3D", void 0);
  26057. __decorate([
  26058. BABYLON.serialize()
  26059. ], BaseTexture.prototype, "gammaSpace", void 0);
  26060. __decorate([
  26061. BABYLON.serialize()
  26062. ], BaseTexture.prototype, "invertZ", void 0);
  26063. __decorate([
  26064. BABYLON.serialize()
  26065. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  26066. __decorate([
  26067. BABYLON.serialize()
  26068. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  26069. __decorate([
  26070. BABYLON.serialize()
  26071. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  26072. __decorate([
  26073. BABYLON.serialize()
  26074. ], BaseTexture.prototype, "isRenderTarget", void 0);
  26075. return BaseTexture;
  26076. }());
  26077. BABYLON.BaseTexture = BaseTexture;
  26078. })(BABYLON || (BABYLON = {}));
  26079. //# sourceMappingURL=babylon.baseTexture.js.map
  26080. var BABYLON;
  26081. (function (BABYLON) {
  26082. var Texture = /** @class */ (function (_super) {
  26083. __extends(Texture, _super);
  26084. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  26085. if (noMipmap === void 0) { noMipmap = false; }
  26086. if (invertY === void 0) { invertY = true; }
  26087. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  26088. if (onLoad === void 0) { onLoad = null; }
  26089. if (onError === void 0) { onError = null; }
  26090. if (buffer === void 0) { buffer = null; }
  26091. if (deleteBuffer === void 0) { deleteBuffer = false; }
  26092. var _this = _super.call(this, scene) || this;
  26093. _this.uOffset = 0;
  26094. _this.vOffset = 0;
  26095. _this.uScale = 1.0;
  26096. _this.vScale = 1.0;
  26097. _this.uAng = 0;
  26098. _this.vAng = 0;
  26099. _this.wAng = 0;
  26100. _this._isBlocking = true;
  26101. _this.name = url || "";
  26102. _this.url = url;
  26103. _this._noMipmap = noMipmap;
  26104. _this._invertY = invertY;
  26105. _this._samplingMode = samplingMode;
  26106. _this._buffer = buffer;
  26107. _this._deleteBuffer = deleteBuffer;
  26108. if (format) {
  26109. _this._format = format;
  26110. }
  26111. scene = _this.getScene();
  26112. if (!scene) {
  26113. return _this;
  26114. }
  26115. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  26116. var load = function () {
  26117. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  26118. _this.onLoadObservable.notifyObservers(_this);
  26119. }
  26120. if (onLoad) {
  26121. onLoad();
  26122. }
  26123. if (!_this.isBlocking && scene) {
  26124. scene.resetCachedMaterial();
  26125. }
  26126. };
  26127. if (!_this.url) {
  26128. _this._delayedOnLoad = load;
  26129. _this._delayedOnError = onError;
  26130. return _this;
  26131. }
  26132. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  26133. if (!_this._texture) {
  26134. if (!scene.useDelayedTextureLoading) {
  26135. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  26136. if (deleteBuffer) {
  26137. delete _this._buffer;
  26138. }
  26139. }
  26140. else {
  26141. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  26142. _this._delayedOnLoad = load;
  26143. _this._delayedOnError = onError;
  26144. }
  26145. }
  26146. else {
  26147. if (_this._texture.isReady) {
  26148. BABYLON.Tools.SetImmediate(function () { return load(); });
  26149. }
  26150. else {
  26151. _this._texture.onLoadedObservable.add(load);
  26152. }
  26153. }
  26154. return _this;
  26155. }
  26156. Object.defineProperty(Texture.prototype, "noMipmap", {
  26157. get: function () {
  26158. return this._noMipmap;
  26159. },
  26160. enumerable: true,
  26161. configurable: true
  26162. });
  26163. Object.defineProperty(Texture.prototype, "isBlocking", {
  26164. get: function () {
  26165. return this._isBlocking;
  26166. },
  26167. set: function (value) {
  26168. this._isBlocking = value;
  26169. },
  26170. enumerable: true,
  26171. configurable: true
  26172. });
  26173. Object.defineProperty(Texture.prototype, "samplingMode", {
  26174. get: function () {
  26175. return this._samplingMode;
  26176. },
  26177. enumerable: true,
  26178. configurable: true
  26179. });
  26180. Texture.prototype.updateURL = function (url) {
  26181. this.url = url;
  26182. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  26183. this.delayLoad();
  26184. };
  26185. Texture.prototype.delayLoad = function () {
  26186. var _this = this;
  26187. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  26188. return;
  26189. }
  26190. var scene = this.getScene();
  26191. if (!scene) {
  26192. return;
  26193. }
  26194. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  26195. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  26196. if (!this._texture) {
  26197. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  26198. if (this._deleteBuffer) {
  26199. delete this._buffer;
  26200. }
  26201. }
  26202. else {
  26203. if (this._texture.isReady) {
  26204. BABYLON.Tools.SetImmediate(function () {
  26205. if (!_this._delayedOnLoad) {
  26206. return;
  26207. }
  26208. _this._delayedOnLoad();
  26209. });
  26210. }
  26211. else {
  26212. if (this._delayedOnLoad) {
  26213. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  26214. }
  26215. }
  26216. }
  26217. };
  26218. Texture.prototype.updateSamplingMode = function (samplingMode) {
  26219. if (!this._texture) {
  26220. return;
  26221. }
  26222. var scene = this.getScene();
  26223. if (!scene) {
  26224. return;
  26225. }
  26226. this._samplingMode = samplingMode;
  26227. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  26228. };
  26229. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  26230. x *= this.uScale;
  26231. y *= this.vScale;
  26232. x -= 0.5 * this.uScale;
  26233. y -= 0.5 * this.vScale;
  26234. z -= 0.5;
  26235. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  26236. t.x += 0.5 * this.uScale + this.uOffset;
  26237. t.y += 0.5 * this.vScale + this.vOffset;
  26238. t.z += 0.5;
  26239. };
  26240. Texture.prototype.getTextureMatrix = function () {
  26241. var _this = this;
  26242. if (this.uOffset === this._cachedUOffset &&
  26243. this.vOffset === this._cachedVOffset &&
  26244. this.uScale === this._cachedUScale &&
  26245. this.vScale === this._cachedVScale &&
  26246. this.uAng === this._cachedUAng &&
  26247. this.vAng === this._cachedVAng &&
  26248. this.wAng === this._cachedWAng) {
  26249. return this._cachedTextureMatrix;
  26250. }
  26251. this._cachedUOffset = this.uOffset;
  26252. this._cachedVOffset = this.vOffset;
  26253. this._cachedUScale = this.uScale;
  26254. this._cachedVScale = this.vScale;
  26255. this._cachedUAng = this.uAng;
  26256. this._cachedVAng = this.vAng;
  26257. this._cachedWAng = this.wAng;
  26258. if (!this._cachedTextureMatrix) {
  26259. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  26260. this._rowGenerationMatrix = new BABYLON.Matrix();
  26261. this._t0 = BABYLON.Vector3.Zero();
  26262. this._t1 = BABYLON.Vector3.Zero();
  26263. this._t2 = BABYLON.Vector3.Zero();
  26264. }
  26265. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  26266. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  26267. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  26268. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  26269. this._t1.subtractInPlace(this._t0);
  26270. this._t2.subtractInPlace(this._t0);
  26271. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  26272. this._cachedTextureMatrix.m[0] = this._t1.x;
  26273. this._cachedTextureMatrix.m[1] = this._t1.y;
  26274. this._cachedTextureMatrix.m[2] = this._t1.z;
  26275. this._cachedTextureMatrix.m[4] = this._t2.x;
  26276. this._cachedTextureMatrix.m[5] = this._t2.y;
  26277. this._cachedTextureMatrix.m[6] = this._t2.z;
  26278. this._cachedTextureMatrix.m[8] = this._t0.x;
  26279. this._cachedTextureMatrix.m[9] = this._t0.y;
  26280. this._cachedTextureMatrix.m[10] = this._t0.z;
  26281. var scene = this.getScene();
  26282. if (!scene) {
  26283. return this._cachedTextureMatrix;
  26284. }
  26285. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  26286. return mat.hasTexture(_this);
  26287. });
  26288. return this._cachedTextureMatrix;
  26289. };
  26290. Texture.prototype.getReflectionTextureMatrix = function () {
  26291. var _this = this;
  26292. var scene = this.getScene();
  26293. if (!scene) {
  26294. return this._cachedTextureMatrix;
  26295. }
  26296. if (this.uOffset === this._cachedUOffset &&
  26297. this.vOffset === this._cachedVOffset &&
  26298. this.uScale === this._cachedUScale &&
  26299. this.vScale === this._cachedVScale &&
  26300. this.coordinatesMode === this._cachedCoordinatesMode) {
  26301. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  26302. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  26303. return this._cachedTextureMatrix;
  26304. }
  26305. }
  26306. else {
  26307. return this._cachedTextureMatrix;
  26308. }
  26309. }
  26310. if (!this._cachedTextureMatrix) {
  26311. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  26312. }
  26313. if (!this._projectionModeMatrix) {
  26314. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  26315. }
  26316. this._cachedUOffset = this.uOffset;
  26317. this._cachedVOffset = this.vOffset;
  26318. this._cachedUScale = this.uScale;
  26319. this._cachedVScale = this.vScale;
  26320. this._cachedCoordinatesMode = this.coordinatesMode;
  26321. switch (this.coordinatesMode) {
  26322. case Texture.PLANAR_MODE:
  26323. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  26324. this._cachedTextureMatrix[0] = this.uScale;
  26325. this._cachedTextureMatrix[5] = this.vScale;
  26326. this._cachedTextureMatrix[12] = this.uOffset;
  26327. this._cachedTextureMatrix[13] = this.vOffset;
  26328. break;
  26329. case Texture.PROJECTION_MODE:
  26330. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  26331. this._projectionModeMatrix.m[0] = 0.5;
  26332. this._projectionModeMatrix.m[5] = -0.5;
  26333. this._projectionModeMatrix.m[10] = 0.0;
  26334. this._projectionModeMatrix.m[12] = 0.5;
  26335. this._projectionModeMatrix.m[13] = 0.5;
  26336. this._projectionModeMatrix.m[14] = 1.0;
  26337. this._projectionModeMatrix.m[15] = 1.0;
  26338. var projectionMatrix = scene.getProjectionMatrix();
  26339. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  26340. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  26341. break;
  26342. default:
  26343. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  26344. break;
  26345. }
  26346. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  26347. return (mat.getActiveTextures().indexOf(_this) !== -1);
  26348. });
  26349. return this._cachedTextureMatrix;
  26350. };
  26351. Texture.prototype.clone = function () {
  26352. var _this = this;
  26353. return BABYLON.SerializationHelper.Clone(function () {
  26354. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  26355. }, this);
  26356. };
  26357. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  26358. get: function () {
  26359. if (!this._onLoadObservable) {
  26360. this._onLoadObservable = new BABYLON.Observable();
  26361. }
  26362. return this._onLoadObservable;
  26363. },
  26364. enumerable: true,
  26365. configurable: true
  26366. });
  26367. Texture.prototype.serialize = function () {
  26368. var serializationObject = _super.prototype.serialize.call(this);
  26369. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  26370. serializationObject.base64String = this._buffer;
  26371. serializationObject.name = serializationObject.name.replace("data:", "");
  26372. }
  26373. return serializationObject;
  26374. };
  26375. Texture.prototype.getClassName = function () {
  26376. return "Texture";
  26377. };
  26378. Texture.prototype.dispose = function () {
  26379. _super.prototype.dispose.call(this);
  26380. if (this.onLoadObservable) {
  26381. this.onLoadObservable.clear();
  26382. this._onLoadObservable = null;
  26383. }
  26384. this._delayedOnLoad = null;
  26385. this._delayedOnError = null;
  26386. };
  26387. // Statics
  26388. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  26389. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  26390. if (onLoad === void 0) { onLoad = null; }
  26391. if (onError === void 0) { onError = null; }
  26392. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  26393. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  26394. };
  26395. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  26396. if (parsedTexture.customType) {
  26397. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  26398. // Update Sampling Mode
  26399. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  26400. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  26401. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  26402. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  26403. }
  26404. }
  26405. return parsedCustomTexture;
  26406. }
  26407. if (parsedTexture.isCube) {
  26408. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  26409. }
  26410. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  26411. return null;
  26412. }
  26413. var texture = BABYLON.SerializationHelper.Parse(function () {
  26414. var generateMipMaps = true;
  26415. if (parsedTexture.noMipmap) {
  26416. generateMipMaps = false;
  26417. }
  26418. if (parsedTexture.mirrorPlane) {
  26419. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  26420. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  26421. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  26422. return mirrorTexture;
  26423. }
  26424. else if (parsedTexture.isRenderTarget) {
  26425. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  26426. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  26427. return renderTargetTexture;
  26428. }
  26429. else {
  26430. var texture;
  26431. if (parsedTexture.base64String) {
  26432. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  26433. }
  26434. else {
  26435. texture = new Texture(rootUrl + parsedTexture.name, scene, !generateMipMaps);
  26436. }
  26437. return texture;
  26438. }
  26439. }, parsedTexture, scene);
  26440. // Update Sampling Mode
  26441. if (parsedTexture.samplingMode) {
  26442. var sampling = parsedTexture.samplingMode;
  26443. if (texture._samplingMode !== sampling) {
  26444. texture.updateSamplingMode(sampling);
  26445. }
  26446. }
  26447. // Animations
  26448. if (parsedTexture.animations) {
  26449. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  26450. var parsedAnimation = parsedTexture.animations[animationIndex];
  26451. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  26452. }
  26453. }
  26454. return texture;
  26455. };
  26456. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  26457. if (deleteBuffer === void 0) { deleteBuffer = false; }
  26458. if (noMipmap === void 0) { noMipmap = false; }
  26459. if (invertY === void 0) { invertY = true; }
  26460. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  26461. if (onLoad === void 0) { onLoad = null; }
  26462. if (onError === void 0) { onError = null; }
  26463. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  26464. if (name.substr(0, 5) !== "data:") {
  26465. name = "data:" + name;
  26466. }
  26467. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  26468. };
  26469. // Constants
  26470. Texture.NEAREST_SAMPLINGMODE = 1;
  26471. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  26472. Texture.BILINEAR_SAMPLINGMODE = 2;
  26473. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  26474. Texture.TRILINEAR_SAMPLINGMODE = 3;
  26475. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  26476. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  26477. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  26478. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  26479. Texture.NEAREST_LINEAR = 7;
  26480. Texture.NEAREST_NEAREST = 8;
  26481. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  26482. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  26483. Texture.LINEAR_LINEAR = 11;
  26484. Texture.LINEAR_NEAREST = 12;
  26485. Texture.EXPLICIT_MODE = 0;
  26486. Texture.SPHERICAL_MODE = 1;
  26487. Texture.PLANAR_MODE = 2;
  26488. Texture.CUBIC_MODE = 3;
  26489. Texture.PROJECTION_MODE = 4;
  26490. Texture.SKYBOX_MODE = 5;
  26491. Texture.INVCUBIC_MODE = 6;
  26492. Texture.EQUIRECTANGULAR_MODE = 7;
  26493. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  26494. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  26495. Texture.CLAMP_ADDRESSMODE = 0;
  26496. Texture.WRAP_ADDRESSMODE = 1;
  26497. Texture.MIRROR_ADDRESSMODE = 2;
  26498. __decorate([
  26499. BABYLON.serialize()
  26500. ], Texture.prototype, "url", void 0);
  26501. __decorate([
  26502. BABYLON.serialize()
  26503. ], Texture.prototype, "uOffset", void 0);
  26504. __decorate([
  26505. BABYLON.serialize()
  26506. ], Texture.prototype, "vOffset", void 0);
  26507. __decorate([
  26508. BABYLON.serialize()
  26509. ], Texture.prototype, "uScale", void 0);
  26510. __decorate([
  26511. BABYLON.serialize()
  26512. ], Texture.prototype, "vScale", void 0);
  26513. __decorate([
  26514. BABYLON.serialize()
  26515. ], Texture.prototype, "uAng", void 0);
  26516. __decorate([
  26517. BABYLON.serialize()
  26518. ], Texture.prototype, "vAng", void 0);
  26519. __decorate([
  26520. BABYLON.serialize()
  26521. ], Texture.prototype, "wAng", void 0);
  26522. __decorate([
  26523. BABYLON.serialize()
  26524. ], Texture.prototype, "isBlocking", null);
  26525. return Texture;
  26526. }(BABYLON.BaseTexture));
  26527. BABYLON.Texture = Texture;
  26528. })(BABYLON || (BABYLON = {}));
  26529. //# sourceMappingURL=babylon.texture.js.map
  26530. var BABYLON;
  26531. (function (BABYLON) {
  26532. var _InstancesBatch = /** @class */ (function () {
  26533. function _InstancesBatch() {
  26534. this.mustReturn = false;
  26535. this.visibleInstances = new Array();
  26536. this.renderSelf = new Array();
  26537. }
  26538. return _InstancesBatch;
  26539. }());
  26540. BABYLON._InstancesBatch = _InstancesBatch;
  26541. var Mesh = /** @class */ (function (_super) {
  26542. __extends(Mesh, _super);
  26543. /**
  26544. * @constructor
  26545. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  26546. * @param {Scene} scene The scene to add this mesh to.
  26547. * @param {Node} parent The parent of this mesh, if it has one
  26548. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  26549. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  26550. * When false, achieved by calling a clone(), also passing False.
  26551. * This will make creation of children, recursive.
  26552. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  26553. */
  26554. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  26555. if (scene === void 0) { scene = null; }
  26556. if (parent === void 0) { parent = null; }
  26557. if (source === void 0) { source = null; }
  26558. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  26559. var _this = _super.call(this, name, scene) || this;
  26560. // Events
  26561. /**
  26562. * An event triggered before rendering the mesh
  26563. * @type {BABYLON.Observable}
  26564. */
  26565. _this.onBeforeRenderObservable = new BABYLON.Observable();
  26566. /**
  26567. * An event triggered after rendering the mesh
  26568. * @type {BABYLON.Observable}
  26569. */
  26570. _this.onAfterRenderObservable = new BABYLON.Observable();
  26571. /**
  26572. * An event triggered before drawing the mesh
  26573. * @type {BABYLON.Observable}
  26574. */
  26575. _this.onBeforeDrawObservable = new BABYLON.Observable();
  26576. // Members
  26577. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  26578. _this.instances = new Array();
  26579. _this._LODLevels = new Array();
  26580. _this._visibleInstances = {};
  26581. _this._renderIdForInstances = new Array();
  26582. _this._batchCache = new _InstancesBatch();
  26583. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  26584. // Use by builder only to know what orientation were the mesh build in.
  26585. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  26586. _this.overrideMaterialSideOrientation = null;
  26587. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  26588. // Will be used to save a source mesh reference, If any
  26589. _this._source = null;
  26590. scene = _this.getScene();
  26591. if (source) {
  26592. // Source mesh
  26593. _this._source = source;
  26594. // Geometry
  26595. if (source._geometry) {
  26596. source._geometry.applyToMesh(_this);
  26597. }
  26598. // Deep copy
  26599. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId", "source", "metadata"], ["_poseMatrix", "_source"]);
  26600. // Metadata
  26601. if (source.metadata && source.metadata.clone) {
  26602. _this.metadata = source.metadata.clone();
  26603. }
  26604. else {
  26605. _this.metadata = source.metadata;
  26606. }
  26607. // Tags
  26608. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  26609. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  26610. }
  26611. // Parent
  26612. _this.parent = source.parent;
  26613. // Pivot
  26614. _this.setPivotMatrix(source.getPivotMatrix());
  26615. _this.id = name + "." + source.id;
  26616. // Material
  26617. _this.material = source.material;
  26618. var index;
  26619. if (!doNotCloneChildren) {
  26620. // Children
  26621. var directDescendants = source.getDescendants(true);
  26622. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  26623. var child = directDescendants[index_1];
  26624. if (child.clone) {
  26625. child.clone(name + "." + child.name, _this);
  26626. }
  26627. }
  26628. }
  26629. // Physics clone
  26630. var physicsEngine = _this.getScene().getPhysicsEngine();
  26631. if (clonePhysicsImpostor && physicsEngine) {
  26632. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  26633. if (impostor) {
  26634. _this.physicsImpostor = impostor.clone(_this);
  26635. }
  26636. }
  26637. // Particles
  26638. for (index = 0; index < scene.particleSystems.length; index++) {
  26639. var system = scene.particleSystems[index];
  26640. if (system.emitter === source) {
  26641. system.clone(system.name, _this);
  26642. }
  26643. }
  26644. _this.computeWorldMatrix(true);
  26645. }
  26646. // Parent
  26647. if (parent !== null) {
  26648. _this.parent = parent;
  26649. }
  26650. return _this;
  26651. }
  26652. Object.defineProperty(Mesh, "FRONTSIDE", {
  26653. /**
  26654. * Mesh side orientation : usually the external or front surface
  26655. */
  26656. get: function () {
  26657. return Mesh._FRONTSIDE;
  26658. },
  26659. enumerable: true,
  26660. configurable: true
  26661. });
  26662. Object.defineProperty(Mesh, "BACKSIDE", {
  26663. /**
  26664. * Mesh side orientation : usually the internal or back surface
  26665. */
  26666. get: function () {
  26667. return Mesh._BACKSIDE;
  26668. },
  26669. enumerable: true,
  26670. configurable: true
  26671. });
  26672. Object.defineProperty(Mesh, "DOUBLESIDE", {
  26673. /**
  26674. * Mesh side orientation : both internal and external or front and back surfaces
  26675. */
  26676. get: function () {
  26677. return Mesh._DOUBLESIDE;
  26678. },
  26679. enumerable: true,
  26680. configurable: true
  26681. });
  26682. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  26683. /**
  26684. * Mesh side orientation : by default, `FRONTSIDE`
  26685. */
  26686. get: function () {
  26687. return Mesh._DEFAULTSIDE;
  26688. },
  26689. enumerable: true,
  26690. configurable: true
  26691. });
  26692. Object.defineProperty(Mesh, "NO_CAP", {
  26693. /**
  26694. * Mesh cap setting : no cap
  26695. */
  26696. get: function () {
  26697. return Mesh._NO_CAP;
  26698. },
  26699. enumerable: true,
  26700. configurable: true
  26701. });
  26702. Object.defineProperty(Mesh, "CAP_START", {
  26703. /**
  26704. * Mesh cap setting : one cap at the beginning of the mesh
  26705. */
  26706. get: function () {
  26707. return Mesh._CAP_START;
  26708. },
  26709. enumerable: true,
  26710. configurable: true
  26711. });
  26712. Object.defineProperty(Mesh, "CAP_END", {
  26713. /**
  26714. * Mesh cap setting : one cap at the end of the mesh
  26715. */
  26716. get: function () {
  26717. return Mesh._CAP_END;
  26718. },
  26719. enumerable: true,
  26720. configurable: true
  26721. });
  26722. Object.defineProperty(Mesh, "CAP_ALL", {
  26723. /**
  26724. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  26725. */
  26726. get: function () {
  26727. return Mesh._CAP_ALL;
  26728. },
  26729. enumerable: true,
  26730. configurable: true
  26731. });
  26732. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  26733. set: function (callback) {
  26734. if (this._onBeforeDrawObserver) {
  26735. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  26736. }
  26737. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  26738. },
  26739. enumerable: true,
  26740. configurable: true
  26741. });
  26742. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  26743. get: function () {
  26744. return this._morphTargetManager;
  26745. },
  26746. set: function (value) {
  26747. if (this._morphTargetManager === value) {
  26748. return;
  26749. }
  26750. this._morphTargetManager = value;
  26751. this._syncGeometryWithMorphTargetManager();
  26752. },
  26753. enumerable: true,
  26754. configurable: true
  26755. });
  26756. Object.defineProperty(Mesh.prototype, "source", {
  26757. get: function () {
  26758. return this._source;
  26759. },
  26760. enumerable: true,
  26761. configurable: true
  26762. });
  26763. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  26764. get: function () {
  26765. return this._unIndexed;
  26766. },
  26767. set: function (value) {
  26768. if (this._unIndexed !== value) {
  26769. this._unIndexed = value;
  26770. this._markSubMeshesAsAttributesDirty();
  26771. }
  26772. },
  26773. enumerable: true,
  26774. configurable: true
  26775. });
  26776. // Methods
  26777. /**
  26778. * Returns the string "Mesh".
  26779. */
  26780. Mesh.prototype.getClassName = function () {
  26781. return "Mesh";
  26782. };
  26783. /**
  26784. * Returns a string.
  26785. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  26786. */
  26787. Mesh.prototype.toString = function (fullDetails) {
  26788. var ret = _super.prototype.toString.call(this, fullDetails);
  26789. ret += ", n vertices: " + this.getTotalVertices();
  26790. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  26791. if (this.animations) {
  26792. for (var i = 0; i < this.animations.length; i++) {
  26793. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  26794. }
  26795. }
  26796. if (fullDetails) {
  26797. if (this._geometry) {
  26798. var ib = this.getIndices();
  26799. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  26800. if (vb && ib) {
  26801. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  26802. }
  26803. }
  26804. else {
  26805. ret += ", flat shading: UNKNOWN";
  26806. }
  26807. }
  26808. return ret;
  26809. };
  26810. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  26811. /**
  26812. * True if the mesh has some Levels Of Details (LOD).
  26813. * Returns a boolean.
  26814. */
  26815. get: function () {
  26816. return this._LODLevels.length > 0;
  26817. },
  26818. enumerable: true,
  26819. configurable: true
  26820. });
  26821. /**
  26822. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  26823. * @returns an array of {BABYLON.MeshLODLevel}
  26824. */
  26825. Mesh.prototype.getLODLevels = function () {
  26826. return this._LODLevels;
  26827. };
  26828. Mesh.prototype._sortLODLevels = function () {
  26829. this._LODLevels.sort(function (a, b) {
  26830. if (a.distance < b.distance) {
  26831. return 1;
  26832. }
  26833. if (a.distance > b.distance) {
  26834. return -1;
  26835. }
  26836. return 0;
  26837. });
  26838. };
  26839. /**
  26840. * Add a mesh as LOD level triggered at the given distance.
  26841. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  26842. * @param {number} distance The distance from the center of the object to show this level
  26843. * @param {Mesh} mesh The mesh to be added as LOD level
  26844. * @return {Mesh} This mesh (for chaining)
  26845. */
  26846. Mesh.prototype.addLODLevel = function (distance, mesh) {
  26847. if (mesh && mesh._masterMesh) {
  26848. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  26849. return this;
  26850. }
  26851. var level = new BABYLON.MeshLODLevel(distance, mesh);
  26852. this._LODLevels.push(level);
  26853. if (mesh) {
  26854. mesh._masterMesh = this;
  26855. }
  26856. this._sortLODLevels();
  26857. return this;
  26858. };
  26859. /**
  26860. * Returns the LOD level mesh at the passed distance or null if not found.
  26861. * It is related to the method `addLODLevel(distance, mesh)`.
  26862. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  26863. * Returns an object Mesh or `null`.
  26864. */
  26865. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  26866. for (var index = 0; index < this._LODLevels.length; index++) {
  26867. var level = this._LODLevels[index];
  26868. if (level.distance === distance) {
  26869. return level.mesh;
  26870. }
  26871. }
  26872. return null;
  26873. };
  26874. /**
  26875. * Remove a mesh from the LOD array
  26876. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  26877. * @param {Mesh} mesh The mesh to be removed.
  26878. * @return {Mesh} This mesh (for chaining)
  26879. */
  26880. Mesh.prototype.removeLODLevel = function (mesh) {
  26881. for (var index = 0; index < this._LODLevels.length; index++) {
  26882. if (this._LODLevels[index].mesh === mesh) {
  26883. this._LODLevels.splice(index, 1);
  26884. if (mesh) {
  26885. mesh._masterMesh = null;
  26886. }
  26887. }
  26888. }
  26889. this._sortLODLevels();
  26890. return this;
  26891. };
  26892. /**
  26893. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  26894. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  26895. */
  26896. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  26897. if (!this._LODLevels || this._LODLevels.length === 0) {
  26898. return this;
  26899. }
  26900. var bSphere;
  26901. if (boundingSphere) {
  26902. bSphere = boundingSphere;
  26903. }
  26904. else {
  26905. var boundingInfo = this.getBoundingInfo();
  26906. bSphere = boundingInfo.boundingSphere;
  26907. }
  26908. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  26909. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  26910. if (this.onLODLevelSelection) {
  26911. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  26912. }
  26913. return this;
  26914. }
  26915. for (var index = 0; index < this._LODLevels.length; index++) {
  26916. var level = this._LODLevels[index];
  26917. if (level.distance < distanceToCamera) {
  26918. if (level.mesh) {
  26919. level.mesh._preActivate();
  26920. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  26921. }
  26922. if (this.onLODLevelSelection) {
  26923. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  26924. }
  26925. return level.mesh;
  26926. }
  26927. }
  26928. if (this.onLODLevelSelection) {
  26929. this.onLODLevelSelection(distanceToCamera, this, this);
  26930. }
  26931. return this;
  26932. };
  26933. Object.defineProperty(Mesh.prototype, "geometry", {
  26934. /**
  26935. * Returns the mesh internal Geometry object.
  26936. */
  26937. get: function () {
  26938. return this._geometry;
  26939. },
  26940. enumerable: true,
  26941. configurable: true
  26942. });
  26943. /**
  26944. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  26945. */
  26946. Mesh.prototype.getTotalVertices = function () {
  26947. if (this._geometry === null || this._geometry === undefined) {
  26948. return 0;
  26949. }
  26950. return this._geometry.getTotalVertices();
  26951. };
  26952. /**
  26953. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  26954. * 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.
  26955. * You can force the copy with forceCopy === true
  26956. * Returns null if the mesh has no geometry or no vertex buffer.
  26957. * Possible `kind` values :
  26958. * - BABYLON.VertexBuffer.PositionKind
  26959. * - BABYLON.VertexBuffer.UVKind
  26960. * - BABYLON.VertexBuffer.UV2Kind
  26961. * - BABYLON.VertexBuffer.UV3Kind
  26962. * - BABYLON.VertexBuffer.UV4Kind
  26963. * - BABYLON.VertexBuffer.UV5Kind
  26964. * - BABYLON.VertexBuffer.UV6Kind
  26965. * - BABYLON.VertexBuffer.ColorKind
  26966. * - BABYLON.VertexBuffer.MatricesIndicesKind
  26967. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  26968. * - BABYLON.VertexBuffer.MatricesWeightsKind
  26969. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  26970. */
  26971. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  26972. if (!this._geometry) {
  26973. return null;
  26974. }
  26975. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  26976. };
  26977. /**
  26978. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  26979. * Returns `null` if the mesh has no geometry.
  26980. * Possible `kind` values :
  26981. * - BABYLON.VertexBuffer.PositionKind
  26982. * - BABYLON.VertexBuffer.UVKind
  26983. * - BABYLON.VertexBuffer.UV2Kind
  26984. * - BABYLON.VertexBuffer.UV3Kind
  26985. * - BABYLON.VertexBuffer.UV4Kind
  26986. * - BABYLON.VertexBuffer.UV5Kind
  26987. * - BABYLON.VertexBuffer.UV6Kind
  26988. * - BABYLON.VertexBuffer.ColorKind
  26989. * - BABYLON.VertexBuffer.MatricesIndicesKind
  26990. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  26991. * - BABYLON.VertexBuffer.MatricesWeightsKind
  26992. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  26993. */
  26994. Mesh.prototype.getVertexBuffer = function (kind) {
  26995. if (!this._geometry) {
  26996. return null;
  26997. }
  26998. return this._geometry.getVertexBuffer(kind);
  26999. };
  27000. /**
  27001. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  27002. * Possible `kind` values :
  27003. * - BABYLON.VertexBuffer.PositionKind
  27004. * - BABYLON.VertexBuffer.UVKind
  27005. * - BABYLON.VertexBuffer.UV2Kind
  27006. * - BABYLON.VertexBuffer.UV3Kind
  27007. * - BABYLON.VertexBuffer.UV4Kind
  27008. * - BABYLON.VertexBuffer.UV5Kind
  27009. * - BABYLON.VertexBuffer.UV6Kind
  27010. * - BABYLON.VertexBuffer.ColorKind
  27011. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27012. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27013. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27014. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27015. */
  27016. Mesh.prototype.isVerticesDataPresent = function (kind) {
  27017. if (!this._geometry) {
  27018. if (this._delayInfo) {
  27019. return this._delayInfo.indexOf(kind) !== -1;
  27020. }
  27021. return false;
  27022. }
  27023. return this._geometry.isVerticesDataPresent(kind);
  27024. };
  27025. /**
  27026. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  27027. * Possible `kind` values :
  27028. * - BABYLON.VertexBuffer.PositionKind
  27029. * - BABYLON.VertexBuffer.UVKind
  27030. * - BABYLON.VertexBuffer.UV2Kind
  27031. * - BABYLON.VertexBuffer.UV3Kind
  27032. * - BABYLON.VertexBuffer.UV4Kind
  27033. * - BABYLON.VertexBuffer.UV5Kind
  27034. * - BABYLON.VertexBuffer.UV6Kind
  27035. * - BABYLON.VertexBuffer.ColorKind
  27036. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27037. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27038. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27039. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27040. */
  27041. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  27042. if (!this._geometry) {
  27043. if (this._delayInfo) {
  27044. return this._delayInfo.indexOf(kind) !== -1;
  27045. }
  27046. return false;
  27047. }
  27048. return this._geometry.isVertexBufferUpdatable(kind);
  27049. };
  27050. /**
  27051. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  27052. * Possible `kind` values :
  27053. * - BABYLON.VertexBuffer.PositionKind
  27054. * - BABYLON.VertexBuffer.UVKind
  27055. * - BABYLON.VertexBuffer.UV2Kind
  27056. * - BABYLON.VertexBuffer.UV3Kind
  27057. * - BABYLON.VertexBuffer.UV4Kind
  27058. * - BABYLON.VertexBuffer.UV5Kind
  27059. * - BABYLON.VertexBuffer.UV6Kind
  27060. * - BABYLON.VertexBuffer.ColorKind
  27061. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27062. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27063. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27064. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27065. */
  27066. Mesh.prototype.getVerticesDataKinds = function () {
  27067. if (!this._geometry) {
  27068. var result = new Array();
  27069. if (this._delayInfo) {
  27070. this._delayInfo.forEach(function (kind, index, array) {
  27071. result.push(kind);
  27072. });
  27073. }
  27074. return result;
  27075. }
  27076. return this._geometry.getVerticesDataKinds();
  27077. };
  27078. /**
  27079. * Returns a positive integer : the total number of indices in this mesh geometry.
  27080. * Returns zero if the mesh has no geometry.
  27081. */
  27082. Mesh.prototype.getTotalIndices = function () {
  27083. if (!this._geometry) {
  27084. return 0;
  27085. }
  27086. return this._geometry.getTotalIndices();
  27087. };
  27088. /**
  27089. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  27090. * 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.
  27091. * Returns an empty array if the mesh has no geometry.
  27092. */
  27093. Mesh.prototype.getIndices = function (copyWhenShared) {
  27094. if (!this._geometry) {
  27095. return [];
  27096. }
  27097. return this._geometry.getIndices(copyWhenShared);
  27098. };
  27099. Object.defineProperty(Mesh.prototype, "isBlocked", {
  27100. get: function () {
  27101. return this._masterMesh !== null && this._masterMesh !== undefined;
  27102. },
  27103. enumerable: true,
  27104. configurable: true
  27105. });
  27106. /**
  27107. * Determine if the current mesh is ready to be rendered
  27108. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  27109. * @returns true if all associated assets are ready (material, textures, shaders)
  27110. */
  27111. Mesh.prototype.isReady = function (forceInstanceSupport) {
  27112. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  27113. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  27114. return false;
  27115. }
  27116. if (!_super.prototype.isReady.call(this)) {
  27117. return false;
  27118. }
  27119. if (!this.subMeshes || this.subMeshes.length === 0) {
  27120. return true;
  27121. }
  27122. var engine = this.getEngine();
  27123. var scene = this.getScene();
  27124. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  27125. this.computeWorldMatrix();
  27126. var mat = this.material || scene.defaultMaterial;
  27127. if (mat) {
  27128. if (mat.storeEffectOnSubMeshes) {
  27129. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  27130. var subMesh = _a[_i];
  27131. var effectiveMaterial = subMesh.getMaterial();
  27132. if (effectiveMaterial) {
  27133. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  27134. return false;
  27135. }
  27136. }
  27137. }
  27138. }
  27139. else {
  27140. if (!mat.isReady(this, hardwareInstancedRendering)) {
  27141. return false;
  27142. }
  27143. }
  27144. }
  27145. // Shadows
  27146. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  27147. var light = _c[_b];
  27148. var generator = light.getShadowGenerator();
  27149. if (generator) {
  27150. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  27151. var subMesh = _e[_d];
  27152. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  27153. return false;
  27154. }
  27155. }
  27156. }
  27157. }
  27158. // LOD
  27159. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  27160. var lod = _g[_f];
  27161. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  27162. return false;
  27163. }
  27164. }
  27165. return true;
  27166. };
  27167. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  27168. /**
  27169. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  27170. * This property is pertinent only for updatable parametric shapes.
  27171. */
  27172. get: function () {
  27173. return this._areNormalsFrozen;
  27174. },
  27175. enumerable: true,
  27176. configurable: true
  27177. });
  27178. /**
  27179. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  27180. * It has no effect at all on other shapes.
  27181. * It prevents the mesh normals from being recomputed on next `positions` array update.
  27182. * Returns the Mesh.
  27183. */
  27184. Mesh.prototype.freezeNormals = function () {
  27185. this._areNormalsFrozen = true;
  27186. return this;
  27187. };
  27188. /**
  27189. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  27190. * It has no effect at all on other shapes.
  27191. * It reactivates the mesh normals computation if it was previously frozen.
  27192. * Returns the Mesh.
  27193. */
  27194. Mesh.prototype.unfreezeNormals = function () {
  27195. this._areNormalsFrozen = false;
  27196. return this;
  27197. };
  27198. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  27199. /**
  27200. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  27201. */
  27202. set: function (count) {
  27203. this._overridenInstanceCount = count;
  27204. },
  27205. enumerable: true,
  27206. configurable: true
  27207. });
  27208. // Methods
  27209. Mesh.prototype._preActivate = function () {
  27210. var sceneRenderId = this.getScene().getRenderId();
  27211. if (this._preActivateId === sceneRenderId) {
  27212. return this;
  27213. }
  27214. this._preActivateId = sceneRenderId;
  27215. this._visibleInstances = null;
  27216. return this;
  27217. };
  27218. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  27219. if (this._visibleInstances) {
  27220. this._visibleInstances.intermediateDefaultRenderId = renderId;
  27221. }
  27222. return this;
  27223. };
  27224. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  27225. if (!this._visibleInstances) {
  27226. this._visibleInstances = {};
  27227. this._visibleInstances.defaultRenderId = renderId;
  27228. this._visibleInstances.selfDefaultRenderId = this._renderId;
  27229. }
  27230. if (!this._visibleInstances[renderId]) {
  27231. this._visibleInstances[renderId] = new Array();
  27232. }
  27233. this._visibleInstances[renderId].push(instance);
  27234. return this;
  27235. };
  27236. /**
  27237. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  27238. * This means the mesh underlying bounding box and sphere are recomputed.
  27239. * Returns the Mesh.
  27240. */
  27241. Mesh.prototype.refreshBoundingInfo = function () {
  27242. return this._refreshBoundingInfo(false);
  27243. };
  27244. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  27245. if (this._boundingInfo && this._boundingInfo.isLocked) {
  27246. return this;
  27247. }
  27248. var data = this._getPositionData(applySkeleton);
  27249. if (data) {
  27250. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  27251. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  27252. }
  27253. if (this.subMeshes) {
  27254. for (var index = 0; index < this.subMeshes.length; index++) {
  27255. this.subMeshes[index].refreshBoundingInfo();
  27256. }
  27257. }
  27258. this._updateBoundingInfo();
  27259. return this;
  27260. };
  27261. Mesh.prototype._getPositionData = function (applySkeleton) {
  27262. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27263. if (data && applySkeleton && this.skeleton) {
  27264. data = BABYLON.Tools.Slice(data);
  27265. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  27266. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  27267. if (matricesWeightsData && matricesIndicesData) {
  27268. var needExtras = this.numBoneInfluencers > 4;
  27269. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  27270. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  27271. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  27272. var tempVector = BABYLON.Tmp.Vector3[0];
  27273. var finalMatrix = BABYLON.Tmp.Matrix[0];
  27274. var tempMatrix = BABYLON.Tmp.Matrix[1];
  27275. var matWeightIdx = 0;
  27276. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  27277. finalMatrix.reset();
  27278. var inf;
  27279. var weight;
  27280. for (inf = 0; inf < 4; inf++) {
  27281. weight = matricesWeightsData[matWeightIdx + inf];
  27282. if (weight <= 0)
  27283. break;
  27284. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  27285. finalMatrix.addToSelf(tempMatrix);
  27286. }
  27287. if (needExtras) {
  27288. for (inf = 0; inf < 4; inf++) {
  27289. weight = matricesWeightsExtraData[matWeightIdx + inf];
  27290. if (weight <= 0)
  27291. break;
  27292. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  27293. finalMatrix.addToSelf(tempMatrix);
  27294. }
  27295. }
  27296. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  27297. tempVector.toArray(data, index);
  27298. }
  27299. }
  27300. }
  27301. return data;
  27302. };
  27303. Mesh.prototype._createGlobalSubMesh = function (force) {
  27304. var totalVertices = this.getTotalVertices();
  27305. if (!totalVertices || !this.getIndices()) {
  27306. return null;
  27307. }
  27308. // Check if we need to recreate the submeshes
  27309. if (this.subMeshes && this.subMeshes.length > 0) {
  27310. var ib = this.getIndices();
  27311. if (!ib) {
  27312. return null;
  27313. }
  27314. var totalIndices = ib.length;
  27315. var needToRecreate = false;
  27316. if (force) {
  27317. needToRecreate = true;
  27318. }
  27319. else {
  27320. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  27321. var submesh = _a[_i];
  27322. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  27323. needToRecreate = true;
  27324. break;
  27325. }
  27326. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  27327. needToRecreate = true;
  27328. break;
  27329. }
  27330. }
  27331. }
  27332. if (!needToRecreate) {
  27333. return this.subMeshes[0];
  27334. }
  27335. }
  27336. this.releaseSubMeshes();
  27337. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  27338. };
  27339. Mesh.prototype.subdivide = function (count) {
  27340. if (count < 1) {
  27341. return;
  27342. }
  27343. var totalIndices = this.getTotalIndices();
  27344. var subdivisionSize = (totalIndices / count) | 0;
  27345. var offset = 0;
  27346. // Ensure that subdivisionSize is a multiple of 3
  27347. while (subdivisionSize % 3 !== 0) {
  27348. subdivisionSize++;
  27349. }
  27350. this.releaseSubMeshes();
  27351. for (var index = 0; index < count; index++) {
  27352. if (offset >= totalIndices) {
  27353. break;
  27354. }
  27355. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  27356. offset += subdivisionSize;
  27357. }
  27358. this.synchronizeInstances();
  27359. };
  27360. /**
  27361. * Sets the vertex data of the mesh geometry for the requested `kind`.
  27362. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  27363. * The `data` are either a numeric array either a Float32Array.
  27364. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  27365. * 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).
  27366. * Note that a new underlying VertexBuffer object is created each call.
  27367. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  27368. *
  27369. * Possible `kind` values :
  27370. * - BABYLON.VertexBuffer.PositionKind
  27371. * - BABYLON.VertexBuffer.UVKind
  27372. * - BABYLON.VertexBuffer.UV2Kind
  27373. * - BABYLON.VertexBuffer.UV3Kind
  27374. * - BABYLON.VertexBuffer.UV4Kind
  27375. * - BABYLON.VertexBuffer.UV5Kind
  27376. * - BABYLON.VertexBuffer.UV6Kind
  27377. * - BABYLON.VertexBuffer.ColorKind
  27378. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27379. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27380. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27381. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27382. *
  27383. * Returns the Mesh.
  27384. */
  27385. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  27386. if (updatable === void 0) { updatable = false; }
  27387. if (!this._geometry) {
  27388. var vertexData = new BABYLON.VertexData();
  27389. vertexData.set(data, kind);
  27390. var scene = this.getScene();
  27391. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  27392. }
  27393. else {
  27394. this._geometry.setVerticesData(kind, data, updatable, stride);
  27395. }
  27396. return this;
  27397. };
  27398. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  27399. if (updatable === void 0) { updatable = true; }
  27400. var vb = this.getVertexBuffer(kind);
  27401. if (!vb || vb.isUpdatable() === updatable) {
  27402. return;
  27403. }
  27404. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  27405. };
  27406. /**
  27407. * Sets the mesh VertexBuffer.
  27408. * Returns the Mesh.
  27409. */
  27410. Mesh.prototype.setVerticesBuffer = function (buffer) {
  27411. if (!this._geometry) {
  27412. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  27413. }
  27414. this._geometry.setVerticesBuffer(buffer);
  27415. return this;
  27416. };
  27417. /**
  27418. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  27419. * If the mesh has no geometry, it is simply returned as it is.
  27420. * The `data` are either a numeric array either a Float32Array.
  27421. * No new underlying VertexBuffer object is created.
  27422. * 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.
  27423. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  27424. *
  27425. * Possible `kind` values :
  27426. * - BABYLON.VertexBuffer.PositionKind
  27427. * - BABYLON.VertexBuffer.UVKind
  27428. * - BABYLON.VertexBuffer.UV2Kind
  27429. * - BABYLON.VertexBuffer.UV3Kind
  27430. * - BABYLON.VertexBuffer.UV4Kind
  27431. * - BABYLON.VertexBuffer.UV5Kind
  27432. * - BABYLON.VertexBuffer.UV6Kind
  27433. * - BABYLON.VertexBuffer.ColorKind
  27434. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27435. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27436. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27437. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27438. *
  27439. * Returns the Mesh.
  27440. */
  27441. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  27442. if (!this._geometry) {
  27443. return this;
  27444. }
  27445. if (!makeItUnique) {
  27446. this._geometry.updateVerticesData(kind, data, updateExtends);
  27447. }
  27448. else {
  27449. this.makeGeometryUnique();
  27450. this.updateVerticesData(kind, data, updateExtends, false);
  27451. }
  27452. return this;
  27453. };
  27454. /**
  27455. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  27456. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  27457. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  27458. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  27459. * Returns the Mesh.
  27460. */
  27461. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  27462. if (computeNormals === void 0) { computeNormals = true; }
  27463. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27464. if (!positions) {
  27465. return this;
  27466. }
  27467. positionFunction(positions);
  27468. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  27469. if (computeNormals) {
  27470. var indices = this.getIndices();
  27471. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  27472. if (!normals) {
  27473. return this;
  27474. }
  27475. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  27476. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  27477. }
  27478. return this;
  27479. };
  27480. /**
  27481. * Creates a un-shared specific occurence of the geometry for the mesh.
  27482. * Returns the Mesh.
  27483. */
  27484. Mesh.prototype.makeGeometryUnique = function () {
  27485. if (!this._geometry) {
  27486. return this;
  27487. }
  27488. var oldGeometry = this._geometry;
  27489. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  27490. oldGeometry.releaseForMesh(this, true);
  27491. geometry.applyToMesh(this);
  27492. return this;
  27493. };
  27494. /**
  27495. * Sets the mesh indices.
  27496. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  27497. * Type is Uint16Array by default unless the mesh has more than 65536 vertices.
  27498. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  27499. * This method creates a new index buffer each call.
  27500. * Returns the Mesh.
  27501. */
  27502. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  27503. if (totalVertices === void 0) { totalVertices = null; }
  27504. if (updatable === void 0) { updatable = false; }
  27505. if (!this._geometry) {
  27506. var vertexData = new BABYLON.VertexData();
  27507. vertexData.indices = indices;
  27508. var scene = this.getScene();
  27509. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  27510. }
  27511. else {
  27512. this._geometry.setIndices(indices, totalVertices, updatable);
  27513. }
  27514. return this;
  27515. };
  27516. /**
  27517. * Update the current index buffer
  27518. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  27519. * Returns the Mesh.
  27520. */
  27521. Mesh.prototype.updateIndices = function (indices, offset) {
  27522. if (!this._geometry) {
  27523. return this;
  27524. }
  27525. this._geometry.updateIndices(indices, offset);
  27526. return this;
  27527. };
  27528. /**
  27529. * Invert the geometry to move from a right handed system to a left handed one.
  27530. * Returns the Mesh.
  27531. */
  27532. Mesh.prototype.toLeftHanded = function () {
  27533. if (!this._geometry) {
  27534. return this;
  27535. }
  27536. this._geometry.toLeftHanded();
  27537. return this;
  27538. };
  27539. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  27540. if (!this._geometry) {
  27541. return this;
  27542. }
  27543. var engine = this.getScene().getEngine();
  27544. // Wireframe
  27545. var indexToBind;
  27546. if (this._unIndexed) {
  27547. indexToBind = null;
  27548. }
  27549. else {
  27550. switch (fillMode) {
  27551. case BABYLON.Material.PointFillMode:
  27552. indexToBind = null;
  27553. break;
  27554. case BABYLON.Material.WireFrameFillMode:
  27555. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  27556. break;
  27557. default:
  27558. case BABYLON.Material.TriangleFillMode:
  27559. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  27560. break;
  27561. }
  27562. }
  27563. // VBOs
  27564. this._geometry._bind(effect, indexToBind);
  27565. return this;
  27566. };
  27567. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  27568. if (alternate === void 0) { alternate = false; }
  27569. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  27570. return this;
  27571. }
  27572. this.onBeforeDrawObservable.notifyObservers(this);
  27573. var scene = this.getScene();
  27574. var engine = scene.getEngine();
  27575. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  27576. // or triangles as points
  27577. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  27578. }
  27579. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  27580. // Triangles as wireframe
  27581. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  27582. }
  27583. else {
  27584. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  27585. }
  27586. if (scene._isAlternateRenderingEnabled && !alternate) {
  27587. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  27588. if (!effect || !scene.activeCamera) {
  27589. return this;
  27590. }
  27591. scene._switchToAlternateCameraConfiguration(true);
  27592. this._effectiveMaterial.bindView(effect);
  27593. this._effectiveMaterial.bindViewProjection(effect);
  27594. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  27595. this._draw(subMesh, fillMode, instancesCount, true);
  27596. engine.setViewport(scene.activeCamera.viewport);
  27597. scene._switchToAlternateCameraConfiguration(false);
  27598. this._effectiveMaterial.bindView(effect);
  27599. this._effectiveMaterial.bindViewProjection(effect);
  27600. }
  27601. return this;
  27602. };
  27603. /**
  27604. * Registers for this mesh a javascript function called just before the rendering process.
  27605. * This function is passed the current mesh.
  27606. * Return the Mesh.
  27607. */
  27608. Mesh.prototype.registerBeforeRender = function (func) {
  27609. this.onBeforeRenderObservable.add(func);
  27610. return this;
  27611. };
  27612. /**
  27613. * Disposes a previously registered javascript function called before the rendering.
  27614. * This function is passed the current mesh.
  27615. * Returns the Mesh.
  27616. */
  27617. Mesh.prototype.unregisterBeforeRender = function (func) {
  27618. this.onBeforeRenderObservable.removeCallback(func);
  27619. return this;
  27620. };
  27621. /**
  27622. * Registers for this mesh a javascript function called just after the rendering is complete.
  27623. * This function is passed the current mesh.
  27624. * Returns the Mesh.
  27625. */
  27626. Mesh.prototype.registerAfterRender = function (func) {
  27627. this.onAfterRenderObservable.add(func);
  27628. return this;
  27629. };
  27630. /**
  27631. * Disposes a previously registered javascript function called after the rendering.
  27632. * This function is passed the current mesh.
  27633. * Return the Mesh.
  27634. */
  27635. Mesh.prototype.unregisterAfterRender = function (func) {
  27636. this.onAfterRenderObservable.removeCallback(func);
  27637. return this;
  27638. };
  27639. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  27640. var scene = this.getScene();
  27641. this._batchCache.mustReturn = false;
  27642. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  27643. this._batchCache.visibleInstances[subMeshId] = null;
  27644. if (this._visibleInstances) {
  27645. var currentRenderId = scene.getRenderId();
  27646. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  27647. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  27648. var selfRenderId = this._renderId;
  27649. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  27650. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  27651. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  27652. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  27653. }
  27654. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  27655. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  27656. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  27657. this._batchCache.mustReturn = true;
  27658. return this._batchCache;
  27659. }
  27660. if (currentRenderId !== selfRenderId) {
  27661. this._batchCache.renderSelf[subMeshId] = false;
  27662. }
  27663. }
  27664. this._renderIdForInstances[subMeshId] = currentRenderId;
  27665. }
  27666. return this._batchCache;
  27667. };
  27668. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  27669. var visibleInstances = batch.visibleInstances[subMesh._id];
  27670. if (!visibleInstances) {
  27671. return this;
  27672. }
  27673. var matricesCount = visibleInstances.length + 1;
  27674. var bufferSize = matricesCount * 16 * 4;
  27675. var currentInstancesBufferSize = this._instancesBufferSize;
  27676. var instancesBuffer = this._instancesBuffer;
  27677. while (this._instancesBufferSize < bufferSize) {
  27678. this._instancesBufferSize *= 2;
  27679. }
  27680. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  27681. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  27682. }
  27683. var offset = 0;
  27684. var instancesCount = 0;
  27685. var world = this.getWorldMatrix();
  27686. if (batch.renderSelf[subMesh._id]) {
  27687. world.copyToArray(this._instancesData, offset);
  27688. offset += 16;
  27689. instancesCount++;
  27690. }
  27691. if (visibleInstances) {
  27692. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  27693. var instance = visibleInstances[instanceIndex];
  27694. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  27695. offset += 16;
  27696. instancesCount++;
  27697. }
  27698. }
  27699. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  27700. if (instancesBuffer) {
  27701. instancesBuffer.dispose();
  27702. }
  27703. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  27704. this._instancesBuffer = instancesBuffer;
  27705. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  27706. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  27707. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  27708. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  27709. }
  27710. else {
  27711. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  27712. }
  27713. this._bind(subMesh, effect, fillMode);
  27714. this._draw(subMesh, fillMode, instancesCount);
  27715. engine.unbindInstanceAttributes();
  27716. return this;
  27717. };
  27718. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  27719. var scene = this.getScene();
  27720. var engine = scene.getEngine();
  27721. if (hardwareInstancedRendering) {
  27722. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  27723. }
  27724. else {
  27725. if (batch.renderSelf[subMesh._id]) {
  27726. // Draw
  27727. if (onBeforeDraw) {
  27728. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  27729. }
  27730. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  27731. }
  27732. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  27733. if (visibleInstancesForSubMesh) {
  27734. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  27735. var instance = visibleInstancesForSubMesh[instanceIndex];
  27736. // World
  27737. var world = instance.getWorldMatrix();
  27738. if (onBeforeDraw) {
  27739. onBeforeDraw(true, world, effectiveMaterial);
  27740. }
  27741. // Draw
  27742. this._draw(subMesh, fillMode);
  27743. }
  27744. }
  27745. }
  27746. return this;
  27747. };
  27748. /**
  27749. * Triggers the draw call for the mesh.
  27750. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  27751. * Returns the Mesh.
  27752. */
  27753. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  27754. this.checkOcclusionQuery();
  27755. if (this._isOccluded) {
  27756. return this;
  27757. }
  27758. var scene = this.getScene();
  27759. // Managing instances
  27760. var batch = this._getInstancesRenderList(subMesh._id);
  27761. if (batch.mustReturn) {
  27762. return this;
  27763. }
  27764. // Checking geometry state
  27765. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  27766. return this;
  27767. }
  27768. this.onBeforeRenderObservable.notifyObservers(this);
  27769. var engine = scene.getEngine();
  27770. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  27771. // Material
  27772. var material = subMesh.getMaterial();
  27773. if (!material) {
  27774. return this;
  27775. }
  27776. this._effectiveMaterial = material;
  27777. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  27778. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  27779. return this;
  27780. }
  27781. }
  27782. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  27783. return this;
  27784. }
  27785. // Alpha mode
  27786. if (enableAlphaMode) {
  27787. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  27788. }
  27789. // Outline - step 1
  27790. var savedDepthWrite = engine.getDepthWrite();
  27791. if (this.renderOutline) {
  27792. engine.setDepthWrite(false);
  27793. scene.getOutlineRenderer().render(subMesh, batch);
  27794. engine.setDepthWrite(savedDepthWrite);
  27795. }
  27796. var effect;
  27797. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  27798. effect = subMesh.effect;
  27799. }
  27800. else {
  27801. effect = this._effectiveMaterial.getEffect();
  27802. }
  27803. if (!effect) {
  27804. return this;
  27805. }
  27806. var sideOrientation = this.overrideMaterialSideOrientation;
  27807. if (sideOrientation == null) {
  27808. sideOrientation = this._effectiveMaterial.sideOrientation;
  27809. if (this._getWorldMatrixDeterminant() < 0) {
  27810. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  27811. }
  27812. }
  27813. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  27814. if (this._effectiveMaterial.forceDepthWrite) {
  27815. engine.setDepthWrite(true);
  27816. }
  27817. // Bind
  27818. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  27819. if (!hardwareInstancedRendering) {
  27820. this._bind(subMesh, effect, fillMode);
  27821. }
  27822. var world = this.getWorldMatrix();
  27823. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  27824. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  27825. }
  27826. else {
  27827. this._effectiveMaterial.bind(world, this);
  27828. }
  27829. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  27830. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  27831. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  27832. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  27833. }
  27834. // Draw
  27835. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  27836. // Unbind
  27837. this._effectiveMaterial.unbind();
  27838. // Outline - step 2
  27839. if (this.renderOutline && savedDepthWrite) {
  27840. engine.setDepthWrite(true);
  27841. engine.setColorWrite(false);
  27842. scene.getOutlineRenderer().render(subMesh, batch);
  27843. engine.setColorWrite(true);
  27844. }
  27845. // Overlay
  27846. if (this.renderOverlay) {
  27847. var currentMode = engine.getAlphaMode();
  27848. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  27849. scene.getOutlineRenderer().render(subMesh, batch, true);
  27850. engine.setAlphaMode(currentMode);
  27851. }
  27852. this.onAfterRenderObservable.notifyObservers(this);
  27853. return this;
  27854. };
  27855. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  27856. if (isInstance && effectiveMaterial) {
  27857. effectiveMaterial.bindOnlyWorldMatrix(world);
  27858. }
  27859. };
  27860. /**
  27861. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  27862. */
  27863. Mesh.prototype.getEmittedParticleSystems = function () {
  27864. var results = new Array();
  27865. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  27866. var particleSystem = this.getScene().particleSystems[index];
  27867. if (particleSystem.emitter === this) {
  27868. results.push(particleSystem);
  27869. }
  27870. }
  27871. return results;
  27872. };
  27873. /**
  27874. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  27875. */
  27876. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  27877. var results = new Array();
  27878. var descendants = this.getDescendants();
  27879. descendants.push(this);
  27880. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  27881. var particleSystem = this.getScene().particleSystems[index];
  27882. var emitter = particleSystem.emitter;
  27883. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  27884. results.push(particleSystem);
  27885. }
  27886. }
  27887. return results;
  27888. };
  27889. Mesh.prototype._checkDelayState = function () {
  27890. var scene = this.getScene();
  27891. if (this._geometry) {
  27892. this._geometry.load(scene);
  27893. }
  27894. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  27895. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  27896. this._queueLoad(scene);
  27897. }
  27898. return this;
  27899. };
  27900. Mesh.prototype._queueLoad = function (scene) {
  27901. var _this = this;
  27902. scene._addPendingData(this);
  27903. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  27904. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  27905. if (data instanceof ArrayBuffer) {
  27906. _this._delayLoadingFunction(data, _this);
  27907. }
  27908. else {
  27909. _this._delayLoadingFunction(JSON.parse(data), _this);
  27910. }
  27911. _this.instances.forEach(function (instance) {
  27912. instance._syncSubMeshes();
  27913. });
  27914. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  27915. scene._removePendingData(_this);
  27916. }, function () { }, scene.database, getBinaryData);
  27917. return this;
  27918. };
  27919. /**
  27920. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  27921. */
  27922. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  27923. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  27924. return false;
  27925. }
  27926. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  27927. return false;
  27928. }
  27929. this._checkDelayState();
  27930. return true;
  27931. };
  27932. /**
  27933. * Sets the mesh material by the material or multiMaterial `id` property.
  27934. * The material `id` is a string identifying the material or the multiMaterial.
  27935. * This method returns the Mesh.
  27936. */
  27937. Mesh.prototype.setMaterialByID = function (id) {
  27938. var materials = this.getScene().materials;
  27939. var index;
  27940. for (index = materials.length - 1; index > -1; index--) {
  27941. if (materials[index].id === id) {
  27942. this.material = materials[index];
  27943. return this;
  27944. }
  27945. }
  27946. // Multi
  27947. var multiMaterials = this.getScene().multiMaterials;
  27948. for (index = multiMaterials.length - 1; index > -1; index--) {
  27949. if (multiMaterials[index].id === id) {
  27950. this.material = multiMaterials[index];
  27951. return this;
  27952. }
  27953. }
  27954. return this;
  27955. };
  27956. /**
  27957. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  27958. */
  27959. Mesh.prototype.getAnimatables = function () {
  27960. var results = new Array();
  27961. if (this.material) {
  27962. results.push(this.material);
  27963. }
  27964. if (this.skeleton) {
  27965. results.push(this.skeleton);
  27966. }
  27967. return results;
  27968. };
  27969. /**
  27970. * Modifies the mesh geometry according to the passed transformation matrix.
  27971. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  27972. * The mesh normals are modified accordingly the same transformation.
  27973. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  27974. * Note that, under the hood, this method sets a new VertexBuffer each call.
  27975. * Returns the Mesh.
  27976. */
  27977. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  27978. // Position
  27979. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  27980. return this;
  27981. }
  27982. var submeshes = this.subMeshes.splice(0);
  27983. this._resetPointsArrayCache();
  27984. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27985. var temp = new Array();
  27986. var index;
  27987. for (index = 0; index < data.length; index += 3) {
  27988. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  27989. }
  27990. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  27991. // Normals
  27992. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  27993. return this;
  27994. }
  27995. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  27996. temp = [];
  27997. for (index = 0; index < data.length; index += 3) {
  27998. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  27999. }
  28000. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  28001. // flip faces?
  28002. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  28003. this.flipFaces();
  28004. }
  28005. // Restore submeshes
  28006. this.releaseSubMeshes();
  28007. this.subMeshes = submeshes;
  28008. return this;
  28009. };
  28010. /**
  28011. * Modifies the mesh geometry according to its own current World Matrix.
  28012. * The mesh World Matrix is then reset.
  28013. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  28014. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  28015. * Note that, under the hood, this method sets a new VertexBuffer each call.
  28016. * Returns the Mesh.
  28017. */
  28018. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  28019. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  28020. this.scaling.copyFromFloats(1, 1, 1);
  28021. this.position.copyFromFloats(0, 0, 0);
  28022. this.rotation.copyFromFloats(0, 0, 0);
  28023. //only if quaternion is already set
  28024. if (this.rotationQuaternion) {
  28025. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  28026. }
  28027. this._worldMatrix = BABYLON.Matrix.Identity();
  28028. return this;
  28029. };
  28030. Object.defineProperty(Mesh.prototype, "_positions", {
  28031. // Cache
  28032. get: function () {
  28033. if (this._geometry) {
  28034. return this._geometry._positions;
  28035. }
  28036. return null;
  28037. },
  28038. enumerable: true,
  28039. configurable: true
  28040. });
  28041. Mesh.prototype._resetPointsArrayCache = function () {
  28042. if (this._geometry) {
  28043. this._geometry._resetPointsArrayCache();
  28044. }
  28045. return this;
  28046. };
  28047. Mesh.prototype._generatePointsArray = function () {
  28048. if (this._geometry) {
  28049. return this._geometry._generatePointsArray();
  28050. }
  28051. return false;
  28052. };
  28053. /**
  28054. * Returns a new Mesh object generated from the current mesh properties.
  28055. * This method must not get confused with createInstance().
  28056. * The parameter `name` is a string, the name given to the new mesh.
  28057. * The optional parameter `newParent` can be any Node object (default `null`).
  28058. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  28059. * 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.
  28060. */
  28061. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  28062. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  28063. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  28064. };
  28065. /**
  28066. * Disposes the Mesh.
  28067. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  28068. * Returns nothing.
  28069. */
  28070. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  28071. var _this = this;
  28072. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  28073. this.morphTargetManager = null;
  28074. if (this._geometry) {
  28075. this._geometry.releaseForMesh(this, true);
  28076. }
  28077. // Sources
  28078. var meshes = this.getScene().meshes;
  28079. meshes.forEach(function (abstractMesh) {
  28080. var mesh = abstractMesh;
  28081. if (mesh._source && mesh._source === _this) {
  28082. mesh._source = null;
  28083. }
  28084. });
  28085. this._source = null;
  28086. // Instances
  28087. if (this._instancesBuffer) {
  28088. this._instancesBuffer.dispose();
  28089. this._instancesBuffer = null;
  28090. }
  28091. while (this.instances.length) {
  28092. this.instances[0].dispose();
  28093. }
  28094. // Effect layers.
  28095. var effectLayers = this.getScene().effectLayers;
  28096. for (var i = 0; i < effectLayers.length; i++) {
  28097. var effectLayer = effectLayers[i];
  28098. if (effectLayer) {
  28099. effectLayer._disposeMesh(this);
  28100. }
  28101. }
  28102. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  28103. };
  28104. /**
  28105. * Modifies the mesh geometry according to a displacement map.
  28106. * 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.
  28107. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  28108. * This method returns nothing.
  28109. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  28110. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  28111. * 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.
  28112. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  28113. * The parameter `uvScale` is an optional vector2 used to scale UV.
  28114. *
  28115. * Returns the Mesh.
  28116. */
  28117. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  28118. var _this = this;
  28119. var scene = this.getScene();
  28120. var onload = function (img) {
  28121. // Getting height map data
  28122. var canvas = document.createElement("canvas");
  28123. var context = canvas.getContext("2d");
  28124. var heightMapWidth = img.width;
  28125. var heightMapHeight = img.height;
  28126. canvas.width = heightMapWidth;
  28127. canvas.height = heightMapHeight;
  28128. context.drawImage(img, 0, 0);
  28129. // Create VertexData from map data
  28130. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  28131. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  28132. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  28133. //execute success callback, if set
  28134. if (onSuccess) {
  28135. onSuccess(_this);
  28136. }
  28137. };
  28138. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  28139. return this;
  28140. };
  28141. /**
  28142. * Modifies the mesh geometry according to a displacementMap buffer.
  28143. * 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.
  28144. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  28145. * This method returns nothing.
  28146. * 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.
  28147. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  28148. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  28149. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  28150. * The parameter `uvScale` is an optional vector2 used to scale UV.
  28151. *
  28152. * Returns the Mesh.
  28153. */
  28154. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  28155. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  28156. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  28157. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  28158. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  28159. return this;
  28160. }
  28161. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28162. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28163. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  28164. var position = BABYLON.Vector3.Zero();
  28165. var normal = BABYLON.Vector3.Zero();
  28166. var uv = BABYLON.Vector2.Zero();
  28167. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  28168. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  28169. for (var index = 0; index < positions.length; index += 3) {
  28170. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  28171. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  28172. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  28173. // Compute height
  28174. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  28175. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  28176. var pos = (u + v * heightMapWidth) * 4;
  28177. var r = buffer[pos] / 255.0;
  28178. var g = buffer[pos + 1] / 255.0;
  28179. var b = buffer[pos + 2] / 255.0;
  28180. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  28181. normal.normalize();
  28182. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  28183. position = position.add(normal);
  28184. position.toArray(positions, index);
  28185. }
  28186. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  28187. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  28188. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  28189. return this;
  28190. };
  28191. /**
  28192. * Modify the mesh to get a flat shading rendering.
  28193. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  28194. * This method returns the Mesh.
  28195. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  28196. */
  28197. Mesh.prototype.convertToFlatShadedMesh = function () {
  28198. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  28199. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  28200. var kinds = this.getVerticesDataKinds();
  28201. var vbs = {};
  28202. var data = {};
  28203. var newdata = {};
  28204. var updatableNormals = false;
  28205. var kindIndex;
  28206. var kind;
  28207. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28208. kind = kinds[kindIndex];
  28209. var vertexBuffer = this.getVertexBuffer(kind);
  28210. if (kind === BABYLON.VertexBuffer.NormalKind) {
  28211. updatableNormals = vertexBuffer.isUpdatable();
  28212. kinds.splice(kindIndex, 1);
  28213. kindIndex--;
  28214. continue;
  28215. }
  28216. vbs[kind] = vertexBuffer;
  28217. data[kind] = vbs[kind].getData();
  28218. newdata[kind] = [];
  28219. }
  28220. // Save previous submeshes
  28221. var previousSubmeshes = this.subMeshes.slice(0);
  28222. var indices = this.getIndices();
  28223. var totalIndices = this.getTotalIndices();
  28224. // Generating unique vertices per face
  28225. var index;
  28226. for (index = 0; index < totalIndices; index++) {
  28227. var vertexIndex = indices[index];
  28228. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28229. kind = kinds[kindIndex];
  28230. var stride = vbs[kind].getStrideSize();
  28231. for (var offset = 0; offset < stride; offset++) {
  28232. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  28233. }
  28234. }
  28235. }
  28236. // Updating faces & normal
  28237. var normals = [];
  28238. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  28239. for (index = 0; index < totalIndices; index += 3) {
  28240. indices[index] = index;
  28241. indices[index + 1] = index + 1;
  28242. indices[index + 2] = index + 2;
  28243. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  28244. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  28245. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  28246. var p1p2 = p1.subtract(p2);
  28247. var p3p2 = p3.subtract(p2);
  28248. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  28249. // Store same normals for every vertex
  28250. for (var localIndex = 0; localIndex < 3; localIndex++) {
  28251. normals.push(normal.x);
  28252. normals.push(normal.y);
  28253. normals.push(normal.z);
  28254. }
  28255. }
  28256. this.setIndices(indices);
  28257. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  28258. // Updating vertex buffers
  28259. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28260. kind = kinds[kindIndex];
  28261. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  28262. }
  28263. // Updating submeshes
  28264. this.releaseSubMeshes();
  28265. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  28266. var previousOne = previousSubmeshes[submeshIndex];
  28267. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  28268. }
  28269. this.synchronizeInstances();
  28270. return this;
  28271. };
  28272. /**
  28273. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  28274. * In other words, more vertices, no more indices and a single bigger VBO.
  28275. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  28276. * Returns the Mesh.
  28277. */
  28278. Mesh.prototype.convertToUnIndexedMesh = function () {
  28279. /// <summary>Remove indices by unfolding faces into buffers</summary>
  28280. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  28281. var kinds = this.getVerticesDataKinds();
  28282. var vbs = {};
  28283. var data = {};
  28284. var newdata = {};
  28285. var kindIndex;
  28286. var kind;
  28287. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28288. kind = kinds[kindIndex];
  28289. var vertexBuffer = this.getVertexBuffer(kind);
  28290. vbs[kind] = vertexBuffer;
  28291. data[kind] = vbs[kind].getData();
  28292. newdata[kind] = [];
  28293. }
  28294. // Save previous submeshes
  28295. var previousSubmeshes = this.subMeshes.slice(0);
  28296. var indices = this.getIndices();
  28297. var totalIndices = this.getTotalIndices();
  28298. // Generating unique vertices per face
  28299. var index;
  28300. for (index = 0; index < totalIndices; index++) {
  28301. var vertexIndex = indices[index];
  28302. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28303. kind = kinds[kindIndex];
  28304. var stride = vbs[kind].getStrideSize();
  28305. for (var offset = 0; offset < stride; offset++) {
  28306. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  28307. }
  28308. }
  28309. }
  28310. // Updating indices
  28311. for (index = 0; index < totalIndices; index += 3) {
  28312. indices[index] = index;
  28313. indices[index + 1] = index + 1;
  28314. indices[index + 2] = index + 2;
  28315. }
  28316. this.setIndices(indices);
  28317. // Updating vertex buffers
  28318. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28319. kind = kinds[kindIndex];
  28320. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  28321. }
  28322. // Updating submeshes
  28323. this.releaseSubMeshes();
  28324. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  28325. var previousOne = previousSubmeshes[submeshIndex];
  28326. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  28327. }
  28328. this._unIndexed = true;
  28329. this.synchronizeInstances();
  28330. return this;
  28331. };
  28332. /**
  28333. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  28334. * This method returns the Mesh.
  28335. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  28336. */
  28337. Mesh.prototype.flipFaces = function (flipNormals) {
  28338. if (flipNormals === void 0) { flipNormals = false; }
  28339. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  28340. var i;
  28341. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  28342. for (i = 0; i < vertex_data.normals.length; i++) {
  28343. vertex_data.normals[i] *= -1;
  28344. }
  28345. }
  28346. if (vertex_data.indices) {
  28347. var temp;
  28348. for (i = 0; i < vertex_data.indices.length; i += 3) {
  28349. // reassign indices
  28350. temp = vertex_data.indices[i + 1];
  28351. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  28352. vertex_data.indices[i + 2] = temp;
  28353. }
  28354. }
  28355. vertex_data.applyToMesh(this);
  28356. return this;
  28357. };
  28358. // Instances
  28359. /**
  28360. * Creates a new InstancedMesh object from the mesh model.
  28361. * An instance shares the same properties and the same material than its model.
  28362. * Only these properties of each instance can then be set individually :
  28363. * - position
  28364. * - rotation
  28365. * - rotationQuaternion
  28366. * - setPivotMatrix
  28367. * - scaling
  28368. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  28369. * Warning : this method is not supported for Line mesh and LineSystem
  28370. */
  28371. Mesh.prototype.createInstance = function (name) {
  28372. return new BABYLON.InstancedMesh(name, this);
  28373. };
  28374. /**
  28375. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  28376. * After this call, all the mesh instances have the same submeshes than the current mesh.
  28377. * This method returns the Mesh.
  28378. */
  28379. Mesh.prototype.synchronizeInstances = function () {
  28380. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  28381. var instance = this.instances[instanceIndex];
  28382. instance._syncSubMeshes();
  28383. }
  28384. return this;
  28385. };
  28386. /**
  28387. * Simplify the mesh according to the given array of settings.
  28388. * Function will return immediately and will simplify async. It returns the Mesh.
  28389. * @param settings a collection of simplification settings.
  28390. * @param parallelProcessing should all levels calculate parallel or one after the other.
  28391. * @param type the type of simplification to run.
  28392. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  28393. */
  28394. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  28395. if (parallelProcessing === void 0) { parallelProcessing = true; }
  28396. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  28397. this.getScene().simplificationQueue.addTask({
  28398. settings: settings,
  28399. parallelProcessing: parallelProcessing,
  28400. mesh: this,
  28401. simplificationType: simplificationType,
  28402. successCallback: successCallback
  28403. });
  28404. return this;
  28405. };
  28406. /**
  28407. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  28408. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  28409. * This should be used together with the simplification to avoid disappearing triangles.
  28410. * Returns the Mesh.
  28411. * @param successCallback an optional success callback to be called after the optimization finished.
  28412. */
  28413. Mesh.prototype.optimizeIndices = function (successCallback) {
  28414. var _this = this;
  28415. var indices = this.getIndices();
  28416. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28417. if (!positions || !indices) {
  28418. return this;
  28419. }
  28420. var vectorPositions = new Array();
  28421. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  28422. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  28423. }
  28424. var dupes = new Array();
  28425. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  28426. var realPos = vectorPositions.length - 1 - iteration;
  28427. var testedPosition = vectorPositions[realPos];
  28428. for (var j = 0; j < realPos; ++j) {
  28429. var againstPosition = vectorPositions[j];
  28430. if (testedPosition.equals(againstPosition)) {
  28431. dupes[realPos] = j;
  28432. break;
  28433. }
  28434. }
  28435. }, function () {
  28436. for (var i = 0; i < indices.length; ++i) {
  28437. indices[i] = dupes[indices[i]] || indices[i];
  28438. }
  28439. //indices are now reordered
  28440. var originalSubMeshes = _this.subMeshes.slice(0);
  28441. _this.setIndices(indices);
  28442. _this.subMeshes = originalSubMeshes;
  28443. if (successCallback) {
  28444. successCallback(_this);
  28445. }
  28446. });
  28447. return this;
  28448. };
  28449. Mesh.prototype.serialize = function (serializationObject) {
  28450. serializationObject.name = this.name;
  28451. serializationObject.id = this.id;
  28452. serializationObject.type = this.getClassName();
  28453. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  28454. serializationObject.tags = BABYLON.Tags.GetTags(this);
  28455. }
  28456. serializationObject.position = this.position.asArray();
  28457. if (this.rotationQuaternion) {
  28458. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  28459. }
  28460. else if (this.rotation) {
  28461. serializationObject.rotation = this.rotation.asArray();
  28462. }
  28463. serializationObject.scaling = this.scaling.asArray();
  28464. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  28465. serializationObject.isEnabled = this.isEnabled(false);
  28466. serializationObject.isVisible = this.isVisible;
  28467. serializationObject.infiniteDistance = this.infiniteDistance;
  28468. serializationObject.pickable = this.isPickable;
  28469. serializationObject.receiveShadows = this.receiveShadows;
  28470. serializationObject.billboardMode = this.billboardMode;
  28471. serializationObject.visibility = this.visibility;
  28472. serializationObject.checkCollisions = this.checkCollisions;
  28473. serializationObject.isBlocker = this.isBlocker;
  28474. // Parent
  28475. if (this.parent) {
  28476. serializationObject.parentId = this.parent.id;
  28477. }
  28478. // Geometry
  28479. serializationObject.isUnIndexed = this.isUnIndexed;
  28480. var geometry = this._geometry;
  28481. if (geometry) {
  28482. var geometryId = geometry.id;
  28483. serializationObject.geometryId = geometryId;
  28484. // SubMeshes
  28485. serializationObject.subMeshes = [];
  28486. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  28487. var subMesh = this.subMeshes[subIndex];
  28488. serializationObject.subMeshes.push({
  28489. materialIndex: subMesh.materialIndex,
  28490. verticesStart: subMesh.verticesStart,
  28491. verticesCount: subMesh.verticesCount,
  28492. indexStart: subMesh.indexStart,
  28493. indexCount: subMesh.indexCount
  28494. });
  28495. }
  28496. }
  28497. // Material
  28498. if (this.material) {
  28499. serializationObject.materialId = this.material.id;
  28500. }
  28501. else {
  28502. this.material = null;
  28503. }
  28504. // Morph targets
  28505. if (this.morphTargetManager) {
  28506. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  28507. }
  28508. // Skeleton
  28509. if (this.skeleton) {
  28510. serializationObject.skeletonId = this.skeleton.id;
  28511. }
  28512. // Physics
  28513. //TODO implement correct serialization for physics impostors.
  28514. var impostor = this.getPhysicsImpostor();
  28515. if (impostor) {
  28516. serializationObject.physicsMass = impostor.getParam("mass");
  28517. serializationObject.physicsFriction = impostor.getParam("friction");
  28518. serializationObject.physicsRestitution = impostor.getParam("mass");
  28519. serializationObject.physicsImpostor = impostor.type;
  28520. }
  28521. // Metadata
  28522. if (this.metadata) {
  28523. serializationObject.metadata = this.metadata;
  28524. }
  28525. // Instances
  28526. serializationObject.instances = [];
  28527. for (var index = 0; index < this.instances.length; index++) {
  28528. var instance = this.instances[index];
  28529. var serializationInstance = {
  28530. name: instance.name,
  28531. id: instance.id,
  28532. position: instance.position.asArray(),
  28533. scaling: instance.scaling.asArray()
  28534. };
  28535. if (instance.rotationQuaternion) {
  28536. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  28537. }
  28538. else if (instance.rotation) {
  28539. serializationInstance.rotation = instance.rotation.asArray();
  28540. }
  28541. serializationObject.instances.push(serializationInstance);
  28542. // Animations
  28543. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  28544. serializationInstance.ranges = instance.serializeAnimationRanges();
  28545. }
  28546. //
  28547. // Animations
  28548. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  28549. serializationObject.ranges = this.serializeAnimationRanges();
  28550. // Layer mask
  28551. serializationObject.layerMask = this.layerMask;
  28552. // Alpha
  28553. serializationObject.alphaIndex = this.alphaIndex;
  28554. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  28555. // Overlay
  28556. serializationObject.overlayAlpha = this.overlayAlpha;
  28557. serializationObject.overlayColor = this.overlayColor.asArray();
  28558. serializationObject.renderOverlay = this.renderOverlay;
  28559. // Fog
  28560. serializationObject.applyFog = this.applyFog;
  28561. // Action Manager
  28562. if (this.actionManager) {
  28563. serializationObject.actions = this.actionManager.serialize(this.name);
  28564. }
  28565. };
  28566. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  28567. if (!this.geometry) {
  28568. return;
  28569. }
  28570. this._markSubMeshesAsAttributesDirty();
  28571. var morphTargetManager = this._morphTargetManager;
  28572. if (morphTargetManager && morphTargetManager.vertexCount) {
  28573. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  28574. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  28575. this.morphTargetManager = null;
  28576. return;
  28577. }
  28578. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  28579. var morphTarget = morphTargetManager.getActiveTarget(index);
  28580. var positions = morphTarget.getPositions();
  28581. if (!positions) {
  28582. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  28583. return;
  28584. }
  28585. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  28586. var normals = morphTarget.getNormals();
  28587. if (normals) {
  28588. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  28589. }
  28590. var tangents = morphTarget.getTangents();
  28591. if (tangents) {
  28592. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  28593. }
  28594. }
  28595. }
  28596. else {
  28597. var index = 0;
  28598. // Positions
  28599. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  28600. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  28601. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  28602. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  28603. }
  28604. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  28605. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  28606. }
  28607. index++;
  28608. }
  28609. }
  28610. };
  28611. // Statics
  28612. /**
  28613. * Returns a new Mesh object parsed from the source provided.
  28614. * The parameter `parsedMesh` is the source.
  28615. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  28616. */
  28617. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  28618. var mesh;
  28619. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  28620. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  28621. }
  28622. else {
  28623. mesh = new Mesh(parsedMesh.name, scene);
  28624. }
  28625. mesh.id = parsedMesh.id;
  28626. if (BABYLON.Tags) {
  28627. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  28628. }
  28629. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  28630. if (parsedMesh.metadata !== undefined) {
  28631. mesh.metadata = parsedMesh.metadata;
  28632. }
  28633. if (parsedMesh.rotationQuaternion) {
  28634. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  28635. }
  28636. else if (parsedMesh.rotation) {
  28637. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  28638. }
  28639. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  28640. if (parsedMesh.localMatrix) {
  28641. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  28642. }
  28643. else if (parsedMesh.pivotMatrix) {
  28644. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  28645. }
  28646. mesh.setEnabled(parsedMesh.isEnabled);
  28647. mesh.isVisible = parsedMesh.isVisible;
  28648. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  28649. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  28650. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  28651. if (parsedMesh.applyFog !== undefined) {
  28652. mesh.applyFog = parsedMesh.applyFog;
  28653. }
  28654. if (parsedMesh.pickable !== undefined) {
  28655. mesh.isPickable = parsedMesh.pickable;
  28656. }
  28657. if (parsedMesh.alphaIndex !== undefined) {
  28658. mesh.alphaIndex = parsedMesh.alphaIndex;
  28659. }
  28660. mesh.receiveShadows = parsedMesh.receiveShadows;
  28661. mesh.billboardMode = parsedMesh.billboardMode;
  28662. if (parsedMesh.visibility !== undefined) {
  28663. mesh.visibility = parsedMesh.visibility;
  28664. }
  28665. mesh.checkCollisions = parsedMesh.checkCollisions;
  28666. if (parsedMesh.isBlocker !== undefined) {
  28667. mesh.isBlocker = parsedMesh.isBlocker;
  28668. }
  28669. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  28670. // freezeWorldMatrix
  28671. if (parsedMesh.freezeWorldMatrix) {
  28672. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  28673. }
  28674. // Parent
  28675. if (parsedMesh.parentId) {
  28676. mesh._waitingParentId = parsedMesh.parentId;
  28677. }
  28678. // Actions
  28679. if (parsedMesh.actions !== undefined) {
  28680. mesh._waitingActions = parsedMesh.actions;
  28681. }
  28682. // Overlay
  28683. if (parsedMesh.overlayAlpha !== undefined) {
  28684. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  28685. }
  28686. if (parsedMesh.overlayColor !== undefined) {
  28687. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  28688. }
  28689. if (parsedMesh.renderOverlay !== undefined) {
  28690. mesh.renderOverlay = parsedMesh.renderOverlay;
  28691. }
  28692. // Geometry
  28693. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  28694. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  28695. if (parsedMesh.delayLoadingFile) {
  28696. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  28697. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  28698. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  28699. if (parsedMesh._binaryInfo) {
  28700. mesh._binaryInfo = parsedMesh._binaryInfo;
  28701. }
  28702. mesh._delayInfo = [];
  28703. if (parsedMesh.hasUVs) {
  28704. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  28705. }
  28706. if (parsedMesh.hasUVs2) {
  28707. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  28708. }
  28709. if (parsedMesh.hasUVs3) {
  28710. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  28711. }
  28712. if (parsedMesh.hasUVs4) {
  28713. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  28714. }
  28715. if (parsedMesh.hasUVs5) {
  28716. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  28717. }
  28718. if (parsedMesh.hasUVs6) {
  28719. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  28720. }
  28721. if (parsedMesh.hasColors) {
  28722. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  28723. }
  28724. if (parsedMesh.hasMatricesIndices) {
  28725. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  28726. }
  28727. if (parsedMesh.hasMatricesWeights) {
  28728. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  28729. }
  28730. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  28731. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  28732. mesh._checkDelayState();
  28733. }
  28734. }
  28735. else {
  28736. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  28737. }
  28738. // Material
  28739. if (parsedMesh.materialId) {
  28740. mesh.setMaterialByID(parsedMesh.materialId);
  28741. }
  28742. else {
  28743. mesh.material = null;
  28744. }
  28745. // Morph targets
  28746. if (parsedMesh.morphTargetManagerId > -1) {
  28747. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  28748. }
  28749. // Skeleton
  28750. if (parsedMesh.skeletonId > -1) {
  28751. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  28752. if (parsedMesh.numBoneInfluencers) {
  28753. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  28754. }
  28755. }
  28756. // Animations
  28757. if (parsedMesh.animations) {
  28758. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  28759. var parsedAnimation = parsedMesh.animations[animationIndex];
  28760. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  28761. }
  28762. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  28763. }
  28764. if (parsedMesh.autoAnimate) {
  28765. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  28766. }
  28767. // Layer Mask
  28768. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  28769. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  28770. }
  28771. else {
  28772. mesh.layerMask = 0x0FFFFFFF;
  28773. }
  28774. // Physics
  28775. if (parsedMesh.physicsImpostor) {
  28776. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  28777. mass: parsedMesh.physicsMass,
  28778. friction: parsedMesh.physicsFriction,
  28779. restitution: parsedMesh.physicsRestitution
  28780. }, scene);
  28781. }
  28782. // Instances
  28783. if (parsedMesh.instances) {
  28784. for (var index = 0; index < parsedMesh.instances.length; index++) {
  28785. var parsedInstance = parsedMesh.instances[index];
  28786. var instance = mesh.createInstance(parsedInstance.name);
  28787. if (parsedInstance.id) {
  28788. instance.id = parsedInstance.id;
  28789. }
  28790. if (BABYLON.Tags) {
  28791. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  28792. }
  28793. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  28794. if (parsedInstance.parentId) {
  28795. instance._waitingParentId = parsedInstance.parentId;
  28796. }
  28797. if (parsedInstance.rotationQuaternion) {
  28798. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  28799. }
  28800. else if (parsedInstance.rotation) {
  28801. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  28802. }
  28803. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  28804. instance.checkCollisions = mesh.checkCollisions;
  28805. if (parsedMesh.animations) {
  28806. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  28807. parsedAnimation = parsedMesh.animations[animationIndex];
  28808. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  28809. }
  28810. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  28811. }
  28812. }
  28813. }
  28814. return mesh;
  28815. };
  28816. /**
  28817. * Creates a ribbon mesh.
  28818. * Please consider using the same method from the MeshBuilder class instead.
  28819. * 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.
  28820. *
  28821. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  28822. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  28823. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  28824. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  28825. * 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.
  28826. * 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.
  28827. * 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
  28828. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28829. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28830. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28831. */
  28832. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  28833. if (closeArray === void 0) { closeArray = false; }
  28834. if (updatable === void 0) { updatable = false; }
  28835. return BABYLON.MeshBuilder.CreateRibbon(name, {
  28836. pathArray: pathArray,
  28837. closeArray: closeArray,
  28838. closePath: closePath,
  28839. offset: offset,
  28840. updatable: updatable,
  28841. sideOrientation: sideOrientation,
  28842. instance: instance
  28843. }, scene);
  28844. };
  28845. /**
  28846. * Creates a plane polygonal mesh. By default, this is a disc.
  28847. * Please consider using the same method from the MeshBuilder class instead.
  28848. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  28849. * 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.
  28850. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28851. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28852. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28853. */
  28854. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  28855. if (scene === void 0) { scene = null; }
  28856. var options = {
  28857. radius: radius,
  28858. tessellation: tessellation,
  28859. sideOrientation: sideOrientation,
  28860. updatable: updatable
  28861. };
  28862. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  28863. };
  28864. /**
  28865. * Creates a box mesh.
  28866. * Please consider using the same method from the MeshBuilder class instead.
  28867. * The parameter `size` sets the size (float) of each box side (default 1).
  28868. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28869. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28870. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28871. */
  28872. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  28873. if (scene === void 0) { scene = null; }
  28874. var options = {
  28875. size: size,
  28876. sideOrientation: sideOrientation,
  28877. updatable: updatable
  28878. };
  28879. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  28880. };
  28881. /**
  28882. * Creates a sphere mesh.
  28883. * Please consider using the same method from the MeshBuilder class instead.
  28884. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  28885. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  28886. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28887. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28888. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28889. */
  28890. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  28891. var options = {
  28892. segments: segments,
  28893. diameterX: diameter,
  28894. diameterY: diameter,
  28895. diameterZ: diameter,
  28896. sideOrientation: sideOrientation,
  28897. updatable: updatable
  28898. };
  28899. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  28900. };
  28901. /**
  28902. * Creates a cylinder or a cone mesh.
  28903. * Please consider using the same method from the MeshBuilder class instead.
  28904. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  28905. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  28906. * 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.
  28907. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  28908. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  28909. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28910. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28911. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28912. */
  28913. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  28914. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  28915. if (scene !== undefined) {
  28916. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  28917. updatable = scene;
  28918. }
  28919. scene = subdivisions;
  28920. subdivisions = 1;
  28921. }
  28922. var options = {
  28923. height: height,
  28924. diameterTop: diameterTop,
  28925. diameterBottom: diameterBottom,
  28926. tessellation: tessellation,
  28927. subdivisions: subdivisions,
  28928. sideOrientation: sideOrientation,
  28929. updatable: updatable
  28930. };
  28931. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  28932. };
  28933. // Torus (Code from SharpDX.org)
  28934. /**
  28935. * Creates a torus mesh.
  28936. * Please consider using the same method from the MeshBuilder class instead.
  28937. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  28938. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  28939. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  28940. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28941. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28942. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28943. */
  28944. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  28945. var options = {
  28946. diameter: diameter,
  28947. thickness: thickness,
  28948. tessellation: tessellation,
  28949. sideOrientation: sideOrientation,
  28950. updatable: updatable
  28951. };
  28952. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  28953. };
  28954. /**
  28955. * Creates a torus knot mesh.
  28956. * Please consider using the same method from the MeshBuilder class instead.
  28957. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  28958. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  28959. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  28960. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  28961. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28962. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28963. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28964. */
  28965. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  28966. var options = {
  28967. radius: radius,
  28968. tube: tube,
  28969. radialSegments: radialSegments,
  28970. tubularSegments: tubularSegments,
  28971. p: p,
  28972. q: q,
  28973. sideOrientation: sideOrientation,
  28974. updatable: updatable
  28975. };
  28976. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  28977. };
  28978. /**
  28979. * Creates a line mesh.
  28980. * Please consider using the same method from the MeshBuilder class instead.
  28981. * 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.
  28982. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  28983. * The parameter `points` is an array successive Vector3.
  28984. * 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
  28985. * When updating an instance, remember that only point positions can change, not the number of points.
  28986. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28987. */
  28988. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  28989. if (scene === void 0) { scene = null; }
  28990. if (updatable === void 0) { updatable = false; }
  28991. if (instance === void 0) { instance = null; }
  28992. var options = {
  28993. points: points,
  28994. updatable: updatable,
  28995. instance: instance
  28996. };
  28997. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  28998. };
  28999. /**
  29000. * Creates a dashed line mesh.
  29001. * Please consider using the same method from the MeshBuilder class instead.
  29002. * 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.
  29003. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  29004. * The parameter `points` is an array successive Vector3.
  29005. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  29006. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  29007. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  29008. * 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
  29009. * When updating an instance, remember that only point positions can change, not the number of points.
  29010. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29011. */
  29012. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  29013. if (scene === void 0) { scene = null; }
  29014. var options = {
  29015. points: points,
  29016. dashSize: dashSize,
  29017. gapSize: gapSize,
  29018. dashNb: dashNb,
  29019. updatable: updatable,
  29020. instance: instance
  29021. };
  29022. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  29023. };
  29024. /**
  29025. * Creates a polygon mesh.
  29026. * Please consider using the same method from the MeshBuilder class instead.
  29027. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  29028. * 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.
  29029. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29030. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29031. * Remember you can only change the shape positions, not their number when updating a polygon.
  29032. */
  29033. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  29034. var options = {
  29035. shape: shape,
  29036. holes: holes,
  29037. updatable: updatable,
  29038. sideOrientation: sideOrientation
  29039. };
  29040. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  29041. };
  29042. /**
  29043. * Creates an extruded polygon mesh, with depth in the Y direction.
  29044. * Please consider using the same method from the MeshBuilder class instead.
  29045. */
  29046. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  29047. var options = {
  29048. shape: shape,
  29049. holes: holes,
  29050. depth: depth,
  29051. updatable: updatable,
  29052. sideOrientation: sideOrientation
  29053. };
  29054. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  29055. };
  29056. /**
  29057. * Creates an extruded shape mesh.
  29058. * 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.
  29059. * Please consider using the same method from the MeshBuilder class instead.
  29060. *
  29061. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  29062. * 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
  29063. * extruded along the Z axis.
  29064. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  29065. * 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.
  29066. * The parameter `scale` (float, default 1) is the value to scale the shape.
  29067. * 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
  29068. * 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
  29069. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  29070. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29071. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29072. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29073. */
  29074. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  29075. if (scene === void 0) { scene = null; }
  29076. var options = {
  29077. shape: shape,
  29078. path: path,
  29079. scale: scale,
  29080. rotation: rotation,
  29081. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  29082. sideOrientation: sideOrientation,
  29083. instance: instance,
  29084. updatable: updatable
  29085. };
  29086. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  29087. };
  29088. /**
  29089. * Creates an custom extruded shape mesh.
  29090. * 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.
  29091. * Please consider using the same method from the MeshBuilder class instead.
  29092. *
  29093. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  29094. * 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
  29095. * extruded along the Z axis.
  29096. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  29097. * 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
  29098. * and the distance of this point from the begining of the path :
  29099. * ```javascript
  29100. * var rotationFunction = function(i, distance) {
  29101. * // do things
  29102. * return rotationValue; }
  29103. * ```
  29104. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  29105. * 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
  29106. * and the distance of this point from the begining of the path :
  29107. * ```javascript
  29108. * var scaleFunction = function(i, distance) {
  29109. * // do things
  29110. * return scaleValue;}
  29111. * ```
  29112. * It must returns a float value that will be the scale value applied to the shape on each path point.
  29113. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  29114. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  29115. * 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
  29116. * 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
  29117. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  29118. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29119. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29120. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29121. */
  29122. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  29123. var options = {
  29124. shape: shape,
  29125. path: path,
  29126. scaleFunction: scaleFunction,
  29127. rotationFunction: rotationFunction,
  29128. ribbonCloseArray: ribbonCloseArray,
  29129. ribbonClosePath: ribbonClosePath,
  29130. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  29131. sideOrientation: sideOrientation,
  29132. instance: instance,
  29133. updatable: updatable
  29134. };
  29135. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  29136. };
  29137. /**
  29138. * Creates lathe mesh.
  29139. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  29140. * Please consider using the same method from the MeshBuilder class instead.
  29141. * 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
  29142. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  29143. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  29144. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  29145. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29146. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29147. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29148. */
  29149. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  29150. var options = {
  29151. shape: shape,
  29152. radius: radius,
  29153. tessellation: tessellation,
  29154. sideOrientation: sideOrientation,
  29155. updatable: updatable
  29156. };
  29157. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  29158. };
  29159. /**
  29160. * Creates a plane mesh.
  29161. * Please consider using the same method from the MeshBuilder class instead.
  29162. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  29163. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29164. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29165. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29166. */
  29167. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  29168. var options = {
  29169. size: size,
  29170. width: size,
  29171. height: size,
  29172. sideOrientation: sideOrientation,
  29173. updatable: updatable
  29174. };
  29175. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  29176. };
  29177. /**
  29178. * Creates a ground mesh.
  29179. * Please consider using the same method from the MeshBuilder class instead.
  29180. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  29181. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  29182. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29183. */
  29184. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  29185. var options = {
  29186. width: width,
  29187. height: height,
  29188. subdivisions: subdivisions,
  29189. updatable: updatable
  29190. };
  29191. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  29192. };
  29193. /**
  29194. * Creates a tiled ground mesh.
  29195. * Please consider using the same method from the MeshBuilder class instead.
  29196. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  29197. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  29198. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  29199. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  29200. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  29201. * numbers of subdivisions on the ground width and height of each tile.
  29202. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29203. */
  29204. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  29205. var options = {
  29206. xmin: xmin,
  29207. zmin: zmin,
  29208. xmax: xmax,
  29209. zmax: zmax,
  29210. subdivisions: subdivisions,
  29211. precision: precision,
  29212. updatable: updatable
  29213. };
  29214. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  29215. };
  29216. /**
  29217. * Creates a ground mesh from a height map.
  29218. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  29219. * Please consider using the same method from the MeshBuilder class instead.
  29220. * The parameter `url` sets the URL of the height map image resource.
  29221. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  29222. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  29223. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  29224. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  29225. * 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).
  29226. * This function is passed the newly built mesh :
  29227. * ```javascript
  29228. * function(mesh) { // do things
  29229. * return; }
  29230. * ```
  29231. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29232. */
  29233. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  29234. var options = {
  29235. width: width,
  29236. height: height,
  29237. subdivisions: subdivisions,
  29238. minHeight: minHeight,
  29239. maxHeight: maxHeight,
  29240. updatable: updatable,
  29241. onReady: onReady
  29242. };
  29243. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  29244. };
  29245. /**
  29246. * Creates a tube mesh.
  29247. * 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.
  29248. * Please consider using the same method from the MeshBuilder class instead.
  29249. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  29250. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  29251. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  29252. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  29253. * 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.
  29254. * It must return a radius value (positive float) :
  29255. * ```javascript
  29256. * var radiusFunction = function(i, distance) {
  29257. * // do things
  29258. * return radius; }
  29259. * ```
  29260. * 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
  29261. * 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
  29262. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29263. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29264. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29265. */
  29266. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  29267. var options = {
  29268. path: path,
  29269. radius: radius,
  29270. tessellation: tessellation,
  29271. radiusFunction: radiusFunction,
  29272. arc: 1,
  29273. cap: cap,
  29274. updatable: updatable,
  29275. sideOrientation: sideOrientation,
  29276. instance: instance
  29277. };
  29278. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  29279. };
  29280. /**
  29281. * Creates a polyhedron mesh.
  29282. * Please consider using the same method from the MeshBuilder class instead.
  29283. * 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
  29284. * to choose the wanted type.
  29285. * The parameter `size` (positive float, default 1) sets the polygon size.
  29286. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  29287. * 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`.
  29288. * 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
  29289. * 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)`).
  29290. * 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
  29291. * 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.
  29292. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29293. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29294. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29295. */
  29296. Mesh.CreatePolyhedron = function (name, options, scene) {
  29297. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  29298. };
  29299. /**
  29300. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  29301. * Please consider using the same method from the MeshBuilder class instead.
  29302. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  29303. * 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`).
  29304. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  29305. * 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.
  29306. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29307. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29308. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29309. */
  29310. Mesh.CreateIcoSphere = function (name, options, scene) {
  29311. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  29312. };
  29313. /**
  29314. * Creates a decal mesh.
  29315. * Please consider using the same method from the MeshBuilder class instead.
  29316. * 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.
  29317. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  29318. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  29319. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  29320. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  29321. */
  29322. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  29323. var options = {
  29324. position: position,
  29325. normal: normal,
  29326. size: size,
  29327. angle: angle
  29328. };
  29329. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  29330. };
  29331. // Skeletons
  29332. /**
  29333. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  29334. */
  29335. Mesh.prototype.setPositionsForCPUSkinning = function () {
  29336. if (!this._sourcePositions) {
  29337. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29338. if (!source) {
  29339. return this._sourcePositions;
  29340. }
  29341. this._sourcePositions = new Float32Array(source);
  29342. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  29343. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  29344. }
  29345. }
  29346. return this._sourcePositions;
  29347. };
  29348. /**
  29349. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  29350. */
  29351. Mesh.prototype.setNormalsForCPUSkinning = function () {
  29352. if (!this._sourceNormals) {
  29353. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  29354. if (!source) {
  29355. return this._sourceNormals;
  29356. }
  29357. this._sourceNormals = new Float32Array(source);
  29358. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  29359. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  29360. }
  29361. }
  29362. return this._sourceNormals;
  29363. };
  29364. /**
  29365. * Updates the vertex buffer by applying transformation from the bones.
  29366. * Returns the Mesh.
  29367. *
  29368. * @param {skeleton} skeleton to apply
  29369. */
  29370. Mesh.prototype.applySkeleton = function (skeleton) {
  29371. if (!this.geometry) {
  29372. return this;
  29373. }
  29374. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  29375. return this;
  29376. }
  29377. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  29378. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  29379. return this;
  29380. }
  29381. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  29382. return this;
  29383. }
  29384. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  29385. return this;
  29386. }
  29387. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  29388. return this;
  29389. }
  29390. if (!this._sourcePositions) {
  29391. var submeshes = this.subMeshes.slice();
  29392. this.setPositionsForCPUSkinning();
  29393. this.subMeshes = submeshes;
  29394. }
  29395. if (!this._sourceNormals) {
  29396. this.setNormalsForCPUSkinning();
  29397. }
  29398. // positionsData checks for not being Float32Array will only pass at most once
  29399. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29400. if (!positionsData) {
  29401. return this;
  29402. }
  29403. if (!(positionsData instanceof Float32Array)) {
  29404. positionsData = new Float32Array(positionsData);
  29405. }
  29406. // normalsData checks for not being Float32Array will only pass at most once
  29407. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  29408. if (!normalsData) {
  29409. return this;
  29410. }
  29411. if (!(normalsData instanceof Float32Array)) {
  29412. normalsData = new Float32Array(normalsData);
  29413. }
  29414. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  29415. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  29416. if (!matricesWeightsData || !matricesIndicesData) {
  29417. return this;
  29418. }
  29419. var needExtras = this.numBoneInfluencers > 4;
  29420. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  29421. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  29422. var skeletonMatrices = skeleton.getTransformMatrices(this);
  29423. var tempVector3 = BABYLON.Vector3.Zero();
  29424. var finalMatrix = new BABYLON.Matrix();
  29425. var tempMatrix = new BABYLON.Matrix();
  29426. var matWeightIdx = 0;
  29427. var inf;
  29428. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  29429. var weight;
  29430. for (inf = 0; inf < 4; inf++) {
  29431. weight = matricesWeightsData[matWeightIdx + inf];
  29432. if (weight > 0) {
  29433. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  29434. finalMatrix.addToSelf(tempMatrix);
  29435. }
  29436. else
  29437. break;
  29438. }
  29439. if (needExtras) {
  29440. for (inf = 0; inf < 4; inf++) {
  29441. weight = matricesWeightsExtraData[matWeightIdx + inf];
  29442. if (weight > 0) {
  29443. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  29444. finalMatrix.addToSelf(tempMatrix);
  29445. }
  29446. else
  29447. break;
  29448. }
  29449. }
  29450. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  29451. tempVector3.toArray(positionsData, index);
  29452. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  29453. tempVector3.toArray(normalsData, index);
  29454. finalMatrix.reset();
  29455. }
  29456. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  29457. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  29458. return this;
  29459. };
  29460. // Tools
  29461. /**
  29462. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  29463. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  29464. */
  29465. Mesh.MinMax = function (meshes) {
  29466. var minVector = null;
  29467. var maxVector = null;
  29468. meshes.forEach(function (mesh, index, array) {
  29469. var boundingInfo = mesh.getBoundingInfo();
  29470. var boundingBox = boundingInfo.boundingBox;
  29471. if (!minVector || !maxVector) {
  29472. minVector = boundingBox.minimumWorld;
  29473. maxVector = boundingBox.maximumWorld;
  29474. }
  29475. else {
  29476. minVector.minimizeInPlace(boundingBox.minimumWorld);
  29477. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  29478. }
  29479. });
  29480. if (!minVector || !maxVector) {
  29481. return {
  29482. min: BABYLON.Vector3.Zero(),
  29483. max: BABYLON.Vector3.Zero()
  29484. };
  29485. }
  29486. return {
  29487. min: minVector,
  29488. max: maxVector
  29489. };
  29490. };
  29491. /**
  29492. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  29493. */
  29494. Mesh.Center = function (meshesOrMinMaxVector) {
  29495. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  29496. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  29497. };
  29498. /**
  29499. * Merge the array of meshes into a single mesh for performance reasons.
  29500. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  29501. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  29502. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  29503. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  29504. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  29505. */
  29506. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  29507. if (disposeSource === void 0) { disposeSource = true; }
  29508. var index;
  29509. if (!allow32BitsIndices) {
  29510. var totalVertices = 0;
  29511. // Counting vertices
  29512. for (index = 0; index < meshes.length; index++) {
  29513. if (meshes[index]) {
  29514. totalVertices += meshes[index].getTotalVertices();
  29515. if (totalVertices > 65536) {
  29516. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  29517. return null;
  29518. }
  29519. }
  29520. }
  29521. }
  29522. // Merge
  29523. var vertexData = null;
  29524. var otherVertexData;
  29525. var indiceArray = new Array();
  29526. var source = null;
  29527. for (index = 0; index < meshes.length; index++) {
  29528. if (meshes[index]) {
  29529. meshes[index].computeWorldMatrix(true);
  29530. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  29531. otherVertexData.transform(meshes[index].getWorldMatrix());
  29532. if (vertexData) {
  29533. vertexData.merge(otherVertexData);
  29534. }
  29535. else {
  29536. vertexData = otherVertexData;
  29537. source = meshes[index];
  29538. }
  29539. if (subdivideWithSubMeshes) {
  29540. indiceArray.push(meshes[index].getTotalIndices());
  29541. }
  29542. }
  29543. }
  29544. source = source;
  29545. if (!meshSubclass) {
  29546. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  29547. }
  29548. vertexData.applyToMesh(meshSubclass);
  29549. // Setting properties
  29550. meshSubclass.material = source.material;
  29551. meshSubclass.checkCollisions = source.checkCollisions;
  29552. // Cleaning
  29553. if (disposeSource) {
  29554. for (index = 0; index < meshes.length; index++) {
  29555. if (meshes[index]) {
  29556. meshes[index].dispose();
  29557. }
  29558. }
  29559. }
  29560. // Subdivide
  29561. if (subdivideWithSubMeshes) {
  29562. //-- Suppresions du submesh global
  29563. meshSubclass.releaseSubMeshes();
  29564. index = 0;
  29565. var offset = 0;
  29566. //-- aplique la subdivision en fonction du tableau d'indices
  29567. while (index < indiceArray.length) {
  29568. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  29569. offset += indiceArray[index];
  29570. index++;
  29571. }
  29572. }
  29573. return meshSubclass;
  29574. };
  29575. // Consts
  29576. Mesh._FRONTSIDE = 0;
  29577. Mesh._BACKSIDE = 1;
  29578. Mesh._DOUBLESIDE = 2;
  29579. Mesh._DEFAULTSIDE = 0;
  29580. Mesh._NO_CAP = 0;
  29581. Mesh._CAP_START = 1;
  29582. Mesh._CAP_END = 2;
  29583. Mesh._CAP_ALL = 3;
  29584. return Mesh;
  29585. }(BABYLON.AbstractMesh));
  29586. BABYLON.Mesh = Mesh;
  29587. })(BABYLON || (BABYLON = {}));
  29588. //# sourceMappingURL=babylon.mesh.js.map
  29589. var BABYLON;
  29590. (function (BABYLON) {
  29591. var BaseSubMesh = /** @class */ (function () {
  29592. function BaseSubMesh() {
  29593. }
  29594. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  29595. get: function () {
  29596. return this._materialEffect;
  29597. },
  29598. enumerable: true,
  29599. configurable: true
  29600. });
  29601. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  29602. if (defines === void 0) { defines = null; }
  29603. if (this._materialEffect === effect) {
  29604. if (!effect) {
  29605. this._materialDefines = null;
  29606. }
  29607. return;
  29608. }
  29609. this._materialDefines = defines;
  29610. this._materialEffect = effect;
  29611. };
  29612. return BaseSubMesh;
  29613. }());
  29614. BABYLON.BaseSubMesh = BaseSubMesh;
  29615. var SubMesh = /** @class */ (function (_super) {
  29616. __extends(SubMesh, _super);
  29617. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  29618. if (createBoundingBox === void 0) { createBoundingBox = true; }
  29619. var _this = _super.call(this) || this;
  29620. _this.materialIndex = materialIndex;
  29621. _this.verticesStart = verticesStart;
  29622. _this.verticesCount = verticesCount;
  29623. _this.indexStart = indexStart;
  29624. _this.indexCount = indexCount;
  29625. _this._renderId = 0;
  29626. _this._mesh = mesh;
  29627. _this._renderingMesh = renderingMesh || mesh;
  29628. mesh.subMeshes.push(_this);
  29629. _this._trianglePlanes = [];
  29630. _this._id = mesh.subMeshes.length - 1;
  29631. if (createBoundingBox) {
  29632. _this.refreshBoundingInfo();
  29633. mesh.computeWorldMatrix(true);
  29634. }
  29635. return _this;
  29636. }
  29637. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  29638. if (createBoundingBox === void 0) { createBoundingBox = true; }
  29639. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  29640. };
  29641. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  29642. get: function () {
  29643. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  29644. },
  29645. enumerable: true,
  29646. configurable: true
  29647. });
  29648. /**
  29649. * Returns the submesh BoudingInfo object.
  29650. */
  29651. SubMesh.prototype.getBoundingInfo = function () {
  29652. if (this.IsGlobal) {
  29653. return this._mesh.getBoundingInfo();
  29654. }
  29655. return this._boundingInfo;
  29656. };
  29657. /**
  29658. * Sets the submesh BoundingInfo.
  29659. * Return the SubMesh.
  29660. */
  29661. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  29662. this._boundingInfo = boundingInfo;
  29663. return this;
  29664. };
  29665. /**
  29666. * Returns the mesh of the current submesh.
  29667. */
  29668. SubMesh.prototype.getMesh = function () {
  29669. return this._mesh;
  29670. };
  29671. /**
  29672. * Returns the rendering mesh of the submesh.
  29673. */
  29674. SubMesh.prototype.getRenderingMesh = function () {
  29675. return this._renderingMesh;
  29676. };
  29677. /**
  29678. * Returns the submesh material.
  29679. */
  29680. SubMesh.prototype.getMaterial = function () {
  29681. var rootMaterial = this._renderingMesh.material;
  29682. if (rootMaterial === null || rootMaterial === undefined) {
  29683. return this._mesh.getScene().defaultMaterial;
  29684. }
  29685. else if (rootMaterial.getSubMaterial) {
  29686. var multiMaterial = rootMaterial;
  29687. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  29688. if (this._currentMaterial !== effectiveMaterial) {
  29689. this._currentMaterial = effectiveMaterial;
  29690. this._materialDefines = null;
  29691. }
  29692. return effectiveMaterial;
  29693. }
  29694. return rootMaterial;
  29695. };
  29696. // Methods
  29697. /**
  29698. * Sets a new updated BoundingInfo object to the submesh.
  29699. * Returns the SubMesh.
  29700. */
  29701. SubMesh.prototype.refreshBoundingInfo = function () {
  29702. this._lastColliderWorldVertices = null;
  29703. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  29704. return this;
  29705. }
  29706. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29707. if (!data) {
  29708. this._boundingInfo = this._mesh.getBoundingInfo();
  29709. return this;
  29710. }
  29711. var indices = this._renderingMesh.getIndices();
  29712. var extend;
  29713. //is this the only submesh?
  29714. if (this.indexStart === 0 && this.indexCount === indices.length) {
  29715. var boundingInfo = this._renderingMesh.getBoundingInfo();
  29716. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  29717. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  29718. }
  29719. else {
  29720. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  29721. }
  29722. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  29723. return this;
  29724. };
  29725. SubMesh.prototype._checkCollision = function (collider) {
  29726. var boundingInfo = this._renderingMesh.getBoundingInfo();
  29727. return boundingInfo._checkCollision(collider);
  29728. };
  29729. /**
  29730. * Updates the submesh BoundingInfo.
  29731. * Returns the Submesh.
  29732. */
  29733. SubMesh.prototype.updateBoundingInfo = function (world) {
  29734. var boundingInfo = this.getBoundingInfo();
  29735. if (!boundingInfo) {
  29736. this.refreshBoundingInfo();
  29737. boundingInfo = this.getBoundingInfo();
  29738. }
  29739. boundingInfo.update(world);
  29740. return this;
  29741. };
  29742. /**
  29743. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  29744. * Boolean returned.
  29745. */
  29746. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  29747. var boundingInfo = this.getBoundingInfo();
  29748. if (!boundingInfo) {
  29749. return false;
  29750. }
  29751. return boundingInfo.isInFrustum(frustumPlanes);
  29752. };
  29753. /**
  29754. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  29755. * Boolean returned.
  29756. */
  29757. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  29758. var boundingInfo = this.getBoundingInfo();
  29759. if (!boundingInfo) {
  29760. return false;
  29761. }
  29762. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  29763. };
  29764. /**
  29765. * Renders the submesh.
  29766. * Returns it.
  29767. */
  29768. SubMesh.prototype.render = function (enableAlphaMode) {
  29769. this._renderingMesh.render(this, enableAlphaMode);
  29770. return this;
  29771. };
  29772. /**
  29773. * Returns a new Index Buffer.
  29774. * Type returned : WebGLBuffer.
  29775. */
  29776. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  29777. if (!this._linesIndexBuffer) {
  29778. var linesIndices = [];
  29779. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  29780. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  29781. }
  29782. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  29783. this.linesIndexCount = linesIndices.length;
  29784. }
  29785. return this._linesIndexBuffer;
  29786. };
  29787. /**
  29788. * True is the passed Ray intersects the submesh bounding box.
  29789. * Boolean returned.
  29790. */
  29791. SubMesh.prototype.canIntersects = function (ray) {
  29792. var boundingInfo = this.getBoundingInfo();
  29793. if (!boundingInfo) {
  29794. return false;
  29795. }
  29796. return ray.intersectsBox(boundingInfo.boundingBox);
  29797. };
  29798. /**
  29799. * Returns an object IntersectionInfo.
  29800. */
  29801. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  29802. var intersectInfo = null;
  29803. // LineMesh first as it's also a Mesh...
  29804. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  29805. var lineMesh = this._mesh;
  29806. // Line test
  29807. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  29808. var p0 = positions[indices[index]];
  29809. var p1 = positions[indices[index + 1]];
  29810. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  29811. if (length < 0) {
  29812. continue;
  29813. }
  29814. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  29815. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  29816. if (fastCheck) {
  29817. break;
  29818. }
  29819. }
  29820. }
  29821. }
  29822. else {
  29823. // Triangles test
  29824. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  29825. var p0 = positions[indices[index]];
  29826. var p1 = positions[indices[index + 1]];
  29827. var p2 = positions[indices[index + 2]];
  29828. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  29829. if (currentIntersectInfo) {
  29830. if (currentIntersectInfo.distance < 0) {
  29831. continue;
  29832. }
  29833. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  29834. intersectInfo = currentIntersectInfo;
  29835. intersectInfo.faceId = index / 3;
  29836. if (fastCheck) {
  29837. break;
  29838. }
  29839. }
  29840. }
  29841. }
  29842. }
  29843. return intersectInfo;
  29844. };
  29845. SubMesh.prototype._rebuild = function () {
  29846. if (this._linesIndexBuffer) {
  29847. this._linesIndexBuffer = null;
  29848. }
  29849. };
  29850. // Clone
  29851. /**
  29852. * Creates a new Submesh from the passed Mesh.
  29853. */
  29854. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  29855. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  29856. if (!this.IsGlobal) {
  29857. var boundingInfo = this.getBoundingInfo();
  29858. if (!boundingInfo) {
  29859. return result;
  29860. }
  29861. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  29862. }
  29863. return result;
  29864. };
  29865. // Dispose
  29866. /**
  29867. * Disposes the Submesh.
  29868. * Returns nothing.
  29869. */
  29870. SubMesh.prototype.dispose = function () {
  29871. if (this._linesIndexBuffer) {
  29872. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  29873. this._linesIndexBuffer = null;
  29874. }
  29875. // Remove from mesh
  29876. var index = this._mesh.subMeshes.indexOf(this);
  29877. this._mesh.subMeshes.splice(index, 1);
  29878. };
  29879. // Statics
  29880. /**
  29881. * Creates a new Submesh from the passed parameters :
  29882. * - materialIndex (integer) : the index of the main mesh material.
  29883. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  29884. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  29885. * - mesh (Mesh) : the main mesh to create the submesh from.
  29886. * - renderingMesh (optional Mesh) : rendering mesh.
  29887. */
  29888. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  29889. var minVertexIndex = Number.MAX_VALUE;
  29890. var maxVertexIndex = -Number.MAX_VALUE;
  29891. renderingMesh = (renderingMesh || mesh);
  29892. var indices = renderingMesh.getIndices();
  29893. for (var index = startIndex; index < startIndex + indexCount; index++) {
  29894. var vertexIndex = indices[index];
  29895. if (vertexIndex < minVertexIndex)
  29896. minVertexIndex = vertexIndex;
  29897. if (vertexIndex > maxVertexIndex)
  29898. maxVertexIndex = vertexIndex;
  29899. }
  29900. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  29901. };
  29902. return SubMesh;
  29903. }(BaseSubMesh));
  29904. BABYLON.SubMesh = SubMesh;
  29905. })(BABYLON || (BABYLON = {}));
  29906. //# sourceMappingURL=babylon.subMesh.js.map
  29907. var __assign = (this && this.__assign) || Object.assign || function(t) {
  29908. for (var s, i = 1, n = arguments.length; i < n; i++) {
  29909. s = arguments[i];
  29910. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  29911. t[p] = s[p];
  29912. }
  29913. return t;
  29914. };
  29915. var BABYLON;
  29916. (function (BABYLON) {
  29917. /**
  29918. * Manages the defines for the Material.
  29919. */
  29920. var MaterialDefines = /** @class */ (function () {
  29921. function MaterialDefines() {
  29922. this._isDirty = true;
  29923. this._areLightsDirty = true;
  29924. this._areAttributesDirty = true;
  29925. this._areTexturesDirty = true;
  29926. this._areFresnelDirty = true;
  29927. this._areMiscDirty = true;
  29928. this._areImageProcessingDirty = true;
  29929. this._normals = false;
  29930. this._uvs = false;
  29931. this._needNormals = false;
  29932. this._needUVs = false;
  29933. }
  29934. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  29935. /**
  29936. * Specifies if the material needs to be re-calculated.
  29937. */
  29938. get: function () {
  29939. return this._isDirty;
  29940. },
  29941. enumerable: true,
  29942. configurable: true
  29943. });
  29944. /**
  29945. * Marks the material to indicate that it has been re-calculated.
  29946. */
  29947. MaterialDefines.prototype.markAsProcessed = function () {
  29948. this._isDirty = false;
  29949. this._areAttributesDirty = false;
  29950. this._areTexturesDirty = false;
  29951. this._areFresnelDirty = false;
  29952. this._areLightsDirty = false;
  29953. this._areMiscDirty = false;
  29954. this._areImageProcessingDirty = false;
  29955. };
  29956. /**
  29957. * Marks the material to indicate that it needs to be re-calculated.
  29958. */
  29959. MaterialDefines.prototype.markAsUnprocessed = function () {
  29960. this._isDirty = true;
  29961. };
  29962. /**
  29963. * Marks the material to indicate all of its defines need to be re-calculated.
  29964. */
  29965. MaterialDefines.prototype.markAllAsDirty = function () {
  29966. this._areTexturesDirty = true;
  29967. this._areAttributesDirty = true;
  29968. this._areLightsDirty = true;
  29969. this._areFresnelDirty = true;
  29970. this._areMiscDirty = true;
  29971. this._areImageProcessingDirty = true;
  29972. this._isDirty = true;
  29973. };
  29974. /**
  29975. * Marks the material to indicate that image processing needs to be re-calculated.
  29976. */
  29977. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  29978. this._areImageProcessingDirty = true;
  29979. this._isDirty = true;
  29980. };
  29981. /**
  29982. * Marks the material to indicate the lights need to be re-calculated.
  29983. */
  29984. MaterialDefines.prototype.markAsLightDirty = function () {
  29985. this._areLightsDirty = true;
  29986. this._isDirty = true;
  29987. };
  29988. /**
  29989. * Marks the attribute state as changed.
  29990. */
  29991. MaterialDefines.prototype.markAsAttributesDirty = function () {
  29992. this._areAttributesDirty = true;
  29993. this._isDirty = true;
  29994. };
  29995. /**
  29996. * Marks the texture state as changed.
  29997. */
  29998. MaterialDefines.prototype.markAsTexturesDirty = function () {
  29999. this._areTexturesDirty = true;
  30000. this._isDirty = true;
  30001. };
  30002. /**
  30003. * Marks the fresnel state as changed.
  30004. */
  30005. MaterialDefines.prototype.markAsFresnelDirty = function () {
  30006. this._areFresnelDirty = true;
  30007. this._isDirty = true;
  30008. };
  30009. /**
  30010. * Marks the misc state as changed.
  30011. */
  30012. MaterialDefines.prototype.markAsMiscDirty = function () {
  30013. this._areMiscDirty = true;
  30014. this._isDirty = true;
  30015. };
  30016. /**
  30017. * Rebuilds the material defines.
  30018. */
  30019. MaterialDefines.prototype.rebuild = function () {
  30020. if (this._keys) {
  30021. delete this._keys;
  30022. }
  30023. this._keys = [];
  30024. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  30025. var key = _a[_i];
  30026. if (key[0] === "_") {
  30027. continue;
  30028. }
  30029. this._keys.push(key);
  30030. }
  30031. };
  30032. /**
  30033. * Specifies if two material defines are equal.
  30034. * @param other - A material define instance to compare to.
  30035. * @returns - Boolean indicating if the material defines are equal (true) or not (false).
  30036. */
  30037. MaterialDefines.prototype.isEqual = function (other) {
  30038. if (this._keys.length !== other._keys.length) {
  30039. return false;
  30040. }
  30041. for (var index = 0; index < this._keys.length; index++) {
  30042. var prop = this._keys[index];
  30043. if (this[prop] !== other[prop]) {
  30044. return false;
  30045. }
  30046. }
  30047. return true;
  30048. };
  30049. /**
  30050. * Clones this instance's defines to another instance.
  30051. * @param other - material defines to clone values to.
  30052. */
  30053. MaterialDefines.prototype.cloneTo = function (other) {
  30054. if (this._keys.length !== other._keys.length) {
  30055. other._keys = this._keys.slice(0);
  30056. }
  30057. for (var index = 0; index < this._keys.length; index++) {
  30058. var prop = this._keys[index];
  30059. other[prop] = this[prop];
  30060. }
  30061. };
  30062. /**
  30063. * Resets the material define values.
  30064. */
  30065. MaterialDefines.prototype.reset = function () {
  30066. for (var index = 0; index < this._keys.length; index++) {
  30067. var prop = this._keys[index];
  30068. if (typeof (this[prop]) === "number") {
  30069. this[prop] = 0;
  30070. }
  30071. else {
  30072. this[prop] = false;
  30073. }
  30074. }
  30075. };
  30076. /**
  30077. * Converts the material define values to a string.
  30078. * @returns - String of material define information.
  30079. */
  30080. MaterialDefines.prototype.toString = function () {
  30081. var result = "";
  30082. for (var index = 0; index < this._keys.length; index++) {
  30083. var prop = this._keys[index];
  30084. var value = this[prop];
  30085. if (typeof (value) === "number") {
  30086. result += "#define " + prop + " " + this[prop] + "\n";
  30087. }
  30088. else if (value) {
  30089. result += "#define " + prop + "\n";
  30090. }
  30091. }
  30092. return result;
  30093. };
  30094. return MaterialDefines;
  30095. }());
  30096. BABYLON.MaterialDefines = MaterialDefines;
  30097. /**
  30098. * This offers the main features of a material in BJS.
  30099. */
  30100. var Material = /** @class */ (function () {
  30101. /**
  30102. * Creates a material instance.
  30103. * @param name - The name of the material.
  30104. * @param scene - The BJS scene to reference.
  30105. * @param doNotAdd - Specifies if the material should be added to the scene.
  30106. */
  30107. function Material(name, scene, doNotAdd) {
  30108. /**
  30109. * Specifies if the ready state should be checked on each call.
  30110. */
  30111. this.checkReadyOnEveryCall = false;
  30112. /**
  30113. * Specifies if the ready state should be checked once.
  30114. */
  30115. this.checkReadyOnlyOnce = false;
  30116. /**
  30117. * The state of the material.
  30118. */
  30119. this.state = "";
  30120. /**
  30121. * The alpha value of the material.
  30122. */
  30123. this._alpha = 1.0;
  30124. /**
  30125. * Specifies if back face culling is enabled.
  30126. */
  30127. this._backFaceCulling = true;
  30128. /**
  30129. * Specifies if the material should be serialized.
  30130. */
  30131. this.doNotSerialize = false;
  30132. /**
  30133. * Specifies if the effect should be stored on sub meshes.
  30134. */
  30135. this.storeEffectOnSubMeshes = false;
  30136. /**
  30137. * An event triggered when the material is disposed.
  30138. * @type {BABYLON.Observable}
  30139. */
  30140. this.onDisposeObservable = new BABYLON.Observable();
  30141. /**
  30142. * An event triggered when the material is bound.
  30143. * @type {BABYLON.Observable}
  30144. */
  30145. this.onBindObservable = new BABYLON.Observable();
  30146. /**
  30147. * An event triggered when the material is unbound.
  30148. * @type {BABYLON.Observable}
  30149. */
  30150. this.onUnBindObservable = new BABYLON.Observable();
  30151. /**
  30152. * Stores the value of the alpha mode.
  30153. */
  30154. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  30155. /**
  30156. * Stores the state of the need depth pre-pass value.
  30157. */
  30158. this._needDepthPrePass = false;
  30159. /**
  30160. * Specifies if depth writing should be disabled.
  30161. */
  30162. this.disableDepthWrite = false;
  30163. /**
  30164. * Specifies if depth writing should be forced.
  30165. */
  30166. this.forceDepthWrite = false;
  30167. /**
  30168. * Specifies if there should be a separate pass for culling.
  30169. */
  30170. this.separateCullingPass = false;
  30171. /**
  30172. * Stores the state specifing if fog should be enabled.
  30173. */
  30174. this._fogEnabled = true;
  30175. /**
  30176. * Stores the size of points.
  30177. */
  30178. this.pointSize = 1.0;
  30179. /**
  30180. * Stores the z offset value.
  30181. */
  30182. this.zOffset = 0;
  30183. /**
  30184. * Specifies if the material was previously ready.
  30185. */
  30186. this._wasPreviouslyReady = false;
  30187. /**
  30188. * Stores the fill mode state.
  30189. */
  30190. this._fillMode = Material.TriangleFillMode;
  30191. this.name = name;
  30192. this.id = name || BABYLON.Tools.RandomId();
  30193. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  30194. if (this._scene.useRightHandedSystem) {
  30195. this.sideOrientation = Material.ClockWiseSideOrientation;
  30196. }
  30197. else {
  30198. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  30199. }
  30200. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  30201. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  30202. if (!doNotAdd) {
  30203. this._scene.materials.push(this);
  30204. }
  30205. }
  30206. Object.defineProperty(Material, "TriangleFillMode", {
  30207. /**
  30208. * Returns the triangle fill mode.
  30209. */
  30210. get: function () {
  30211. return Material._TriangleFillMode;
  30212. },
  30213. enumerable: true,
  30214. configurable: true
  30215. });
  30216. Object.defineProperty(Material, "WireFrameFillMode", {
  30217. /**
  30218. * Returns the wireframe mode.
  30219. */
  30220. get: function () {
  30221. return Material._WireFrameFillMode;
  30222. },
  30223. enumerable: true,
  30224. configurable: true
  30225. });
  30226. Object.defineProperty(Material, "PointFillMode", {
  30227. /**
  30228. * Returns the point fill mode.
  30229. */
  30230. get: function () {
  30231. return Material._PointFillMode;
  30232. },
  30233. enumerable: true,
  30234. configurable: true
  30235. });
  30236. Object.defineProperty(Material, "PointListDrawMode", {
  30237. /**
  30238. * Returns the point list draw mode.
  30239. */
  30240. get: function () {
  30241. return Material._PointListDrawMode;
  30242. },
  30243. enumerable: true,
  30244. configurable: true
  30245. });
  30246. Object.defineProperty(Material, "LineListDrawMode", {
  30247. /**
  30248. * Returns the line list draw mode.
  30249. */
  30250. get: function () {
  30251. return Material._LineListDrawMode;
  30252. },
  30253. enumerable: true,
  30254. configurable: true
  30255. });
  30256. Object.defineProperty(Material, "LineLoopDrawMode", {
  30257. /**
  30258. * Returns the line loop draw mode.
  30259. */
  30260. get: function () {
  30261. return Material._LineLoopDrawMode;
  30262. },
  30263. enumerable: true,
  30264. configurable: true
  30265. });
  30266. Object.defineProperty(Material, "LineStripDrawMode", {
  30267. /**
  30268. * Returns the line strip draw mode.
  30269. */
  30270. get: function () {
  30271. return Material._LineStripDrawMode;
  30272. },
  30273. enumerable: true,
  30274. configurable: true
  30275. });
  30276. Object.defineProperty(Material, "TriangleStripDrawMode", {
  30277. /**
  30278. * Returns the triangle strip draw mode.
  30279. */
  30280. get: function () {
  30281. return Material._TriangleStripDrawMode;
  30282. },
  30283. enumerable: true,
  30284. configurable: true
  30285. });
  30286. Object.defineProperty(Material, "TriangleFanDrawMode", {
  30287. /**
  30288. * Returns the triangle fan draw mode.
  30289. */
  30290. get: function () {
  30291. return Material._TriangleFanDrawMode;
  30292. },
  30293. enumerable: true,
  30294. configurable: true
  30295. });
  30296. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  30297. /**
  30298. * Returns the clock-wise side orientation.
  30299. */
  30300. get: function () {
  30301. return Material._ClockWiseSideOrientation;
  30302. },
  30303. enumerable: true,
  30304. configurable: true
  30305. });
  30306. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  30307. /**
  30308. * Returns the counter clock-wise side orientation.
  30309. */
  30310. get: function () {
  30311. return Material._CounterClockWiseSideOrientation;
  30312. },
  30313. enumerable: true,
  30314. configurable: true
  30315. });
  30316. Object.defineProperty(Material, "TextureDirtyFlag", {
  30317. /**
  30318. * Returns the dirty texture flag value.
  30319. */
  30320. get: function () {
  30321. return Material._TextureDirtyFlag;
  30322. },
  30323. enumerable: true,
  30324. configurable: true
  30325. });
  30326. Object.defineProperty(Material, "LightDirtyFlag", {
  30327. /**
  30328. * Returns the dirty light flag value.
  30329. */
  30330. get: function () {
  30331. return Material._LightDirtyFlag;
  30332. },
  30333. enumerable: true,
  30334. configurable: true
  30335. });
  30336. Object.defineProperty(Material, "FresnelDirtyFlag", {
  30337. /**
  30338. * Returns the dirty fresnel flag value.
  30339. */
  30340. get: function () {
  30341. return Material._FresnelDirtyFlag;
  30342. },
  30343. enumerable: true,
  30344. configurable: true
  30345. });
  30346. Object.defineProperty(Material, "AttributesDirtyFlag", {
  30347. /**
  30348. * Returns the dirty attributes flag value.
  30349. */
  30350. get: function () {
  30351. return Material._AttributesDirtyFlag;
  30352. },
  30353. enumerable: true,
  30354. configurable: true
  30355. });
  30356. Object.defineProperty(Material, "MiscDirtyFlag", {
  30357. /**
  30358. * Returns the dirty misc flag value.
  30359. */
  30360. get: function () {
  30361. return Material._MiscDirtyFlag;
  30362. },
  30363. enumerable: true,
  30364. configurable: true
  30365. });
  30366. Object.defineProperty(Material.prototype, "alpha", {
  30367. /**
  30368. * Gets the alpha value of the material.
  30369. */
  30370. get: function () {
  30371. return this._alpha;
  30372. },
  30373. /**
  30374. * Sets the alpha value of the material.
  30375. */
  30376. set: function (value) {
  30377. if (this._alpha === value) {
  30378. return;
  30379. }
  30380. this._alpha = value;
  30381. this.markAsDirty(Material.MiscDirtyFlag);
  30382. },
  30383. enumerable: true,
  30384. configurable: true
  30385. });
  30386. Object.defineProperty(Material.prototype, "backFaceCulling", {
  30387. /**
  30388. * Gets the back-face culling state.
  30389. */
  30390. get: function () {
  30391. return this._backFaceCulling;
  30392. },
  30393. /**
  30394. * Sets the back-face culling state.
  30395. */
  30396. set: function (value) {
  30397. if (this._backFaceCulling === value) {
  30398. return;
  30399. }
  30400. this._backFaceCulling = value;
  30401. this.markAsDirty(Material.TextureDirtyFlag);
  30402. },
  30403. enumerable: true,
  30404. configurable: true
  30405. });
  30406. Object.defineProperty(Material.prototype, "onDispose", {
  30407. /**
  30408. * Called during a dispose event.
  30409. */
  30410. set: function (callback) {
  30411. if (this._onDisposeObserver) {
  30412. this.onDisposeObservable.remove(this._onDisposeObserver);
  30413. }
  30414. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  30415. },
  30416. enumerable: true,
  30417. configurable: true
  30418. });
  30419. Object.defineProperty(Material.prototype, "onBind", {
  30420. /**
  30421. * Called during a bind event.
  30422. */
  30423. set: function (callback) {
  30424. if (this._onBindObserver) {
  30425. this.onBindObservable.remove(this._onBindObserver);
  30426. }
  30427. this._onBindObserver = this.onBindObservable.add(callback);
  30428. },
  30429. enumerable: true,
  30430. configurable: true
  30431. });
  30432. Object.defineProperty(Material.prototype, "alphaMode", {
  30433. /**
  30434. * Gets the value of the alpha mode.
  30435. */
  30436. get: function () {
  30437. return this._alphaMode;
  30438. },
  30439. /**
  30440. * Sets the value of the alpha mode.
  30441. */
  30442. set: function (value) {
  30443. if (this._alphaMode === value) {
  30444. return;
  30445. }
  30446. this._alphaMode = value;
  30447. this.markAsDirty(Material.TextureDirtyFlag);
  30448. },
  30449. enumerable: true,
  30450. configurable: true
  30451. });
  30452. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  30453. /**
  30454. * Gets the depth pre-pass value.
  30455. */
  30456. get: function () {
  30457. return this._needDepthPrePass;
  30458. },
  30459. /**
  30460. * Sets the need depth pre-pass value.
  30461. */
  30462. set: function (value) {
  30463. if (this._needDepthPrePass === value) {
  30464. return;
  30465. }
  30466. this._needDepthPrePass = value;
  30467. if (this._needDepthPrePass) {
  30468. this.checkReadyOnEveryCall = true;
  30469. }
  30470. },
  30471. enumerable: true,
  30472. configurable: true
  30473. });
  30474. Object.defineProperty(Material.prototype, "fogEnabled", {
  30475. /**
  30476. * Gets the value of the fog enabled state.
  30477. */
  30478. get: function () {
  30479. return this._fogEnabled;
  30480. },
  30481. /**
  30482. * Sets the state for enabling fog.
  30483. */
  30484. set: function (value) {
  30485. if (this._fogEnabled === value) {
  30486. return;
  30487. }
  30488. this._fogEnabled = value;
  30489. this.markAsDirty(Material.MiscDirtyFlag);
  30490. },
  30491. enumerable: true,
  30492. configurable: true
  30493. });
  30494. Object.defineProperty(Material.prototype, "wireframe", {
  30495. /**
  30496. * Gets a value specifying if wireframe mode is enabled.
  30497. */
  30498. get: function () {
  30499. return this._fillMode === Material.WireFrameFillMode;
  30500. },
  30501. /**
  30502. * Sets the state of wireframe mode.
  30503. */
  30504. set: function (value) {
  30505. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  30506. },
  30507. enumerable: true,
  30508. configurable: true
  30509. });
  30510. Object.defineProperty(Material.prototype, "pointsCloud", {
  30511. /**
  30512. * Gets the value specifying if point clouds are enabled.
  30513. */
  30514. get: function () {
  30515. return this._fillMode === Material.PointFillMode;
  30516. },
  30517. /**
  30518. * Sets the state of point cloud mode.
  30519. */
  30520. set: function (value) {
  30521. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  30522. },
  30523. enumerable: true,
  30524. configurable: true
  30525. });
  30526. Object.defineProperty(Material.prototype, "fillMode", {
  30527. /**
  30528. * Gets the material fill mode.
  30529. */
  30530. get: function () {
  30531. return this._fillMode;
  30532. },
  30533. /**
  30534. * Sets the material fill mode.
  30535. */
  30536. set: function (value) {
  30537. if (this._fillMode === value) {
  30538. return;
  30539. }
  30540. this._fillMode = value;
  30541. this.markAsDirty(Material.MiscDirtyFlag);
  30542. },
  30543. enumerable: true,
  30544. configurable: true
  30545. });
  30546. /**
  30547. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  30548. * subclasses should override adding information pertainent to themselves.
  30549. * @returns - String with material information.
  30550. */
  30551. Material.prototype.toString = function (fullDetails) {
  30552. var ret = "Name: " + this.name;
  30553. if (fullDetails) {
  30554. }
  30555. return ret;
  30556. };
  30557. /**
  30558. * Gets the class name of the material.
  30559. * @returns - String with the class name of the material.
  30560. */
  30561. Material.prototype.getClassName = function () {
  30562. return "Material";
  30563. };
  30564. Object.defineProperty(Material.prototype, "isFrozen", {
  30565. /**
  30566. * Specifies if updates for the material been locked.
  30567. */
  30568. get: function () {
  30569. return this.checkReadyOnlyOnce;
  30570. },
  30571. enumerable: true,
  30572. configurable: true
  30573. });
  30574. /**
  30575. * Locks updates for the material.
  30576. */
  30577. Material.prototype.freeze = function () {
  30578. this.checkReadyOnlyOnce = true;
  30579. };
  30580. /**
  30581. * Unlocks updates for the material.
  30582. */
  30583. Material.prototype.unfreeze = function () {
  30584. this.checkReadyOnlyOnce = false;
  30585. };
  30586. /**
  30587. * Specifies if the material is ready to be used.
  30588. * @param mesh - BJS mesh.
  30589. * @param useInstances - Specifies if instances should be used.
  30590. * @returns - Boolean indicating if the material is ready to be used.
  30591. */
  30592. Material.prototype.isReady = function (mesh, useInstances) {
  30593. return true;
  30594. };
  30595. /**
  30596. * Specifies that the submesh is ready to be used.
  30597. * @param mesh - BJS mesh.
  30598. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  30599. * @param useInstances - Specifies that instances should be used.
  30600. * @returns - boolean indicating that the submesh is ready or not.
  30601. */
  30602. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  30603. return false;
  30604. };
  30605. /**
  30606. * Returns the material effect.
  30607. * @returns - Nullable material effect.
  30608. */
  30609. Material.prototype.getEffect = function () {
  30610. return this._effect;
  30611. };
  30612. /**
  30613. * Returns the BJS scene.
  30614. * @returns - BJS Scene.
  30615. */
  30616. Material.prototype.getScene = function () {
  30617. return this._scene;
  30618. };
  30619. /**
  30620. * Specifies if the material will require alpha blending
  30621. * @returns - Boolean specifying if alpha blending is needed.
  30622. */
  30623. Material.prototype.needAlphaBlending = function () {
  30624. return (this.alpha < 1.0);
  30625. };
  30626. /**
  30627. * Specifies if the mesh will require alpha blending.
  30628. * @param mesh - BJS mesh.
  30629. * @returns - Boolean specifying if alpha blending is needed for the mesh.
  30630. */
  30631. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  30632. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  30633. };
  30634. /**
  30635. * Specifies if this material should be rendered in alpha test mode.
  30636. * @returns - Boolean specifying if an alpha test is needed.
  30637. */
  30638. Material.prototype.needAlphaTesting = function () {
  30639. return false;
  30640. };
  30641. /**
  30642. * Gets the texture used for the alpha test.
  30643. * @returns - Nullable alpha test texture.
  30644. */
  30645. Material.prototype.getAlphaTestTexture = function () {
  30646. return null;
  30647. };
  30648. /**
  30649. * Marks the material to indicate that it needs to be re-calculated.
  30650. */
  30651. Material.prototype.markDirty = function () {
  30652. this._wasPreviouslyReady = false;
  30653. };
  30654. Material.prototype._preBind = function (effect, overrideOrientation) {
  30655. if (overrideOrientation === void 0) { overrideOrientation = null; }
  30656. var engine = this._scene.getEngine();
  30657. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  30658. var reverse = orientation === Material.ClockWiseSideOrientation;
  30659. engine.enableEffect(effect ? effect : this._effect);
  30660. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  30661. return reverse;
  30662. };
  30663. /**
  30664. * Binds the material to the mesh.
  30665. * @param world - World transformation matrix.
  30666. * @param mesh - Mesh to bind the material to.
  30667. */
  30668. Material.prototype.bind = function (world, mesh) {
  30669. };
  30670. /**
  30671. * Binds the submesh to the material.
  30672. * @param world - World transformation matrix.
  30673. * @param mesh - Mesh containing the submesh.
  30674. * @param subMesh - Submesh to bind the material to.
  30675. */
  30676. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  30677. };
  30678. /**
  30679. * Binds the world matrix to the material.
  30680. * @param world - World transformation matrix.
  30681. */
  30682. Material.prototype.bindOnlyWorldMatrix = function (world) {
  30683. };
  30684. /**
  30685. * Binds the scene's uniform buffer to the effect.
  30686. * @param effect - Effect to bind to the scene uniform buffer.
  30687. * @param sceneUbo - Scene uniform buffer.
  30688. */
  30689. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  30690. sceneUbo.bindToEffect(effect, "Scene");
  30691. };
  30692. /**
  30693. * Binds the view matrix to the effect.
  30694. * @param effect - Effect to bind the view matrix to.
  30695. */
  30696. Material.prototype.bindView = function (effect) {
  30697. if (!this._useUBO) {
  30698. effect.setMatrix("view", this.getScene().getViewMatrix());
  30699. }
  30700. else {
  30701. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  30702. }
  30703. };
  30704. /**
  30705. * Binds the view projection matrix to the effect.
  30706. * @param effect - Effect to bind the view projection matrix to.
  30707. */
  30708. Material.prototype.bindViewProjection = function (effect) {
  30709. if (!this._useUBO) {
  30710. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  30711. }
  30712. else {
  30713. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  30714. }
  30715. };
  30716. /**
  30717. * Specifies if material alpha testing should be turned on for the mesh.
  30718. * @param mesh - BJS mesh.
  30719. */
  30720. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  30721. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  30722. };
  30723. /**
  30724. * Processes to execute after binding the material to a mesh.
  30725. * @param mesh - BJS mesh.
  30726. */
  30727. Material.prototype._afterBind = function (mesh) {
  30728. this._scene._cachedMaterial = this;
  30729. if (mesh) {
  30730. this._scene._cachedVisibility = mesh.visibility;
  30731. }
  30732. else {
  30733. this._scene._cachedVisibility = 1;
  30734. }
  30735. if (mesh) {
  30736. this.onBindObservable.notifyObservers(mesh);
  30737. }
  30738. if (this.disableDepthWrite) {
  30739. var engine = this._scene.getEngine();
  30740. this._cachedDepthWriteState = engine.getDepthWrite();
  30741. engine.setDepthWrite(false);
  30742. }
  30743. };
  30744. /**
  30745. * Unbinds the material from the mesh.
  30746. */
  30747. Material.prototype.unbind = function () {
  30748. this.onUnBindObservable.notifyObservers(this);
  30749. if (this.disableDepthWrite) {
  30750. var engine = this._scene.getEngine();
  30751. engine.setDepthWrite(this._cachedDepthWriteState);
  30752. }
  30753. };
  30754. /**
  30755. * Gets the active textures from the material.
  30756. * @returns - Array of textures.
  30757. */
  30758. Material.prototype.getActiveTextures = function () {
  30759. return [];
  30760. };
  30761. /**
  30762. * Specifies if the material uses a texture.
  30763. * @param texture - Texture to check against the material.
  30764. * @returns - Boolean specifying if the material uses the texture.
  30765. */
  30766. Material.prototype.hasTexture = function (texture) {
  30767. return false;
  30768. };
  30769. /**
  30770. * Makes a duplicate of the material, and gives it a new name.
  30771. * @param name - Name to call the duplicated material.
  30772. * @returns - Nullable cloned material
  30773. */
  30774. Material.prototype.clone = function (name) {
  30775. return null;
  30776. };
  30777. /**
  30778. * Gets the meshes bound to the material.
  30779. * @returns - Array of meshes bound to the material.
  30780. */
  30781. Material.prototype.getBindedMeshes = function () {
  30782. var result = new Array();
  30783. for (var index = 0; index < this._scene.meshes.length; index++) {
  30784. var mesh = this._scene.meshes[index];
  30785. if (mesh.material === this) {
  30786. result.push(mesh);
  30787. }
  30788. }
  30789. return result;
  30790. };
  30791. /**
  30792. * Force shader compilation
  30793. * @param mesh - BJS mesh.
  30794. * @param onCompiled - function to execute once the material is compiled.
  30795. * @param options - options to pass to this function.
  30796. */
  30797. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  30798. var _this = this;
  30799. var localOptions = __assign({ clipPlane: false }, options);
  30800. var subMesh = new BABYLON.BaseSubMesh();
  30801. var scene = this.getScene();
  30802. var checkReady = function () {
  30803. if (!_this._scene || !_this._scene.getEngine()) {
  30804. return;
  30805. }
  30806. if (subMesh._materialDefines) {
  30807. subMesh._materialDefines._renderId = -1;
  30808. }
  30809. var clipPlaneState = scene.clipPlane;
  30810. if (localOptions.clipPlane) {
  30811. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  30812. }
  30813. if (_this.storeEffectOnSubMeshes) {
  30814. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  30815. if (onCompiled) {
  30816. onCompiled(_this);
  30817. }
  30818. }
  30819. else {
  30820. setTimeout(checkReady, 16);
  30821. }
  30822. }
  30823. else {
  30824. if (_this.isReady(mesh)) {
  30825. if (onCompiled) {
  30826. onCompiled(_this);
  30827. }
  30828. }
  30829. else {
  30830. setTimeout(checkReady, 16);
  30831. }
  30832. }
  30833. if (localOptions.clipPlane) {
  30834. scene.clipPlane = clipPlaneState;
  30835. }
  30836. };
  30837. checkReady();
  30838. };
  30839. /**
  30840. * Force shader compilation.
  30841. * @param mesh The mesh that will use this material
  30842. * @param options Additional options for compiling the shaders
  30843. * @returns A promise that resolves when the compilation completes
  30844. */
  30845. Material.prototype.forceCompilationAsync = function (mesh, options) {
  30846. var _this = this;
  30847. return new Promise(function (resolve) {
  30848. _this.forceCompilation(mesh, function () {
  30849. resolve();
  30850. }, options);
  30851. });
  30852. };
  30853. /**
  30854. * Marks a define in the material to indicate that it needs to be re-computed.
  30855. * @param flag - Material define flag.
  30856. */
  30857. Material.prototype.markAsDirty = function (flag) {
  30858. if (flag & Material.TextureDirtyFlag) {
  30859. this._markAllSubMeshesAsTexturesDirty();
  30860. }
  30861. if (flag & Material.LightDirtyFlag) {
  30862. this._markAllSubMeshesAsLightsDirty();
  30863. }
  30864. if (flag & Material.FresnelDirtyFlag) {
  30865. this._markAllSubMeshesAsFresnelDirty();
  30866. }
  30867. if (flag & Material.AttributesDirtyFlag) {
  30868. this._markAllSubMeshesAsAttributesDirty();
  30869. }
  30870. if (flag & Material.MiscDirtyFlag) {
  30871. this._markAllSubMeshesAsMiscDirty();
  30872. }
  30873. this.getScene().resetCachedMaterial();
  30874. };
  30875. /**
  30876. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated.
  30877. * @param func - function which checks material defines against the submeshes.
  30878. */
  30879. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  30880. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  30881. var mesh = _a[_i];
  30882. if (!mesh.subMeshes) {
  30883. continue;
  30884. }
  30885. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  30886. var subMesh = _c[_b];
  30887. if (subMesh.getMaterial() !== this) {
  30888. continue;
  30889. }
  30890. if (!subMesh._materialDefines) {
  30891. continue;
  30892. }
  30893. func(subMesh._materialDefines);
  30894. }
  30895. }
  30896. };
  30897. /**
  30898. * Indicates that image processing needs to be re-calculated for all submeshes.
  30899. */
  30900. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  30901. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  30902. };
  30903. /**
  30904. * Indicates that textures need to be re-calculated for all submeshes.
  30905. */
  30906. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  30907. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  30908. };
  30909. /**
  30910. * Indicates that fresnel needs to be re-calculated for all submeshes.
  30911. */
  30912. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  30913. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  30914. };
  30915. /**
  30916. * Indicates that fresnel and misc need to be re-calculated for all submeshes.
  30917. */
  30918. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  30919. this._markAllSubMeshesAsDirty(function (defines) {
  30920. defines.markAsFresnelDirty();
  30921. defines.markAsMiscDirty();
  30922. });
  30923. };
  30924. /**
  30925. * Indicates that lights need to be re-calculated for all submeshes.
  30926. */
  30927. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  30928. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  30929. };
  30930. /**
  30931. * Indicates that attributes need to be re-calculated for all submeshes.
  30932. */
  30933. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  30934. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  30935. };
  30936. /**
  30937. * Indicates that misc needs to be re-calculated for all submeshes.
  30938. */
  30939. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  30940. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  30941. };
  30942. /**
  30943. * Indicates that textures and misc need to be re-calculated for all submeshes.
  30944. */
  30945. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  30946. this._markAllSubMeshesAsDirty(function (defines) {
  30947. defines.markAsTexturesDirty();
  30948. defines.markAsMiscDirty();
  30949. });
  30950. };
  30951. /**
  30952. * Disposes the material.
  30953. * @param forceDisposeEffect - Specifies if effects should be force disposed.
  30954. * @param forceDisposeTextures - Specifies if textures should be force disposed.
  30955. */
  30956. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  30957. // Animations
  30958. this.getScene().stopAnimation(this);
  30959. // Remove from scene
  30960. var index = this._scene.materials.indexOf(this);
  30961. if (index >= 0) {
  30962. this._scene.materials.splice(index, 1);
  30963. }
  30964. // Remove from meshes
  30965. for (index = 0; index < this._scene.meshes.length; index++) {
  30966. var mesh = this._scene.meshes[index];
  30967. if (mesh.material === this) {
  30968. mesh.material = null;
  30969. if (mesh.geometry) {
  30970. var geometry = (mesh.geometry);
  30971. if (this.storeEffectOnSubMeshes) {
  30972. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  30973. var subMesh = _a[_i];
  30974. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  30975. if (forceDisposeEffect && subMesh._materialEffect) {
  30976. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  30977. }
  30978. }
  30979. }
  30980. else {
  30981. geometry._releaseVertexArrayObject(this._effect);
  30982. }
  30983. }
  30984. }
  30985. }
  30986. this._uniformBuffer.dispose();
  30987. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  30988. if (forceDisposeEffect && this._effect) {
  30989. if (!this.storeEffectOnSubMeshes) {
  30990. this._scene.getEngine()._releaseEffect(this._effect);
  30991. }
  30992. this._effect = null;
  30993. }
  30994. // Callback
  30995. this.onDisposeObservable.notifyObservers(this);
  30996. this.onDisposeObservable.clear();
  30997. this.onBindObservable.clear();
  30998. this.onUnBindObservable.clear();
  30999. };
  31000. /**
  31001. * Serializes this material.
  31002. * @returns - serialized material object.
  31003. */
  31004. Material.prototype.serialize = function () {
  31005. return BABYLON.SerializationHelper.Serialize(this);
  31006. };
  31007. /**
  31008. * Creates a MultiMaterial from parse MultiMaterial data.
  31009. * @param parsedMultiMaterial - Parsed MultiMaterial data.
  31010. * @param scene - BJS scene.
  31011. * @returns - MultiMaterial.
  31012. */
  31013. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  31014. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  31015. multiMaterial.id = parsedMultiMaterial.id;
  31016. if (BABYLON.Tags) {
  31017. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  31018. }
  31019. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  31020. var subMatId = parsedMultiMaterial.materials[matIndex];
  31021. if (subMatId) {
  31022. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  31023. }
  31024. else {
  31025. multiMaterial.subMaterials.push(null);
  31026. }
  31027. }
  31028. return multiMaterial;
  31029. };
  31030. /**
  31031. * Creates a material from parsed material data.
  31032. * @param parsedMaterial - Parsed material data.
  31033. * @param scene - BJS scene.
  31034. * @param rootUrl - Root URL containing the material information.
  31035. * @returns - Parsed material.
  31036. */
  31037. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  31038. if (!parsedMaterial.customType) {
  31039. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  31040. }
  31041. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  31042. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  31043. if (!BABYLON.LegacyPBRMaterial) {
  31044. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  31045. return;
  31046. }
  31047. }
  31048. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  31049. return materialType.Parse(parsedMaterial, scene, rootUrl);
  31050. ;
  31051. };
  31052. // Triangle views
  31053. Material._TriangleFillMode = 0;
  31054. Material._WireFrameFillMode = 1;
  31055. Material._PointFillMode = 2;
  31056. // Draw modes
  31057. Material._PointListDrawMode = 3;
  31058. Material._LineListDrawMode = 4;
  31059. Material._LineLoopDrawMode = 5;
  31060. Material._LineStripDrawMode = 6;
  31061. Material._TriangleStripDrawMode = 7;
  31062. Material._TriangleFanDrawMode = 8;
  31063. /**
  31064. * Stores the clock-wise side orientation.
  31065. */
  31066. Material._ClockWiseSideOrientation = 0;
  31067. /**
  31068. * Stores the counter clock-wise side orientation.
  31069. */
  31070. Material._CounterClockWiseSideOrientation = 1;
  31071. /**
  31072. * The dirty texture flag value.
  31073. */
  31074. Material._TextureDirtyFlag = 1;
  31075. /**
  31076. * The dirty light flag value.
  31077. */
  31078. Material._LightDirtyFlag = 2;
  31079. /**
  31080. * The dirty fresnel flag value.
  31081. */
  31082. Material._FresnelDirtyFlag = 4;
  31083. /**
  31084. * The dirty attribute flag value.
  31085. */
  31086. Material._AttributesDirtyFlag = 8;
  31087. /**
  31088. * The dirty misc flag value.
  31089. */
  31090. Material._MiscDirtyFlag = 16;
  31091. __decorate([
  31092. BABYLON.serialize()
  31093. ], Material.prototype, "id", void 0);
  31094. __decorate([
  31095. BABYLON.serialize()
  31096. ], Material.prototype, "name", void 0);
  31097. __decorate([
  31098. BABYLON.serialize()
  31099. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  31100. __decorate([
  31101. BABYLON.serialize()
  31102. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  31103. __decorate([
  31104. BABYLON.serialize()
  31105. ], Material.prototype, "state", void 0);
  31106. __decorate([
  31107. BABYLON.serialize("alpha")
  31108. ], Material.prototype, "_alpha", void 0);
  31109. __decorate([
  31110. BABYLON.serialize("backFaceCulling")
  31111. ], Material.prototype, "_backFaceCulling", void 0);
  31112. __decorate([
  31113. BABYLON.serialize()
  31114. ], Material.prototype, "sideOrientation", void 0);
  31115. __decorate([
  31116. BABYLON.serialize("alphaMode")
  31117. ], Material.prototype, "_alphaMode", void 0);
  31118. __decorate([
  31119. BABYLON.serialize()
  31120. ], Material.prototype, "_needDepthPrePass", void 0);
  31121. __decorate([
  31122. BABYLON.serialize()
  31123. ], Material.prototype, "disableDepthWrite", void 0);
  31124. __decorate([
  31125. BABYLON.serialize()
  31126. ], Material.prototype, "forceDepthWrite", void 0);
  31127. __decorate([
  31128. BABYLON.serialize()
  31129. ], Material.prototype, "separateCullingPass", void 0);
  31130. __decorate([
  31131. BABYLON.serialize("fogEnabled")
  31132. ], Material.prototype, "_fogEnabled", void 0);
  31133. __decorate([
  31134. BABYLON.serialize()
  31135. ], Material.prototype, "pointSize", void 0);
  31136. __decorate([
  31137. BABYLON.serialize()
  31138. ], Material.prototype, "zOffset", void 0);
  31139. __decorate([
  31140. BABYLON.serialize()
  31141. ], Material.prototype, "wireframe", null);
  31142. __decorate([
  31143. BABYLON.serialize()
  31144. ], Material.prototype, "pointsCloud", null);
  31145. __decorate([
  31146. BABYLON.serialize()
  31147. ], Material.prototype, "fillMode", null);
  31148. return Material;
  31149. }());
  31150. BABYLON.Material = Material;
  31151. })(BABYLON || (BABYLON = {}));
  31152. //# sourceMappingURL=babylon.material.js.map
  31153. var BABYLON;
  31154. (function (BABYLON) {
  31155. var UniformBuffer = /** @class */ (function () {
  31156. /**
  31157. * Uniform buffer objects.
  31158. *
  31159. * Handles blocks of uniform on the GPU.
  31160. *
  31161. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  31162. *
  31163. * For more information, please refer to :
  31164. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  31165. */
  31166. function UniformBuffer(engine, data, dynamic) {
  31167. this._engine = engine;
  31168. this._noUBO = !engine.supportsUniformBuffers;
  31169. this._dynamic = dynamic;
  31170. this._data = data || [];
  31171. this._uniformLocations = {};
  31172. this._uniformSizes = {};
  31173. this._uniformLocationPointer = 0;
  31174. this._needSync = false;
  31175. if (this._noUBO) {
  31176. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  31177. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  31178. this.updateFloat = this._updateFloatForEffect;
  31179. this.updateFloat2 = this._updateFloat2ForEffect;
  31180. this.updateFloat3 = this._updateFloat3ForEffect;
  31181. this.updateFloat4 = this._updateFloat4ForEffect;
  31182. this.updateMatrix = this._updateMatrixForEffect;
  31183. this.updateVector3 = this._updateVector3ForEffect;
  31184. this.updateVector4 = this._updateVector4ForEffect;
  31185. this.updateColor3 = this._updateColor3ForEffect;
  31186. this.updateColor4 = this._updateColor4ForEffect;
  31187. }
  31188. else {
  31189. this._engine._uniformBuffers.push(this);
  31190. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  31191. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  31192. this.updateFloat = this._updateFloatForUniform;
  31193. this.updateFloat2 = this._updateFloat2ForUniform;
  31194. this.updateFloat3 = this._updateFloat3ForUniform;
  31195. this.updateFloat4 = this._updateFloat4ForUniform;
  31196. this.updateMatrix = this._updateMatrixForUniform;
  31197. this.updateVector3 = this._updateVector3ForUniform;
  31198. this.updateVector4 = this._updateVector4ForUniform;
  31199. this.updateColor3 = this._updateColor3ForUniform;
  31200. this.updateColor4 = this._updateColor4ForUniform;
  31201. }
  31202. }
  31203. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  31204. // Properties
  31205. /**
  31206. * Indicates if the buffer is using the WebGL2 UBO implementation,
  31207. * or just falling back on setUniformXXX calls.
  31208. */
  31209. get: function () {
  31210. return !this._noUBO;
  31211. },
  31212. enumerable: true,
  31213. configurable: true
  31214. });
  31215. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  31216. /**
  31217. * Indicates if the WebGL underlying uniform buffer is in sync
  31218. * with the javascript cache data.
  31219. */
  31220. get: function () {
  31221. return !this._needSync;
  31222. },
  31223. enumerable: true,
  31224. configurable: true
  31225. });
  31226. /**
  31227. * Indicates if the WebGL underlying uniform buffer is dynamic.
  31228. * Also, a dynamic UniformBuffer will disable cache verification and always
  31229. * update the underlying WebGL uniform buffer to the GPU.
  31230. */
  31231. UniformBuffer.prototype.isDynamic = function () {
  31232. return this._dynamic !== undefined;
  31233. };
  31234. /**
  31235. * The data cache on JS side.
  31236. */
  31237. UniformBuffer.prototype.getData = function () {
  31238. return this._bufferData;
  31239. };
  31240. /**
  31241. * The underlying WebGL Uniform buffer.
  31242. */
  31243. UniformBuffer.prototype.getBuffer = function () {
  31244. return this._buffer;
  31245. };
  31246. /**
  31247. * std140 layout specifies how to align data within an UBO structure.
  31248. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  31249. * for specs.
  31250. */
  31251. UniformBuffer.prototype._fillAlignment = function (size) {
  31252. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  31253. // and 4x4 matrices
  31254. // TODO : change if other types are used
  31255. var alignment;
  31256. if (size <= 2) {
  31257. alignment = size;
  31258. }
  31259. else {
  31260. alignment = 4;
  31261. }
  31262. if ((this._uniformLocationPointer % alignment) !== 0) {
  31263. var oldPointer = this._uniformLocationPointer;
  31264. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  31265. var diff = this._uniformLocationPointer - oldPointer;
  31266. for (var i = 0; i < diff; i++) {
  31267. this._data.push(0);
  31268. }
  31269. }
  31270. };
  31271. /**
  31272. * Adds an uniform in the buffer.
  31273. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  31274. * for the layout to be correct !
  31275. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31276. * @param {number|number[]} size Data size, or data directly.
  31277. */
  31278. UniformBuffer.prototype.addUniform = function (name, size) {
  31279. if (this._noUBO) {
  31280. return;
  31281. }
  31282. if (this._uniformLocations[name] !== undefined) {
  31283. // Already existing uniform
  31284. return;
  31285. }
  31286. // This function must be called in the order of the shader layout !
  31287. // size can be the size of the uniform, or data directly
  31288. var data;
  31289. if (size instanceof Array) {
  31290. data = size;
  31291. size = data.length;
  31292. }
  31293. else {
  31294. size = size;
  31295. data = [];
  31296. // Fill with zeros
  31297. for (var i = 0; i < size; i++) {
  31298. data.push(0);
  31299. }
  31300. }
  31301. this._fillAlignment(size);
  31302. this._uniformSizes[name] = size;
  31303. this._uniformLocations[name] = this._uniformLocationPointer;
  31304. this._uniformLocationPointer += size;
  31305. for (var i = 0; i < size; i++) {
  31306. this._data.push(data[i]);
  31307. }
  31308. this._needSync = true;
  31309. };
  31310. /**
  31311. * Wrapper for addUniform.
  31312. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31313. * @param {Matrix} mat A 4x4 matrix.
  31314. */
  31315. UniformBuffer.prototype.addMatrix = function (name, mat) {
  31316. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  31317. };
  31318. /**
  31319. * Wrapper for addUniform.
  31320. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31321. * @param {number} x
  31322. * @param {number} y
  31323. */
  31324. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  31325. var temp = [x, y];
  31326. this.addUniform(name, temp);
  31327. };
  31328. /**
  31329. * Wrapper for addUniform.
  31330. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31331. * @param {number} x
  31332. * @param {number} y
  31333. * @param {number} z
  31334. */
  31335. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  31336. var temp = [x, y, z];
  31337. this.addUniform(name, temp);
  31338. };
  31339. /**
  31340. * Wrapper for addUniform.
  31341. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31342. * @param {Color3} color
  31343. */
  31344. UniformBuffer.prototype.addColor3 = function (name, color) {
  31345. var temp = new Array();
  31346. color.toArray(temp);
  31347. this.addUniform(name, temp);
  31348. };
  31349. /**
  31350. * Wrapper for addUniform.
  31351. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31352. * @param {Color3} color
  31353. * @param {number} alpha
  31354. */
  31355. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  31356. var temp = new Array();
  31357. color.toArray(temp);
  31358. temp.push(alpha);
  31359. this.addUniform(name, temp);
  31360. };
  31361. /**
  31362. * Wrapper for addUniform.
  31363. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31364. * @param {Vector3} vector
  31365. */
  31366. UniformBuffer.prototype.addVector3 = function (name, vector) {
  31367. var temp = new Array();
  31368. vector.toArray(temp);
  31369. this.addUniform(name, temp);
  31370. };
  31371. /**
  31372. * Wrapper for addUniform.
  31373. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31374. */
  31375. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  31376. this.addUniform(name, 12);
  31377. };
  31378. /**
  31379. * Wrapper for addUniform.
  31380. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31381. */
  31382. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  31383. this.addUniform(name, 8);
  31384. };
  31385. /**
  31386. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  31387. */
  31388. UniformBuffer.prototype.create = function () {
  31389. if (this._noUBO) {
  31390. return;
  31391. }
  31392. if (this._buffer) {
  31393. return; // nothing to do
  31394. }
  31395. // See spec, alignment must be filled as a vec4
  31396. this._fillAlignment(4);
  31397. this._bufferData = new Float32Array(this._data);
  31398. this._rebuild();
  31399. this._needSync = true;
  31400. };
  31401. UniformBuffer.prototype._rebuild = function () {
  31402. if (this._noUBO) {
  31403. return;
  31404. }
  31405. if (this._dynamic) {
  31406. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  31407. }
  31408. else {
  31409. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  31410. }
  31411. };
  31412. /**
  31413. * Updates the WebGL Uniform Buffer on the GPU.
  31414. * If the `dynamic` flag is set to true, no cache comparison is done.
  31415. * Otherwise, the buffer will be updated only if the cache differs.
  31416. */
  31417. UniformBuffer.prototype.update = function () {
  31418. if (!this._buffer) {
  31419. this.create();
  31420. return;
  31421. }
  31422. if (!this._dynamic && !this._needSync) {
  31423. return;
  31424. }
  31425. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  31426. this._needSync = false;
  31427. };
  31428. /**
  31429. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  31430. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  31431. * @param {number[]|Float32Array} data Flattened data
  31432. * @param {number} size Size of the data.
  31433. */
  31434. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  31435. var location = this._uniformLocations[uniformName];
  31436. if (location === undefined) {
  31437. if (this._buffer) {
  31438. // Cannot add an uniform if the buffer is already created
  31439. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  31440. return;
  31441. }
  31442. this.addUniform(uniformName, size);
  31443. location = this._uniformLocations[uniformName];
  31444. }
  31445. if (!this._buffer) {
  31446. this.create();
  31447. }
  31448. if (!this._dynamic) {
  31449. // Cache for static uniform buffers
  31450. var changed = false;
  31451. for (var i = 0; i < size; i++) {
  31452. if (this._bufferData[location + i] !== data[i]) {
  31453. changed = true;
  31454. this._bufferData[location + i] = data[i];
  31455. }
  31456. }
  31457. this._needSync = this._needSync || changed;
  31458. }
  31459. else {
  31460. // No cache for dynamic
  31461. for (var i = 0; i < size; i++) {
  31462. this._bufferData[location + i] = data[i];
  31463. }
  31464. }
  31465. };
  31466. // Update methods
  31467. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  31468. // To match std140, matrix must be realigned
  31469. for (var i = 0; i < 3; i++) {
  31470. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  31471. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  31472. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  31473. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  31474. }
  31475. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  31476. };
  31477. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  31478. this._currentEffect.setMatrix3x3(name, matrix);
  31479. };
  31480. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  31481. this._currentEffect.setMatrix2x2(name, matrix);
  31482. };
  31483. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  31484. // To match std140, matrix must be realigned
  31485. for (var i = 0; i < 2; i++) {
  31486. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  31487. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  31488. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  31489. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  31490. }
  31491. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  31492. };
  31493. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  31494. this._currentEffect.setFloat(name, x);
  31495. };
  31496. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  31497. UniformBuffer._tempBuffer[0] = x;
  31498. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  31499. };
  31500. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  31501. if (suffix === void 0) { suffix = ""; }
  31502. this._currentEffect.setFloat2(name + suffix, x, y);
  31503. };
  31504. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  31505. if (suffix === void 0) { suffix = ""; }
  31506. UniformBuffer._tempBuffer[0] = x;
  31507. UniformBuffer._tempBuffer[1] = y;
  31508. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  31509. };
  31510. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  31511. if (suffix === void 0) { suffix = ""; }
  31512. this._currentEffect.setFloat3(name + suffix, x, y, z);
  31513. };
  31514. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  31515. if (suffix === void 0) { suffix = ""; }
  31516. UniformBuffer._tempBuffer[0] = x;
  31517. UniformBuffer._tempBuffer[1] = y;
  31518. UniformBuffer._tempBuffer[2] = z;
  31519. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  31520. };
  31521. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  31522. if (suffix === void 0) { suffix = ""; }
  31523. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  31524. };
  31525. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  31526. if (suffix === void 0) { suffix = ""; }
  31527. UniformBuffer._tempBuffer[0] = x;
  31528. UniformBuffer._tempBuffer[1] = y;
  31529. UniformBuffer._tempBuffer[2] = z;
  31530. UniformBuffer._tempBuffer[3] = w;
  31531. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  31532. };
  31533. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  31534. this._currentEffect.setMatrix(name, mat);
  31535. };
  31536. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  31537. this.updateUniform(name, mat.toArray(), 16);
  31538. };
  31539. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  31540. this._currentEffect.setVector3(name, vector);
  31541. };
  31542. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  31543. vector.toArray(UniformBuffer._tempBuffer);
  31544. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  31545. };
  31546. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  31547. this._currentEffect.setVector4(name, vector);
  31548. };
  31549. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  31550. vector.toArray(UniformBuffer._tempBuffer);
  31551. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  31552. };
  31553. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  31554. if (suffix === void 0) { suffix = ""; }
  31555. this._currentEffect.setColor3(name + suffix, color);
  31556. };
  31557. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  31558. if (suffix === void 0) { suffix = ""; }
  31559. color.toArray(UniformBuffer._tempBuffer);
  31560. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  31561. };
  31562. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  31563. if (suffix === void 0) { suffix = ""; }
  31564. this._currentEffect.setColor4(name + suffix, color, alpha);
  31565. };
  31566. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  31567. if (suffix === void 0) { suffix = ""; }
  31568. color.toArray(UniformBuffer._tempBuffer);
  31569. UniformBuffer._tempBuffer[3] = alpha;
  31570. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  31571. };
  31572. /**
  31573. * Sets a sampler uniform on the effect.
  31574. * @param {string} name Name of the sampler.
  31575. * @param {Texture} texture
  31576. */
  31577. UniformBuffer.prototype.setTexture = function (name, texture) {
  31578. this._currentEffect.setTexture(name, texture);
  31579. };
  31580. /**
  31581. * Directly updates the value of the uniform in the cache AND on the GPU.
  31582. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  31583. * @param {number[]|Float32Array} data Flattened data
  31584. */
  31585. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  31586. this.updateUniform(uniformName, data, data.length);
  31587. this.update();
  31588. };
  31589. /**
  31590. * Binds this uniform buffer to an effect.
  31591. * @param {Effect} effect
  31592. * @param {string} name Name of the uniform block in the shader.
  31593. */
  31594. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  31595. this._currentEffect = effect;
  31596. if (this._noUBO || !this._buffer) {
  31597. return;
  31598. }
  31599. effect.bindUniformBuffer(this._buffer, name);
  31600. };
  31601. /**
  31602. * Disposes the uniform buffer.
  31603. */
  31604. UniformBuffer.prototype.dispose = function () {
  31605. if (this._noUBO) {
  31606. return;
  31607. }
  31608. var index = this._engine._uniformBuffers.indexOf(this);
  31609. if (index !== -1) {
  31610. this._engine._uniformBuffers.splice(index, 1);
  31611. }
  31612. if (!this._buffer) {
  31613. return;
  31614. }
  31615. if (this._engine._releaseBuffer(this._buffer)) {
  31616. this._buffer = null;
  31617. }
  31618. };
  31619. // Pool for avoiding memory leaks
  31620. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  31621. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  31622. return UniformBuffer;
  31623. }());
  31624. BABYLON.UniformBuffer = UniformBuffer;
  31625. })(BABYLON || (BABYLON = {}));
  31626. //# sourceMappingURL=babylon.uniformBuffer.js.map
  31627. var BABYLON;
  31628. (function (BABYLON) {
  31629. var VertexData = /** @class */ (function () {
  31630. function VertexData() {
  31631. }
  31632. VertexData.prototype.set = function (data, kind) {
  31633. switch (kind) {
  31634. case BABYLON.VertexBuffer.PositionKind:
  31635. this.positions = data;
  31636. break;
  31637. case BABYLON.VertexBuffer.NormalKind:
  31638. this.normals = data;
  31639. break;
  31640. case BABYLON.VertexBuffer.TangentKind:
  31641. this.tangents = data;
  31642. break;
  31643. case BABYLON.VertexBuffer.UVKind:
  31644. this.uvs = data;
  31645. break;
  31646. case BABYLON.VertexBuffer.UV2Kind:
  31647. this.uvs2 = data;
  31648. break;
  31649. case BABYLON.VertexBuffer.UV3Kind:
  31650. this.uvs3 = data;
  31651. break;
  31652. case BABYLON.VertexBuffer.UV4Kind:
  31653. this.uvs4 = data;
  31654. break;
  31655. case BABYLON.VertexBuffer.UV5Kind:
  31656. this.uvs5 = data;
  31657. break;
  31658. case BABYLON.VertexBuffer.UV6Kind:
  31659. this.uvs6 = data;
  31660. break;
  31661. case BABYLON.VertexBuffer.ColorKind:
  31662. this.colors = data;
  31663. break;
  31664. case BABYLON.VertexBuffer.MatricesIndicesKind:
  31665. this.matricesIndices = data;
  31666. break;
  31667. case BABYLON.VertexBuffer.MatricesWeightsKind:
  31668. this.matricesWeights = data;
  31669. break;
  31670. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  31671. this.matricesIndicesExtra = data;
  31672. break;
  31673. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  31674. this.matricesWeightsExtra = data;
  31675. break;
  31676. }
  31677. };
  31678. /**
  31679. * Associates the vertexData to the passed Mesh.
  31680. * Sets it as updatable or not (default `false`).
  31681. * Returns the VertexData.
  31682. */
  31683. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  31684. this._applyTo(mesh, updatable);
  31685. return this;
  31686. };
  31687. /**
  31688. * Associates the vertexData to the passed Geometry.
  31689. * Sets it as updatable or not (default `false`).
  31690. * Returns the VertexData.
  31691. */
  31692. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  31693. this._applyTo(geometry, updatable);
  31694. return this;
  31695. };
  31696. /**
  31697. * Updates the associated mesh.
  31698. * Returns the VertexData.
  31699. */
  31700. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  31701. this._update(mesh);
  31702. return this;
  31703. };
  31704. /**
  31705. * Updates the associated geometry.
  31706. * Returns the VertexData.
  31707. */
  31708. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  31709. this._update(geometry);
  31710. return this;
  31711. };
  31712. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  31713. if (updatable === void 0) { updatable = false; }
  31714. if (this.positions) {
  31715. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  31716. }
  31717. if (this.normals) {
  31718. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  31719. }
  31720. if (this.tangents) {
  31721. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  31722. }
  31723. if (this.uvs) {
  31724. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  31725. }
  31726. if (this.uvs2) {
  31727. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  31728. }
  31729. if (this.uvs3) {
  31730. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  31731. }
  31732. if (this.uvs4) {
  31733. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  31734. }
  31735. if (this.uvs5) {
  31736. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  31737. }
  31738. if (this.uvs6) {
  31739. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  31740. }
  31741. if (this.colors) {
  31742. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  31743. }
  31744. if (this.matricesIndices) {
  31745. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  31746. }
  31747. if (this.matricesWeights) {
  31748. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  31749. }
  31750. if (this.matricesIndicesExtra) {
  31751. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  31752. }
  31753. if (this.matricesWeightsExtra) {
  31754. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  31755. }
  31756. if (this.indices) {
  31757. meshOrGeometry.setIndices(this.indices, null, updatable);
  31758. }
  31759. return this;
  31760. };
  31761. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  31762. if (this.positions) {
  31763. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  31764. }
  31765. if (this.normals) {
  31766. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  31767. }
  31768. if (this.tangents) {
  31769. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  31770. }
  31771. if (this.uvs) {
  31772. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  31773. }
  31774. if (this.uvs2) {
  31775. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  31776. }
  31777. if (this.uvs3) {
  31778. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  31779. }
  31780. if (this.uvs4) {
  31781. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  31782. }
  31783. if (this.uvs5) {
  31784. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  31785. }
  31786. if (this.uvs6) {
  31787. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  31788. }
  31789. if (this.colors) {
  31790. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  31791. }
  31792. if (this.matricesIndices) {
  31793. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  31794. }
  31795. if (this.matricesWeights) {
  31796. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  31797. }
  31798. if (this.matricesIndicesExtra) {
  31799. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  31800. }
  31801. if (this.matricesWeightsExtra) {
  31802. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  31803. }
  31804. if (this.indices) {
  31805. meshOrGeometry.setIndices(this.indices, null);
  31806. }
  31807. return this;
  31808. };
  31809. /**
  31810. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  31811. * Returns the VertexData.
  31812. */
  31813. VertexData.prototype.transform = function (matrix) {
  31814. var transformed = BABYLON.Vector3.Zero();
  31815. var index;
  31816. if (this.positions) {
  31817. var position = BABYLON.Vector3.Zero();
  31818. for (index = 0; index < this.positions.length; index += 3) {
  31819. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  31820. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  31821. this.positions[index] = transformed.x;
  31822. this.positions[index + 1] = transformed.y;
  31823. this.positions[index + 2] = transformed.z;
  31824. }
  31825. }
  31826. if (this.normals) {
  31827. var normal = BABYLON.Vector3.Zero();
  31828. for (index = 0; index < this.normals.length; index += 3) {
  31829. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  31830. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  31831. this.normals[index] = transformed.x;
  31832. this.normals[index + 1] = transformed.y;
  31833. this.normals[index + 2] = transformed.z;
  31834. }
  31835. }
  31836. if (this.tangents) {
  31837. var tangent = BABYLON.Vector4.Zero();
  31838. var tangentTransformed = BABYLON.Vector4.Zero();
  31839. for (index = 0; index < this.tangents.length; index += 4) {
  31840. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  31841. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  31842. this.tangents[index] = tangentTransformed.x;
  31843. this.tangents[index + 1] = tangentTransformed.y;
  31844. this.tangents[index + 2] = tangentTransformed.z;
  31845. this.tangents[index + 3] = tangentTransformed.w;
  31846. }
  31847. }
  31848. return this;
  31849. };
  31850. /**
  31851. * Merges the passed VertexData into the current one.
  31852. * Returns the modified VertexData.
  31853. */
  31854. VertexData.prototype.merge = function (other) {
  31855. this._validate();
  31856. other._validate();
  31857. if (!this.normals !== !other.normals ||
  31858. !this.tangents !== !other.tangents ||
  31859. !this.uvs !== !other.uvs ||
  31860. !this.uvs2 !== !other.uvs2 ||
  31861. !this.uvs3 !== !other.uvs3 ||
  31862. !this.uvs4 !== !other.uvs4 ||
  31863. !this.uvs5 !== !other.uvs5 ||
  31864. !this.uvs6 !== !other.uvs6 ||
  31865. !this.colors !== !other.colors ||
  31866. !this.matricesIndices !== !other.matricesIndices ||
  31867. !this.matricesWeights !== !other.matricesWeights ||
  31868. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  31869. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  31870. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  31871. }
  31872. if (other.indices) {
  31873. if (!this.indices) {
  31874. this.indices = [];
  31875. }
  31876. var offset = this.positions ? this.positions.length / 3 : 0;
  31877. for (var index = 0; index < other.indices.length; index++) {
  31878. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  31879. this.indices.push(other.indices[index] + offset);
  31880. }
  31881. }
  31882. this.positions = this._mergeElement(this.positions, other.positions);
  31883. this.normals = this._mergeElement(this.normals, other.normals);
  31884. this.tangents = this._mergeElement(this.tangents, other.tangents);
  31885. this.uvs = this._mergeElement(this.uvs, other.uvs);
  31886. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  31887. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  31888. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  31889. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  31890. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  31891. this.colors = this._mergeElement(this.colors, other.colors);
  31892. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  31893. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  31894. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  31895. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  31896. return this;
  31897. };
  31898. VertexData.prototype._mergeElement = function (source, other) {
  31899. if (!source) {
  31900. return other;
  31901. }
  31902. if (!other) {
  31903. return source;
  31904. }
  31905. var len = other.length + source.length;
  31906. var isSrcTypedArray = source instanceof Float32Array;
  31907. var isOthTypedArray = other instanceof Float32Array;
  31908. // use non-loop method when the source is Float32Array
  31909. if (isSrcTypedArray) {
  31910. var ret32 = new Float32Array(len);
  31911. ret32.set(source);
  31912. ret32.set(other, source.length);
  31913. return ret32;
  31914. // source is number[], when other is also use concat
  31915. }
  31916. else if (!isOthTypedArray) {
  31917. return source.concat(other);
  31918. // source is a number[], but other is a Float32Array, loop required
  31919. }
  31920. else {
  31921. var ret = source.slice(0); // copy source to a separate array
  31922. for (var i = 0, len = other.length; i < len; i++) {
  31923. ret.push(other[i]);
  31924. }
  31925. return ret;
  31926. }
  31927. };
  31928. VertexData.prototype._validate = function () {
  31929. if (!this.positions) {
  31930. throw new Error("Positions are required");
  31931. }
  31932. var getElementCount = function (kind, values) {
  31933. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  31934. if ((values.length % stride) !== 0) {
  31935. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  31936. }
  31937. return values.length / stride;
  31938. };
  31939. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  31940. var validateElementCount = function (kind, values) {
  31941. var elementCount = getElementCount(kind, values);
  31942. if (elementCount !== positionsElementCount) {
  31943. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  31944. }
  31945. };
  31946. if (this.normals)
  31947. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  31948. if (this.tangents)
  31949. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  31950. if (this.uvs)
  31951. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  31952. if (this.uvs2)
  31953. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  31954. if (this.uvs3)
  31955. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  31956. if (this.uvs4)
  31957. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  31958. if (this.uvs5)
  31959. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  31960. if (this.uvs6)
  31961. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  31962. if (this.colors)
  31963. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  31964. if (this.matricesIndices)
  31965. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  31966. if (this.matricesWeights)
  31967. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  31968. if (this.matricesIndicesExtra)
  31969. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  31970. if (this.matricesWeightsExtra)
  31971. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  31972. };
  31973. /**
  31974. * Serializes the VertexData.
  31975. * Returns a serialized object.
  31976. */
  31977. VertexData.prototype.serialize = function () {
  31978. var serializationObject = this.serialize();
  31979. if (this.positions) {
  31980. serializationObject.positions = this.positions;
  31981. }
  31982. if (this.normals) {
  31983. serializationObject.normals = this.normals;
  31984. }
  31985. if (this.tangents) {
  31986. serializationObject.tangents = this.tangents;
  31987. }
  31988. if (this.uvs) {
  31989. serializationObject.uvs = this.uvs;
  31990. }
  31991. if (this.uvs2) {
  31992. serializationObject.uvs2 = this.uvs2;
  31993. }
  31994. if (this.uvs3) {
  31995. serializationObject.uvs3 = this.uvs3;
  31996. }
  31997. if (this.uvs4) {
  31998. serializationObject.uvs4 = this.uvs4;
  31999. }
  32000. if (this.uvs5) {
  32001. serializationObject.uvs5 = this.uvs5;
  32002. }
  32003. if (this.uvs6) {
  32004. serializationObject.uvs6 = this.uvs6;
  32005. }
  32006. if (this.colors) {
  32007. serializationObject.colors = this.colors;
  32008. }
  32009. if (this.matricesIndices) {
  32010. serializationObject.matricesIndices = this.matricesIndices;
  32011. serializationObject.matricesIndices._isExpanded = true;
  32012. }
  32013. if (this.matricesWeights) {
  32014. serializationObject.matricesWeights = this.matricesWeights;
  32015. }
  32016. if (this.matricesIndicesExtra) {
  32017. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  32018. serializationObject.matricesIndicesExtra._isExpanded = true;
  32019. }
  32020. if (this.matricesWeightsExtra) {
  32021. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  32022. }
  32023. serializationObject.indices = this.indices;
  32024. return serializationObject;
  32025. };
  32026. // Statics
  32027. /**
  32028. * Returns the object VertexData associated to the passed mesh.
  32029. */
  32030. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  32031. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  32032. };
  32033. /**
  32034. * Returns the object VertexData associated to the passed geometry.
  32035. */
  32036. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  32037. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  32038. };
  32039. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  32040. var result = new VertexData();
  32041. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32042. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  32043. }
  32044. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32045. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  32046. }
  32047. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  32048. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  32049. }
  32050. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32051. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  32052. }
  32053. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  32054. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  32055. }
  32056. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  32057. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  32058. }
  32059. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  32060. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  32061. }
  32062. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  32063. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  32064. }
  32065. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  32066. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  32067. }
  32068. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  32069. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  32070. }
  32071. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  32072. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  32073. }
  32074. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  32075. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  32076. }
  32077. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  32078. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  32079. }
  32080. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  32081. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  32082. }
  32083. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  32084. return result;
  32085. };
  32086. /**
  32087. * Creates the vertexData of the Ribbon.
  32088. */
  32089. VertexData.CreateRibbon = function (options) {
  32090. var pathArray = options.pathArray;
  32091. var closeArray = options.closeArray || false;
  32092. var closePath = options.closePath || false;
  32093. var invertUV = options.invertUV || false;
  32094. var defaultOffset = Math.floor(pathArray[0].length / 2);
  32095. var offset = options.offset || defaultOffset;
  32096. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  32097. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32098. var customUV = options.uvs;
  32099. var customColors = options.colors;
  32100. var positions = [];
  32101. var indices = [];
  32102. var normals = [];
  32103. var uvs = [];
  32104. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  32105. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  32106. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  32107. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  32108. var minlg; // minimal length among all paths from pathArray
  32109. var lg = []; // array of path lengths : nb of vertex per path
  32110. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  32111. var p; // path iterator
  32112. var i; // point iterator
  32113. var j; // point iterator
  32114. // if single path in pathArray
  32115. if (pathArray.length < 2) {
  32116. var ar1 = [];
  32117. var ar2 = [];
  32118. for (i = 0; i < pathArray[0].length - offset; i++) {
  32119. ar1.push(pathArray[0][i]);
  32120. ar2.push(pathArray[0][i + offset]);
  32121. }
  32122. pathArray = [ar1, ar2];
  32123. }
  32124. // positions and horizontal distances (u)
  32125. var idc = 0;
  32126. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  32127. var path;
  32128. var l;
  32129. minlg = pathArray[0].length;
  32130. var vectlg;
  32131. var dist;
  32132. for (p = 0; p < pathArray.length; p++) {
  32133. uTotalDistance[p] = 0;
  32134. us[p] = [0];
  32135. path = pathArray[p];
  32136. l = path.length;
  32137. minlg = (minlg < l) ? minlg : l;
  32138. j = 0;
  32139. while (j < l) {
  32140. positions.push(path[j].x, path[j].y, path[j].z);
  32141. if (j > 0) {
  32142. vectlg = path[j].subtract(path[j - 1]).length();
  32143. dist = vectlg + uTotalDistance[p];
  32144. us[p].push(dist);
  32145. uTotalDistance[p] = dist;
  32146. }
  32147. j++;
  32148. }
  32149. if (closePath) {
  32150. j--;
  32151. positions.push(path[0].x, path[0].y, path[0].z);
  32152. vectlg = path[j].subtract(path[0]).length();
  32153. dist = vectlg + uTotalDistance[p];
  32154. us[p].push(dist);
  32155. uTotalDistance[p] = dist;
  32156. }
  32157. lg[p] = l + closePathCorr;
  32158. idx[p] = idc;
  32159. idc += (l + closePathCorr);
  32160. }
  32161. // vertical distances (v)
  32162. var path1;
  32163. var path2;
  32164. var vertex1 = null;
  32165. var vertex2 = null;
  32166. for (i = 0; i < minlg + closePathCorr; i++) {
  32167. vTotalDistance[i] = 0;
  32168. vs[i] = [0];
  32169. for (p = 0; p < pathArray.length - 1; p++) {
  32170. path1 = pathArray[p];
  32171. path2 = pathArray[p + 1];
  32172. if (i === minlg) {
  32173. vertex1 = path1[0];
  32174. vertex2 = path2[0];
  32175. }
  32176. else {
  32177. vertex1 = path1[i];
  32178. vertex2 = path2[i];
  32179. }
  32180. vectlg = vertex2.subtract(vertex1).length();
  32181. dist = vectlg + vTotalDistance[i];
  32182. vs[i].push(dist);
  32183. vTotalDistance[i] = dist;
  32184. }
  32185. if (closeArray && vertex2 && vertex1) {
  32186. path1 = pathArray[p];
  32187. path2 = pathArray[0];
  32188. if (i === minlg) {
  32189. vertex2 = path2[0];
  32190. }
  32191. vectlg = vertex2.subtract(vertex1).length();
  32192. dist = vectlg + vTotalDistance[i];
  32193. vTotalDistance[i] = dist;
  32194. }
  32195. }
  32196. // uvs
  32197. var u;
  32198. var v;
  32199. if (customUV) {
  32200. for (p = 0; p < customUV.length; p++) {
  32201. uvs.push(customUV[p].x, customUV[p].y);
  32202. }
  32203. }
  32204. else {
  32205. for (p = 0; p < pathArray.length; p++) {
  32206. for (i = 0; i < minlg + closePathCorr; i++) {
  32207. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  32208. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  32209. if (invertUV) {
  32210. uvs.push(v, u);
  32211. }
  32212. else {
  32213. uvs.push(u, v);
  32214. }
  32215. }
  32216. }
  32217. }
  32218. // indices
  32219. p = 0; // path index
  32220. var pi = 0; // positions array index
  32221. var l1 = lg[p] - 1; // path1 length
  32222. var l2 = lg[p + 1] - 1; // path2 length
  32223. var min = (l1 < l2) ? l1 : l2; // current path stop index
  32224. var shft = idx[1] - idx[0]; // shift
  32225. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  32226. while (pi <= min && p < path1nb) {
  32227. // 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
  32228. indices.push(pi, pi + shft, pi + 1);
  32229. indices.push(pi + shft + 1, pi + 1, pi + shft);
  32230. pi += 1;
  32231. if (pi === min) {
  32232. p++;
  32233. if (p === lg.length - 1) {
  32234. shft = idx[0] - idx[p];
  32235. l1 = lg[p] - 1;
  32236. l2 = lg[0] - 1;
  32237. }
  32238. else {
  32239. shft = idx[p + 1] - idx[p];
  32240. l1 = lg[p] - 1;
  32241. l2 = lg[p + 1] - 1;
  32242. }
  32243. pi = idx[p];
  32244. min = (l1 < l2) ? l1 + pi : l2 + pi;
  32245. }
  32246. }
  32247. // normals
  32248. VertexData.ComputeNormals(positions, indices, normals);
  32249. if (closePath) {
  32250. var indexFirst = 0;
  32251. var indexLast = 0;
  32252. for (p = 0; p < pathArray.length; p++) {
  32253. indexFirst = idx[p] * 3;
  32254. if (p + 1 < pathArray.length) {
  32255. indexLast = (idx[p + 1] - 1) * 3;
  32256. }
  32257. else {
  32258. indexLast = normals.length - 3;
  32259. }
  32260. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  32261. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  32262. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  32263. normals[indexLast] = normals[indexFirst];
  32264. normals[indexLast + 1] = normals[indexFirst + 1];
  32265. normals[indexLast + 2] = normals[indexFirst + 2];
  32266. }
  32267. }
  32268. // sides
  32269. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  32270. // Colors
  32271. var colors = null;
  32272. if (customColors) {
  32273. colors = new Float32Array(customColors.length * 4);
  32274. for (var c = 0; c < customColors.length; c++) {
  32275. colors[c * 4] = customColors[c].r;
  32276. colors[c * 4 + 1] = customColors[c].g;
  32277. colors[c * 4 + 2] = customColors[c].b;
  32278. colors[c * 4 + 3] = customColors[c].a;
  32279. }
  32280. }
  32281. // Result
  32282. var vertexData = new VertexData();
  32283. var positions32 = new Float32Array(positions);
  32284. var normals32 = new Float32Array(normals);
  32285. var uvs32 = new Float32Array(uvs);
  32286. vertexData.indices = indices;
  32287. vertexData.positions = positions32;
  32288. vertexData.normals = normals32;
  32289. vertexData.uvs = uvs32;
  32290. if (colors) {
  32291. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  32292. }
  32293. if (closePath) {
  32294. vertexData._idx = idx;
  32295. }
  32296. return vertexData;
  32297. };
  32298. /**
  32299. * Creates the VertexData of the Box.
  32300. */
  32301. VertexData.CreateBox = function (options) {
  32302. var normalsSource = [
  32303. new BABYLON.Vector3(0, 0, 1),
  32304. new BABYLON.Vector3(0, 0, -1),
  32305. new BABYLON.Vector3(1, 0, 0),
  32306. new BABYLON.Vector3(-1, 0, 0),
  32307. new BABYLON.Vector3(0, 1, 0),
  32308. new BABYLON.Vector3(0, -1, 0)
  32309. ];
  32310. var indices = [];
  32311. var positions = [];
  32312. var normals = [];
  32313. var uvs = [];
  32314. var width = options.width || options.size || 1;
  32315. var height = options.height || options.size || 1;
  32316. var depth = options.depth || options.size || 1;
  32317. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32318. var faceUV = options.faceUV || new Array(6);
  32319. var faceColors = options.faceColors;
  32320. var colors = [];
  32321. // default face colors and UV if undefined
  32322. for (var f = 0; f < 6; f++) {
  32323. if (faceUV[f] === undefined) {
  32324. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  32325. }
  32326. if (faceColors && faceColors[f] === undefined) {
  32327. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  32328. }
  32329. }
  32330. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  32331. // Create each face in turn.
  32332. for (var index = 0; index < normalsSource.length; index++) {
  32333. var normal = normalsSource[index];
  32334. // Get two vectors perpendicular to the face normal and to each other.
  32335. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  32336. var side2 = BABYLON.Vector3.Cross(normal, side1);
  32337. // Six indices (two triangles) per face.
  32338. var verticesLength = positions.length / 3;
  32339. indices.push(verticesLength);
  32340. indices.push(verticesLength + 1);
  32341. indices.push(verticesLength + 2);
  32342. indices.push(verticesLength);
  32343. indices.push(verticesLength + 2);
  32344. indices.push(verticesLength + 3);
  32345. // Four vertices per face.
  32346. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  32347. positions.push(vertex.x, vertex.y, vertex.z);
  32348. normals.push(normal.x, normal.y, normal.z);
  32349. uvs.push(faceUV[index].z, faceUV[index].w);
  32350. if (faceColors) {
  32351. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  32352. }
  32353. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  32354. positions.push(vertex.x, vertex.y, vertex.z);
  32355. normals.push(normal.x, normal.y, normal.z);
  32356. uvs.push(faceUV[index].x, faceUV[index].w);
  32357. if (faceColors) {
  32358. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  32359. }
  32360. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  32361. positions.push(vertex.x, vertex.y, vertex.z);
  32362. normals.push(normal.x, normal.y, normal.z);
  32363. uvs.push(faceUV[index].x, faceUV[index].y);
  32364. if (faceColors) {
  32365. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  32366. }
  32367. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  32368. positions.push(vertex.x, vertex.y, vertex.z);
  32369. normals.push(normal.x, normal.y, normal.z);
  32370. uvs.push(faceUV[index].z, faceUV[index].y);
  32371. if (faceColors) {
  32372. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  32373. }
  32374. }
  32375. // sides
  32376. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  32377. // Result
  32378. var vertexData = new VertexData();
  32379. vertexData.indices = indices;
  32380. vertexData.positions = positions;
  32381. vertexData.normals = normals;
  32382. vertexData.uvs = uvs;
  32383. if (faceColors) {
  32384. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  32385. vertexData.colors = totalColors;
  32386. }
  32387. return vertexData;
  32388. };
  32389. /**
  32390. * Creates the VertexData of the Sphere.
  32391. */
  32392. VertexData.CreateSphere = function (options) {
  32393. var segments = options.segments || 32;
  32394. var diameterX = options.diameterX || options.diameter || 1;
  32395. var diameterY = options.diameterY || options.diameter || 1;
  32396. var diameterZ = options.diameterZ || options.diameter || 1;
  32397. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  32398. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  32399. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32400. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  32401. var totalZRotationSteps = 2 + segments;
  32402. var totalYRotationSteps = 2 * totalZRotationSteps;
  32403. var indices = [];
  32404. var positions = [];
  32405. var normals = [];
  32406. var uvs = [];
  32407. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  32408. var normalizedZ = zRotationStep / totalZRotationSteps;
  32409. var angleZ = normalizedZ * Math.PI * slice;
  32410. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  32411. var normalizedY = yRotationStep / totalYRotationSteps;
  32412. var angleY = normalizedY * Math.PI * 2 * arc;
  32413. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  32414. var rotationY = BABYLON.Matrix.RotationY(angleY);
  32415. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  32416. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  32417. var vertex = complete.multiply(radius);
  32418. var normal = complete.divide(radius).normalize();
  32419. positions.push(vertex.x, vertex.y, vertex.z);
  32420. normals.push(normal.x, normal.y, normal.z);
  32421. uvs.push(normalizedY, normalizedZ);
  32422. }
  32423. if (zRotationStep > 0) {
  32424. var verticesCount = positions.length / 3;
  32425. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  32426. indices.push((firstIndex));
  32427. indices.push((firstIndex + 1));
  32428. indices.push(firstIndex + totalYRotationSteps + 1);
  32429. indices.push((firstIndex + totalYRotationSteps + 1));
  32430. indices.push((firstIndex + 1));
  32431. indices.push((firstIndex + totalYRotationSteps + 2));
  32432. }
  32433. }
  32434. }
  32435. // Sides
  32436. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  32437. // Result
  32438. var vertexData = new VertexData();
  32439. vertexData.indices = indices;
  32440. vertexData.positions = positions;
  32441. vertexData.normals = normals;
  32442. vertexData.uvs = uvs;
  32443. return vertexData;
  32444. };
  32445. /**
  32446. * Creates the VertexData of the Cylinder or Cone.
  32447. */
  32448. VertexData.CreateCylinder = function (options) {
  32449. var height = options.height || 2;
  32450. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  32451. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  32452. var tessellation = options.tessellation || 24;
  32453. var subdivisions = options.subdivisions || 1;
  32454. var hasRings = options.hasRings ? true : false;
  32455. var enclose = options.enclose ? true : false;
  32456. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  32457. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32458. var faceUV = options.faceUV || new Array(3);
  32459. var faceColors = options.faceColors;
  32460. // default face colors and UV if undefined
  32461. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  32462. var ringNb = (hasRings) ? subdivisions : 1;
  32463. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  32464. var f;
  32465. for (f = 0; f < surfaceNb; f++) {
  32466. if (faceColors && faceColors[f] === undefined) {
  32467. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  32468. }
  32469. }
  32470. for (f = 0; f < surfaceNb; f++) {
  32471. if (faceUV && faceUV[f] === undefined) {
  32472. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  32473. }
  32474. }
  32475. var indices = new Array();
  32476. var positions = new Array();
  32477. var normals = new Array();
  32478. var uvs = new Array();
  32479. var colors = new Array();
  32480. var angle_step = Math.PI * 2 * arc / tessellation;
  32481. var angle;
  32482. var h;
  32483. var radius;
  32484. var tan = (diameterBottom - diameterTop) / 2 / height;
  32485. var ringVertex = BABYLON.Vector3.Zero();
  32486. var ringNormal = BABYLON.Vector3.Zero();
  32487. var ringFirstVertex = BABYLON.Vector3.Zero();
  32488. var ringFirstNormal = BABYLON.Vector3.Zero();
  32489. var quadNormal = BABYLON.Vector3.Zero();
  32490. var Y = BABYLON.Axis.Y;
  32491. // positions, normals, uvs
  32492. var i;
  32493. var j;
  32494. var r;
  32495. var ringIdx = 1;
  32496. var s = 1; // surface index
  32497. var cs = 0;
  32498. var v = 0;
  32499. for (i = 0; i <= subdivisions; i++) {
  32500. h = i / subdivisions;
  32501. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  32502. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  32503. for (r = 0; r < ringIdx; r++) {
  32504. if (hasRings) {
  32505. s += r;
  32506. }
  32507. if (enclose) {
  32508. s += 2 * r;
  32509. }
  32510. for (j = 0; j <= tessellation; j++) {
  32511. angle = j * angle_step;
  32512. // position
  32513. ringVertex.x = Math.cos(-angle) * radius;
  32514. ringVertex.y = -height / 2 + h * height;
  32515. ringVertex.z = Math.sin(-angle) * radius;
  32516. // normal
  32517. if (diameterTop === 0 && i === subdivisions) {
  32518. // if no top cap, reuse former normals
  32519. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  32520. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  32521. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  32522. }
  32523. else {
  32524. ringNormal.x = ringVertex.x;
  32525. ringNormal.z = ringVertex.z;
  32526. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  32527. ringNormal.normalize();
  32528. }
  32529. // keep first ring vertex values for enclose
  32530. if (j === 0) {
  32531. ringFirstVertex.copyFrom(ringVertex);
  32532. ringFirstNormal.copyFrom(ringNormal);
  32533. }
  32534. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  32535. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  32536. if (hasRings) {
  32537. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  32538. }
  32539. else {
  32540. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  32541. }
  32542. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  32543. if (faceColors) {
  32544. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  32545. }
  32546. }
  32547. // if enclose, add four vertices and their dedicated normals
  32548. if (arc !== 1 && enclose) {
  32549. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  32550. positions.push(0, ringVertex.y, 0);
  32551. positions.push(0, ringVertex.y, 0);
  32552. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  32553. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  32554. quadNormal.normalize();
  32555. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  32556. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  32557. quadNormal.normalize();
  32558. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  32559. if (hasRings) {
  32560. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  32561. }
  32562. else {
  32563. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  32564. }
  32565. uvs.push(faceUV[s + 1].x, v);
  32566. uvs.push(faceUV[s + 1].z, v);
  32567. if (hasRings) {
  32568. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  32569. }
  32570. else {
  32571. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  32572. }
  32573. uvs.push(faceUV[s + 2].x, v);
  32574. uvs.push(faceUV[s + 2].z, v);
  32575. if (faceColors) {
  32576. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  32577. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  32578. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  32579. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  32580. }
  32581. }
  32582. if (cs !== s) {
  32583. cs = s;
  32584. }
  32585. }
  32586. }
  32587. // indices
  32588. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  32589. var s;
  32590. i = 0;
  32591. for (s = 0; s < subdivisions; s++) {
  32592. var i0 = 0;
  32593. var i1 = 0;
  32594. var i2 = 0;
  32595. var i3 = 0;
  32596. for (j = 0; j < tessellation; j++) {
  32597. i0 = i * (e + 1) + j;
  32598. i1 = (i + 1) * (e + 1) + j;
  32599. i2 = i * (e + 1) + (j + 1);
  32600. i3 = (i + 1) * (e + 1) + (j + 1);
  32601. indices.push(i0, i1, i2);
  32602. indices.push(i3, i2, i1);
  32603. }
  32604. if (arc !== 1 && enclose) {
  32605. indices.push(i0 + 2, i1 + 2, i2 + 2);
  32606. indices.push(i3 + 2, i2 + 2, i1 + 2);
  32607. indices.push(i0 + 4, i1 + 4, i2 + 4);
  32608. indices.push(i3 + 4, i2 + 4, i1 + 4);
  32609. }
  32610. i = (hasRings) ? (i + 2) : (i + 1);
  32611. }
  32612. // Caps
  32613. var createCylinderCap = function (isTop) {
  32614. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  32615. if (radius === 0) {
  32616. return;
  32617. }
  32618. // Cap positions, normals & uvs
  32619. var angle;
  32620. var circleVector;
  32621. var i;
  32622. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  32623. var c = null;
  32624. if (faceColors) {
  32625. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  32626. }
  32627. // cap center
  32628. var vbase = positions.length / 3;
  32629. var offset = isTop ? height / 2 : -height / 2;
  32630. var center = new BABYLON.Vector3(0, offset, 0);
  32631. positions.push(center.x, center.y, center.z);
  32632. normals.push(0, isTop ? 1 : -1, 0);
  32633. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  32634. if (c) {
  32635. colors.push(c.r, c.g, c.b, c.a);
  32636. }
  32637. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  32638. for (i = 0; i <= tessellation; i++) {
  32639. angle = Math.PI * 2 * i * arc / tessellation;
  32640. var cos = Math.cos(-angle);
  32641. var sin = Math.sin(-angle);
  32642. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  32643. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  32644. positions.push(circleVector.x, circleVector.y, circleVector.z);
  32645. normals.push(0, isTop ? 1 : -1, 0);
  32646. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  32647. if (c) {
  32648. colors.push(c.r, c.g, c.b, c.a);
  32649. }
  32650. }
  32651. // Cap indices
  32652. for (i = 0; i < tessellation; i++) {
  32653. if (!isTop) {
  32654. indices.push(vbase);
  32655. indices.push(vbase + (i + 1));
  32656. indices.push(vbase + (i + 2));
  32657. }
  32658. else {
  32659. indices.push(vbase);
  32660. indices.push(vbase + (i + 2));
  32661. indices.push(vbase + (i + 1));
  32662. }
  32663. }
  32664. };
  32665. // add caps to geometry
  32666. createCylinderCap(false);
  32667. createCylinderCap(true);
  32668. // Sides
  32669. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  32670. var vertexData = new VertexData();
  32671. vertexData.indices = indices;
  32672. vertexData.positions = positions;
  32673. vertexData.normals = normals;
  32674. vertexData.uvs = uvs;
  32675. if (faceColors) {
  32676. vertexData.colors = colors;
  32677. }
  32678. return vertexData;
  32679. };
  32680. /**
  32681. * Creates the VertexData of the Torus.
  32682. */
  32683. VertexData.CreateTorus = function (options) {
  32684. var indices = [];
  32685. var positions = [];
  32686. var normals = [];
  32687. var uvs = [];
  32688. var diameter = options.diameter || 1;
  32689. var thickness = options.thickness || 0.5;
  32690. var tessellation = options.tessellation || 16;
  32691. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32692. var stride = tessellation + 1;
  32693. for (var i = 0; i <= tessellation; i++) {
  32694. var u = i / tessellation;
  32695. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  32696. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  32697. for (var j = 0; j <= tessellation; j++) {
  32698. var v = 1 - j / tessellation;
  32699. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  32700. var dx = Math.cos(innerAngle);
  32701. var dy = Math.sin(innerAngle);
  32702. // Create a vertex.
  32703. var normal = new BABYLON.Vector3(dx, dy, 0);
  32704. var position = normal.scale(thickness / 2);
  32705. var textureCoordinate = new BABYLON.Vector2(u, v);
  32706. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  32707. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  32708. positions.push(position.x, position.y, position.z);
  32709. normals.push(normal.x, normal.y, normal.z);
  32710. uvs.push(textureCoordinate.x, textureCoordinate.y);
  32711. // And create indices for two triangles.
  32712. var nextI = (i + 1) % stride;
  32713. var nextJ = (j + 1) % stride;
  32714. indices.push(i * stride + j);
  32715. indices.push(i * stride + nextJ);
  32716. indices.push(nextI * stride + j);
  32717. indices.push(i * stride + nextJ);
  32718. indices.push(nextI * stride + nextJ);
  32719. indices.push(nextI * stride + j);
  32720. }
  32721. }
  32722. // Sides
  32723. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  32724. // Result
  32725. var vertexData = new VertexData();
  32726. vertexData.indices = indices;
  32727. vertexData.positions = positions;
  32728. vertexData.normals = normals;
  32729. vertexData.uvs = uvs;
  32730. return vertexData;
  32731. };
  32732. /**
  32733. * Creates the VertexData of the LineSystem.
  32734. */
  32735. VertexData.CreateLineSystem = function (options) {
  32736. var indices = [];
  32737. var positions = [];
  32738. var lines = options.lines;
  32739. var colors = options.colors;
  32740. var vertexColors = [];
  32741. var idx = 0;
  32742. for (var l = 0; l < lines.length; l++) {
  32743. var points = lines[l];
  32744. for (var index = 0; index < points.length; index++) {
  32745. positions.push(points[index].x, points[index].y, points[index].z);
  32746. if (colors) {
  32747. var color = colors[l];
  32748. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  32749. }
  32750. if (index > 0) {
  32751. indices.push(idx - 1);
  32752. indices.push(idx);
  32753. }
  32754. idx++;
  32755. }
  32756. }
  32757. var vertexData = new VertexData();
  32758. vertexData.indices = indices;
  32759. vertexData.positions = positions;
  32760. if (colors) {
  32761. vertexData.colors = vertexColors;
  32762. }
  32763. return vertexData;
  32764. };
  32765. /**
  32766. * Create the VertexData of the DashedLines.
  32767. */
  32768. VertexData.CreateDashedLines = function (options) {
  32769. var dashSize = options.dashSize || 3;
  32770. var gapSize = options.gapSize || 1;
  32771. var dashNb = options.dashNb || 200;
  32772. var points = options.points;
  32773. var positions = new Array();
  32774. var indices = new Array();
  32775. var curvect = BABYLON.Vector3.Zero();
  32776. var lg = 0;
  32777. var nb = 0;
  32778. var shft = 0;
  32779. var dashshft = 0;
  32780. var curshft = 0;
  32781. var idx = 0;
  32782. var i = 0;
  32783. for (i = 0; i < points.length - 1; i++) {
  32784. points[i + 1].subtractToRef(points[i], curvect);
  32785. lg += curvect.length();
  32786. }
  32787. shft = lg / dashNb;
  32788. dashshft = dashSize * shft / (dashSize + gapSize);
  32789. for (i = 0; i < points.length - 1; i++) {
  32790. points[i + 1].subtractToRef(points[i], curvect);
  32791. nb = Math.floor(curvect.length() / shft);
  32792. curvect.normalize();
  32793. for (var j = 0; j < nb; j++) {
  32794. curshft = shft * j;
  32795. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  32796. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  32797. indices.push(idx, idx + 1);
  32798. idx += 2;
  32799. }
  32800. }
  32801. // Result
  32802. var vertexData = new VertexData();
  32803. vertexData.positions = positions;
  32804. vertexData.indices = indices;
  32805. return vertexData;
  32806. };
  32807. /**
  32808. * Creates the VertexData of the Ground.
  32809. */
  32810. VertexData.CreateGround = function (options) {
  32811. var indices = [];
  32812. var positions = [];
  32813. var normals = [];
  32814. var uvs = [];
  32815. var row, col;
  32816. var width = options.width || 1;
  32817. var height = options.height || 1;
  32818. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  32819. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  32820. for (row = 0; row <= subdivisionsY; row++) {
  32821. for (col = 0; col <= subdivisionsX; col++) {
  32822. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  32823. var normal = new BABYLON.Vector3(0, 1.0, 0);
  32824. positions.push(position.x, position.y, position.z);
  32825. normals.push(normal.x, normal.y, normal.z);
  32826. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  32827. }
  32828. }
  32829. for (row = 0; row < subdivisionsY; row++) {
  32830. for (col = 0; col < subdivisionsX; col++) {
  32831. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  32832. indices.push(col + 1 + row * (subdivisionsX + 1));
  32833. indices.push(col + row * (subdivisionsX + 1));
  32834. indices.push(col + (row + 1) * (subdivisionsX + 1));
  32835. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  32836. indices.push(col + row * (subdivisionsX + 1));
  32837. }
  32838. }
  32839. // Result
  32840. var vertexData = new VertexData();
  32841. vertexData.indices = indices;
  32842. vertexData.positions = positions;
  32843. vertexData.normals = normals;
  32844. vertexData.uvs = uvs;
  32845. return vertexData;
  32846. };
  32847. /**
  32848. * Creates the VertexData of the TiledGround.
  32849. */
  32850. VertexData.CreateTiledGround = function (options) {
  32851. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  32852. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  32853. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  32854. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  32855. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  32856. var precision = options.precision || { w: 1, h: 1 };
  32857. var indices = new Array();
  32858. var positions = new Array();
  32859. var normals = new Array();
  32860. var uvs = new Array();
  32861. var row, col, tileRow, tileCol;
  32862. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  32863. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  32864. precision.w = (precision.w < 1) ? 1 : precision.w;
  32865. precision.h = (precision.h < 1) ? 1 : precision.h;
  32866. var tileSize = {
  32867. 'w': (xmax - xmin) / subdivisions.w,
  32868. 'h': (zmax - zmin) / subdivisions.h
  32869. };
  32870. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  32871. // Indices
  32872. var base = positions.length / 3;
  32873. var rowLength = precision.w + 1;
  32874. for (row = 0; row < precision.h; row++) {
  32875. for (col = 0; col < precision.w; col++) {
  32876. var square = [
  32877. base + col + row * rowLength,
  32878. base + (col + 1) + row * rowLength,
  32879. base + (col + 1) + (row + 1) * rowLength,
  32880. base + col + (row + 1) * rowLength
  32881. ];
  32882. indices.push(square[1]);
  32883. indices.push(square[2]);
  32884. indices.push(square[3]);
  32885. indices.push(square[0]);
  32886. indices.push(square[1]);
  32887. indices.push(square[3]);
  32888. }
  32889. }
  32890. // Position, normals and uvs
  32891. var position = BABYLON.Vector3.Zero();
  32892. var normal = new BABYLON.Vector3(0, 1.0, 0);
  32893. for (row = 0; row <= precision.h; row++) {
  32894. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  32895. for (col = 0; col <= precision.w; col++) {
  32896. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  32897. position.y = 0;
  32898. positions.push(position.x, position.y, position.z);
  32899. normals.push(normal.x, normal.y, normal.z);
  32900. uvs.push(col / precision.w, row / precision.h);
  32901. }
  32902. }
  32903. }
  32904. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  32905. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  32906. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  32907. }
  32908. }
  32909. // Result
  32910. var vertexData = new VertexData();
  32911. vertexData.indices = indices;
  32912. vertexData.positions = positions;
  32913. vertexData.normals = normals;
  32914. vertexData.uvs = uvs;
  32915. return vertexData;
  32916. };
  32917. /**
  32918. * Creates the VertexData of the Ground designed from a heightmap.
  32919. */
  32920. VertexData.CreateGroundFromHeightMap = function (options) {
  32921. var indices = [];
  32922. var positions = [];
  32923. var normals = [];
  32924. var uvs = [];
  32925. var row, col;
  32926. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  32927. // Vertices
  32928. for (row = 0; row <= options.subdivisions; row++) {
  32929. for (col = 0; col <= options.subdivisions; col++) {
  32930. 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));
  32931. // Compute height
  32932. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  32933. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  32934. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  32935. var r = options.buffer[pos] / 255.0;
  32936. var g = options.buffer[pos + 1] / 255.0;
  32937. var b = options.buffer[pos + 2] / 255.0;
  32938. var gradient = r * filter.r + g * filter.g + b * filter.b;
  32939. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  32940. // Add vertex
  32941. positions.push(position.x, position.y, position.z);
  32942. normals.push(0, 0, 0);
  32943. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  32944. }
  32945. }
  32946. // Indices
  32947. for (row = 0; row < options.subdivisions; row++) {
  32948. for (col = 0; col < options.subdivisions; col++) {
  32949. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  32950. indices.push(col + 1 + row * (options.subdivisions + 1));
  32951. indices.push(col + row * (options.subdivisions + 1));
  32952. indices.push(col + (row + 1) * (options.subdivisions + 1));
  32953. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  32954. indices.push(col + row * (options.subdivisions + 1));
  32955. }
  32956. }
  32957. // Normals
  32958. VertexData.ComputeNormals(positions, indices, normals);
  32959. // Result
  32960. var vertexData = new VertexData();
  32961. vertexData.indices = indices;
  32962. vertexData.positions = positions;
  32963. vertexData.normals = normals;
  32964. vertexData.uvs = uvs;
  32965. return vertexData;
  32966. };
  32967. /**
  32968. * Creates the VertexData of the Plane.
  32969. */
  32970. VertexData.CreatePlane = function (options) {
  32971. var indices = [];
  32972. var positions = [];
  32973. var normals = [];
  32974. var uvs = [];
  32975. var width = options.width || options.size || 1;
  32976. var height = options.height || options.size || 1;
  32977. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32978. // Vertices
  32979. var halfWidth = width / 2.0;
  32980. var halfHeight = height / 2.0;
  32981. positions.push(-halfWidth, -halfHeight, 0);
  32982. normals.push(0, 0, -1.0);
  32983. uvs.push(0.0, 0.0);
  32984. positions.push(halfWidth, -halfHeight, 0);
  32985. normals.push(0, 0, -1.0);
  32986. uvs.push(1.0, 0.0);
  32987. positions.push(halfWidth, halfHeight, 0);
  32988. normals.push(0, 0, -1.0);
  32989. uvs.push(1.0, 1.0);
  32990. positions.push(-halfWidth, halfHeight, 0);
  32991. normals.push(0, 0, -1.0);
  32992. uvs.push(0.0, 1.0);
  32993. // Indices
  32994. indices.push(0);
  32995. indices.push(1);
  32996. indices.push(2);
  32997. indices.push(0);
  32998. indices.push(2);
  32999. indices.push(3);
  33000. // Sides
  33001. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33002. // Result
  33003. var vertexData = new VertexData();
  33004. vertexData.indices = indices;
  33005. vertexData.positions = positions;
  33006. vertexData.normals = normals;
  33007. vertexData.uvs = uvs;
  33008. return vertexData;
  33009. };
  33010. /**
  33011. * Creates the VertexData of the Disc or regular Polygon.
  33012. */
  33013. VertexData.CreateDisc = function (options) {
  33014. var positions = new Array();
  33015. var indices = new Array();
  33016. var normals = new Array();
  33017. var uvs = new Array();
  33018. var radius = options.radius || 0.5;
  33019. var tessellation = options.tessellation || 64;
  33020. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  33021. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33022. // positions and uvs
  33023. positions.push(0, 0, 0); // disc center first
  33024. uvs.push(0.5, 0.5);
  33025. var theta = Math.PI * 2 * arc;
  33026. var step = theta / tessellation;
  33027. for (var a = 0; a < theta; a += step) {
  33028. var x = Math.cos(a);
  33029. var y = Math.sin(a);
  33030. var u = (x + 1) / 2;
  33031. var v = (1 - y) / 2;
  33032. positions.push(radius * x, radius * y, 0);
  33033. uvs.push(u, v);
  33034. }
  33035. if (arc === 1) {
  33036. positions.push(positions[3], positions[4], positions[5]); // close the circle
  33037. uvs.push(uvs[2], uvs[3]);
  33038. }
  33039. //indices
  33040. var vertexNb = positions.length / 3;
  33041. for (var i = 1; i < vertexNb - 1; i++) {
  33042. indices.push(i + 1, 0, i);
  33043. }
  33044. // result
  33045. VertexData.ComputeNormals(positions, indices, normals);
  33046. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33047. var vertexData = new VertexData();
  33048. vertexData.indices = indices;
  33049. vertexData.positions = positions;
  33050. vertexData.normals = normals;
  33051. vertexData.uvs = uvs;
  33052. return vertexData;
  33053. };
  33054. /**
  33055. * Re-creates the VertexData of the Polygon for sideOrientation.
  33056. */
  33057. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  33058. var faceUV = fUV || new Array(3);
  33059. var faceColors = fColors;
  33060. var colors = [];
  33061. // default face colors and UV if undefined
  33062. for (var f = 0; f < 3; f++) {
  33063. if (faceUV[f] === undefined) {
  33064. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  33065. }
  33066. if (faceColors && faceColors[f] === undefined) {
  33067. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  33068. }
  33069. }
  33070. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33071. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33072. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  33073. var indices = polygon.getIndices();
  33074. // set face colours and textures
  33075. var idx = 0;
  33076. var face = 0;
  33077. for (var index = 0; index < normals.length; index += 3) {
  33078. //Edge Face no. 1
  33079. if (Math.abs(normals[index + 1]) < 0.001) {
  33080. face = 1;
  33081. }
  33082. //Top Face no. 0
  33083. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  33084. face = 0;
  33085. }
  33086. //Bottom Face no. 2
  33087. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  33088. face = 2;
  33089. }
  33090. idx = index / 3;
  33091. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  33092. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  33093. if (faceColors) {
  33094. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  33095. }
  33096. }
  33097. // sides
  33098. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  33099. // Result
  33100. var vertexData = new VertexData();
  33101. vertexData.indices = indices;
  33102. vertexData.positions = positions;
  33103. vertexData.normals = normals;
  33104. vertexData.uvs = uvs;
  33105. if (faceColors) {
  33106. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  33107. vertexData.colors = totalColors;
  33108. }
  33109. return vertexData;
  33110. };
  33111. /**
  33112. * Creates the VertexData of the IcoSphere.
  33113. */
  33114. VertexData.CreateIcoSphere = function (options) {
  33115. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33116. var radius = options.radius || 1;
  33117. var flat = (options.flat === undefined) ? true : options.flat;
  33118. var subdivisions = options.subdivisions || 4;
  33119. var radiusX = options.radiusX || radius;
  33120. var radiusY = options.radiusY || radius;
  33121. var radiusZ = options.radiusZ || radius;
  33122. var t = (1 + Math.sqrt(5)) / 2;
  33123. // 12 vertex x,y,z
  33124. var ico_vertices = [
  33125. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  33126. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  33127. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  33128. ];
  33129. // index of 3 vertex makes a face of icopshere
  33130. var ico_indices = [
  33131. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  33132. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  33133. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  33134. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  33135. ];
  33136. // vertex for uv have aliased position, not for UV
  33137. var vertices_unalias_id = [
  33138. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  33139. // vertex alias
  33140. 0,
  33141. 2,
  33142. 3,
  33143. 3,
  33144. 3,
  33145. 4,
  33146. 7,
  33147. 8,
  33148. 9,
  33149. 9,
  33150. 10,
  33151. 11 // 23: B + 12
  33152. ];
  33153. // uv as integer step (not pixels !)
  33154. var ico_vertexuv = [
  33155. 5, 1, 3, 1, 6, 4, 0, 0,
  33156. 5, 3, 4, 2, 2, 2, 4, 0,
  33157. 2, 0, 1, 1, 6, 0, 6, 2,
  33158. // vertex alias (for same vertex on different faces)
  33159. 0, 4,
  33160. 3, 3,
  33161. 4, 4,
  33162. 3, 1,
  33163. 4, 2,
  33164. 4, 4,
  33165. 0, 2,
  33166. 1, 1,
  33167. 2, 2,
  33168. 3, 3,
  33169. 1, 3,
  33170. 2, 4 // 23: B + 12
  33171. ];
  33172. // Vertices[0, 1, ...9, A, B] : position on UV plane
  33173. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  33174. // First island of uv mapping
  33175. // v = 4h 3+ 2
  33176. // v = 3h 9+ 4
  33177. // v = 2h 9+ 5 B
  33178. // v = 1h 9 1 0
  33179. // v = 0h 3 8 7 A
  33180. // u = 0 1 2 3 4 5 6 *a
  33181. // Second island of uv mapping
  33182. // v = 4h 0+ B+ 4+
  33183. // v = 3h A+ 2+
  33184. // v = 2h 7+ 6 3+
  33185. // v = 1h 8+ 3+
  33186. // v = 0h
  33187. // u = 0 1 2 3 4 5 6 *a
  33188. // Face layout on texture UV mapping
  33189. // ============
  33190. // \ 4 /\ 16 / ======
  33191. // \ / \ / /\ 11 /
  33192. // \/ 7 \/ / \ /
  33193. // ======= / 10 \/
  33194. // /\ 17 /\ =======
  33195. // / \ / \ \ 15 /\
  33196. // / 8 \/ 12 \ \ / \
  33197. // ============ \/ 6 \
  33198. // \ 18 /\ ============
  33199. // \ / \ \ 5 /\ 0 /
  33200. // \/ 13 \ \ / \ /
  33201. // ======= \/ 1 \/
  33202. // =============
  33203. // /\ 19 /\ 2 /\
  33204. // / \ / \ / \
  33205. // / 14 \/ 9 \/ 3 \
  33206. // ===================
  33207. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  33208. var ustep = 138 / 1024;
  33209. var vstep = 239 / 1024;
  33210. var uoffset = 60 / 1024;
  33211. var voffset = 26 / 1024;
  33212. // Second island should have margin, not to touch the first island
  33213. // avoid any borderline artefact in pixel rounding
  33214. var island_u_offset = -40 / 1024;
  33215. var island_v_offset = +20 / 1024;
  33216. // face is either island 0 or 1 :
  33217. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  33218. var island = [
  33219. 0, 0, 0, 0, 1,
  33220. 0, 0, 1, 1, 0,
  33221. 0, 0, 1, 1, 0,
  33222. 0, 1, 1, 1, 0 // 15 - 19
  33223. ];
  33224. var indices = new Array();
  33225. var positions = new Array();
  33226. var normals = new Array();
  33227. var uvs = new Array();
  33228. var current_indice = 0;
  33229. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  33230. var face_vertex_pos = new Array(3);
  33231. var face_vertex_uv = new Array(3);
  33232. var v012;
  33233. for (v012 = 0; v012 < 3; v012++) {
  33234. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  33235. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  33236. }
  33237. // create all with normals
  33238. for (var face = 0; face < 20; face++) {
  33239. // 3 vertex per face
  33240. for (v012 = 0; v012 < 3; v012++) {
  33241. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  33242. var v_id = ico_indices[3 * face + v012];
  33243. // vertex have 3D position (x,y,z)
  33244. 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]);
  33245. // Normalize to get normal, then scale to radius
  33246. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  33247. // uv Coordinates from vertex ID
  33248. 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);
  33249. }
  33250. // Subdivide the face (interpolate pos, norm, uv)
  33251. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  33252. // - norm is linear interpolation of vertex corner normal
  33253. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  33254. // - uv is linear interpolation
  33255. //
  33256. // Topology is as below for sub-divide by 2
  33257. // vertex shown as v0,v1,v2
  33258. // interp index is i1 to progress in range [v0,v1[
  33259. // interp index is i2 to progress in range [v0,v2[
  33260. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  33261. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  33262. //
  33263. //
  33264. // i2 v2
  33265. // ^ ^
  33266. // / / \
  33267. // / / \
  33268. // / / \
  33269. // / / (0,1) \
  33270. // / #---------\
  33271. // / / \ (0,0)'/ \
  33272. // / / \ / \
  33273. // / / \ / \
  33274. // / / (0,0) \ / (1,0) \
  33275. // / #---------#---------\
  33276. // v0 v1
  33277. //
  33278. // --------------------> i1
  33279. //
  33280. // interp of (i1,i2):
  33281. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  33282. // along i1 : lerp(x0,x1, i1/(S-i2))
  33283. //
  33284. // centroid of triangle is needed to get help normal computation
  33285. // (c1,c2) are used for centroid location
  33286. var interp_vertex = function (i1, i2, c1, c2) {
  33287. // vertex is interpolated from
  33288. // - face_vertex_pos[0..2]
  33289. // - face_vertex_uv[0..2]
  33290. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  33291. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  33292. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  33293. pos_interp.normalize();
  33294. var vertex_normal;
  33295. if (flat) {
  33296. // in flat mode, recalculate normal as face centroid normal
  33297. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  33298. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  33299. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  33300. }
  33301. else {
  33302. // in smooth mode, recalculate normal from each single vertex position
  33303. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  33304. }
  33305. // Vertex normal need correction due to X,Y,Z radius scaling
  33306. vertex_normal.x /= radiusX;
  33307. vertex_normal.y /= radiusY;
  33308. vertex_normal.z /= radiusZ;
  33309. vertex_normal.normalize();
  33310. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  33311. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  33312. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  33313. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  33314. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  33315. uvs.push(uv_interp.x, uv_interp.y);
  33316. // push each vertex has member of a face
  33317. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  33318. indices.push(current_indice);
  33319. current_indice++;
  33320. };
  33321. for (var i2 = 0; i2 < subdivisions; i2++) {
  33322. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  33323. // face : (i1,i2) for /\ :
  33324. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  33325. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  33326. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  33327. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  33328. if (i1 + i2 + 1 < subdivisions) {
  33329. // face : (i1,i2)' for \/ :
  33330. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  33331. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  33332. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  33333. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  33334. }
  33335. }
  33336. }
  33337. }
  33338. // Sides
  33339. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33340. // Result
  33341. var vertexData = new VertexData();
  33342. vertexData.indices = indices;
  33343. vertexData.positions = positions;
  33344. vertexData.normals = normals;
  33345. vertexData.uvs = uvs;
  33346. return vertexData;
  33347. };
  33348. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  33349. /**
  33350. * Creates the VertexData of the Polyhedron.
  33351. */
  33352. VertexData.CreatePolyhedron = function (options) {
  33353. // provided polyhedron types :
  33354. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  33355. // 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)
  33356. var polyhedra = [];
  33357. 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]] };
  33358. 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]] };
  33359. polyhedra[2] = {
  33360. 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]],
  33361. 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]]
  33362. };
  33363. polyhedra[3] = {
  33364. 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]],
  33365. 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]]
  33366. };
  33367. polyhedra[4] = {
  33368. 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]],
  33369. 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]]
  33370. };
  33371. 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]] };
  33372. 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]] };
  33373. 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]] };
  33374. 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]] };
  33375. 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]] };
  33376. 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]] };
  33377. 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]] };
  33378. 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]] };
  33379. 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]] };
  33380. polyhedra[14] = {
  33381. 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]],
  33382. 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]]
  33383. };
  33384. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  33385. var size = options.size;
  33386. var sizeX = options.sizeX || size || 1;
  33387. var sizeY = options.sizeY || size || 1;
  33388. var sizeZ = options.sizeZ || size || 1;
  33389. var data = options.custom || polyhedra[type];
  33390. var nbfaces = data.face.length;
  33391. var faceUV = options.faceUV || new Array(nbfaces);
  33392. var faceColors = options.faceColors;
  33393. var flat = (options.flat === undefined) ? true : options.flat;
  33394. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33395. var positions = new Array();
  33396. var indices = new Array();
  33397. var normals = new Array();
  33398. var uvs = new Array();
  33399. var colors = new Array();
  33400. var index = 0;
  33401. var faceIdx = 0; // face cursor in the array "indexes"
  33402. var indexes = new Array();
  33403. var i = 0;
  33404. var f = 0;
  33405. var u, v, ang, x, y, tmp;
  33406. // default face colors and UV if undefined
  33407. if (flat) {
  33408. for (f = 0; f < nbfaces; f++) {
  33409. if (faceColors && faceColors[f] === undefined) {
  33410. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  33411. }
  33412. if (faceUV && faceUV[f] === undefined) {
  33413. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  33414. }
  33415. }
  33416. }
  33417. if (!flat) {
  33418. for (i = 0; i < data.vertex.length; i++) {
  33419. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  33420. uvs.push(0, 0);
  33421. }
  33422. for (f = 0; f < nbfaces; f++) {
  33423. for (i = 0; i < data.face[f].length - 2; i++) {
  33424. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  33425. }
  33426. }
  33427. }
  33428. else {
  33429. for (f = 0; f < nbfaces; f++) {
  33430. var fl = data.face[f].length; // number of vertices of the current face
  33431. ang = 2 * Math.PI / fl;
  33432. x = 0.5 * Math.tan(ang / 2);
  33433. y = 0.5;
  33434. // positions, uvs, colors
  33435. for (i = 0; i < fl; i++) {
  33436. // positions
  33437. 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);
  33438. indexes.push(index);
  33439. index++;
  33440. // uvs
  33441. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  33442. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  33443. uvs.push(u, v);
  33444. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  33445. y = x * Math.sin(ang) + y * Math.cos(ang);
  33446. x = tmp;
  33447. // colors
  33448. if (faceColors) {
  33449. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  33450. }
  33451. }
  33452. // indices from indexes
  33453. for (i = 0; i < fl - 2; i++) {
  33454. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  33455. }
  33456. faceIdx += fl;
  33457. }
  33458. }
  33459. VertexData.ComputeNormals(positions, indices, normals);
  33460. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33461. var vertexData = new VertexData();
  33462. vertexData.positions = positions;
  33463. vertexData.indices = indices;
  33464. vertexData.normals = normals;
  33465. vertexData.uvs = uvs;
  33466. if (faceColors && flat) {
  33467. vertexData.colors = colors;
  33468. }
  33469. return vertexData;
  33470. };
  33471. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  33472. /**
  33473. * Creates the VertexData of the Torus Knot.
  33474. */
  33475. VertexData.CreateTorusKnot = function (options) {
  33476. var indices = new Array();
  33477. var positions = new Array();
  33478. var normals = new Array();
  33479. var uvs = new Array();
  33480. var radius = options.radius || 2;
  33481. var tube = options.tube || 0.5;
  33482. var radialSegments = options.radialSegments || 32;
  33483. var tubularSegments = options.tubularSegments || 32;
  33484. var p = options.p || 2;
  33485. var q = options.q || 3;
  33486. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33487. // Helper
  33488. var getPos = function (angle) {
  33489. var cu = Math.cos(angle);
  33490. var su = Math.sin(angle);
  33491. var quOverP = q / p * angle;
  33492. var cs = Math.cos(quOverP);
  33493. var tx = radius * (2 + cs) * 0.5 * cu;
  33494. var ty = radius * (2 + cs) * su * 0.5;
  33495. var tz = radius * Math.sin(quOverP) * 0.5;
  33496. return new BABYLON.Vector3(tx, ty, tz);
  33497. };
  33498. // Vertices
  33499. var i;
  33500. var j;
  33501. for (i = 0; i <= radialSegments; i++) {
  33502. var modI = i % radialSegments;
  33503. var u = modI / radialSegments * 2 * p * Math.PI;
  33504. var p1 = getPos(u);
  33505. var p2 = getPos(u + 0.01);
  33506. var tang = p2.subtract(p1);
  33507. var n = p2.add(p1);
  33508. var bitan = BABYLON.Vector3.Cross(tang, n);
  33509. n = BABYLON.Vector3.Cross(bitan, tang);
  33510. bitan.normalize();
  33511. n.normalize();
  33512. for (j = 0; j < tubularSegments; j++) {
  33513. var modJ = j % tubularSegments;
  33514. var v = modJ / tubularSegments * 2 * Math.PI;
  33515. var cx = -tube * Math.cos(v);
  33516. var cy = tube * Math.sin(v);
  33517. positions.push(p1.x + cx * n.x + cy * bitan.x);
  33518. positions.push(p1.y + cx * n.y + cy * bitan.y);
  33519. positions.push(p1.z + cx * n.z + cy * bitan.z);
  33520. uvs.push(i / radialSegments);
  33521. uvs.push(j / tubularSegments);
  33522. }
  33523. }
  33524. for (i = 0; i < radialSegments; i++) {
  33525. for (j = 0; j < tubularSegments; j++) {
  33526. var jNext = (j + 1) % tubularSegments;
  33527. var a = i * tubularSegments + j;
  33528. var b = (i + 1) * tubularSegments + j;
  33529. var c = (i + 1) * tubularSegments + jNext;
  33530. var d = i * tubularSegments + jNext;
  33531. indices.push(d);
  33532. indices.push(b);
  33533. indices.push(a);
  33534. indices.push(d);
  33535. indices.push(c);
  33536. indices.push(b);
  33537. }
  33538. }
  33539. // Normals
  33540. VertexData.ComputeNormals(positions, indices, normals);
  33541. // Sides
  33542. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33543. // Result
  33544. var vertexData = new VertexData();
  33545. vertexData.indices = indices;
  33546. vertexData.positions = positions;
  33547. vertexData.normals = normals;
  33548. vertexData.uvs = uvs;
  33549. return vertexData;
  33550. };
  33551. // Tools
  33552. /**
  33553. * @param {any} - positions (number[] or Float32Array)
  33554. * @param {any} - indices (number[] or Uint16Array)
  33555. * @param {any} - normals (number[] or Float32Array)
  33556. * options (optional) :
  33557. * facetPositions : optional array of facet positions (vector3)
  33558. * facetNormals : optional array of facet normals (vector3)
  33559. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  33560. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  33561. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  33562. * bbSize : optional bounding box size data, required for facetPartitioning computation
  33563. * bInfo : optional bounding info, required for facetPartitioning computation
  33564. * useRightHandedSystem: optional boolean to for right handed system computation
  33565. * depthSort : optional boolean to enable the facet depth sort computation
  33566. * distanceTo : optional Vector3 to compute the facet depth from this location
  33567. * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  33568. */
  33569. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  33570. // temporary scalar variables
  33571. var index = 0; // facet index
  33572. var p1p2x = 0.0; // p1p2 vector x coordinate
  33573. var p1p2y = 0.0; // p1p2 vector y coordinate
  33574. var p1p2z = 0.0; // p1p2 vector z coordinate
  33575. var p3p2x = 0.0; // p3p2 vector x coordinate
  33576. var p3p2y = 0.0; // p3p2 vector y coordinate
  33577. var p3p2z = 0.0; // p3p2 vector z coordinate
  33578. var faceNormalx = 0.0; // facet normal x coordinate
  33579. var faceNormaly = 0.0; // facet normal y coordinate
  33580. var faceNormalz = 0.0; // facet normal z coordinate
  33581. var length = 0.0; // facet normal length before normalization
  33582. var v1x = 0; // vector1 x index in the positions array
  33583. var v1y = 0; // vector1 y index in the positions array
  33584. var v1z = 0; // vector1 z index in the positions array
  33585. var v2x = 0; // vector2 x index in the positions array
  33586. var v2y = 0; // vector2 y index in the positions array
  33587. var v2z = 0; // vector2 z index in the positions array
  33588. var v3x = 0; // vector3 x index in the positions array
  33589. var v3y = 0; // vector3 y index in the positions array
  33590. var v3z = 0; // vector3 z index in the positions array
  33591. var computeFacetNormals = false;
  33592. var computeFacetPositions = false;
  33593. var computeFacetPartitioning = false;
  33594. var computeDepthSort = false;
  33595. var faceNormalSign = 1;
  33596. var ratio = 0;
  33597. var distanceTo = null;
  33598. if (options) {
  33599. computeFacetNormals = (options.facetNormals) ? true : false;
  33600. computeFacetPositions = (options.facetPositions) ? true : false;
  33601. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  33602. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  33603. ratio = options.ratio || 0;
  33604. computeDepthSort = (options.depthSort) ? true : false;
  33605. distanceTo = (options.distanceTo);
  33606. if (computeDepthSort) {
  33607. if (distanceTo === undefined) {
  33608. distanceTo = BABYLON.Vector3.Zero();
  33609. }
  33610. var depthSortedFacets = options.depthSortedFacets;
  33611. }
  33612. }
  33613. // facetPartitioning reinit if needed
  33614. var xSubRatio = 0;
  33615. var ySubRatio = 0;
  33616. var zSubRatio = 0;
  33617. var subSq = 0;
  33618. if (computeFacetPartitioning && options && options.bbSize) {
  33619. var ox = 0; // X partitioning index for facet position
  33620. var oy = 0; // Y partinioning index for facet position
  33621. var oz = 0; // Z partinioning index for facet position
  33622. var b1x = 0; // X partitioning index for facet v1 vertex
  33623. var b1y = 0; // Y partitioning index for facet v1 vertex
  33624. var b1z = 0; // z partitioning index for facet v1 vertex
  33625. var b2x = 0; // X partitioning index for facet v2 vertex
  33626. var b2y = 0; // Y partitioning index for facet v2 vertex
  33627. var b2z = 0; // Z partitioning index for facet v2 vertex
  33628. var b3x = 0; // X partitioning index for facet v3 vertex
  33629. var b3y = 0; // Y partitioning index for facet v3 vertex
  33630. var b3z = 0; // Z partitioning index for facet v3 vertex
  33631. var block_idx_o = 0; // facet barycenter block index
  33632. var block_idx_v1 = 0; // v1 vertex block index
  33633. var block_idx_v2 = 0; // v2 vertex block index
  33634. var block_idx_v3 = 0; // v3 vertex block index
  33635. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  33636. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  33637. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  33638. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  33639. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  33640. subSq = options.subDiv.max * options.subDiv.max;
  33641. options.facetPartitioning.length = 0;
  33642. }
  33643. // reset the normals
  33644. for (index = 0; index < positions.length; index++) {
  33645. normals[index] = 0.0;
  33646. }
  33647. // Loop : 1 indice triplet = 1 facet
  33648. var nbFaces = (indices.length / 3) | 0;
  33649. for (index = 0; index < nbFaces; index++) {
  33650. // get the indexes of the coordinates of each vertex of the facet
  33651. v1x = indices[index * 3] * 3;
  33652. v1y = v1x + 1;
  33653. v1z = v1x + 2;
  33654. v2x = indices[index * 3 + 1] * 3;
  33655. v2y = v2x + 1;
  33656. v2z = v2x + 2;
  33657. v3x = indices[index * 3 + 2] * 3;
  33658. v3y = v3x + 1;
  33659. v3z = v3x + 2;
  33660. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  33661. p1p2y = positions[v1y] - positions[v2y];
  33662. p1p2z = positions[v1z] - positions[v2z];
  33663. p3p2x = positions[v3x] - positions[v2x];
  33664. p3p2y = positions[v3y] - positions[v2y];
  33665. p3p2z = positions[v3z] - positions[v2z];
  33666. // compute the face normal with the cross product
  33667. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  33668. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  33669. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  33670. // normalize this normal and store it in the array facetData
  33671. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  33672. length = (length === 0) ? 1.0 : length;
  33673. faceNormalx /= length;
  33674. faceNormaly /= length;
  33675. faceNormalz /= length;
  33676. if (computeFacetNormals && options) {
  33677. options.facetNormals[index].x = faceNormalx;
  33678. options.facetNormals[index].y = faceNormaly;
  33679. options.facetNormals[index].z = faceNormalz;
  33680. }
  33681. if (computeFacetPositions && options) {
  33682. // compute and the facet barycenter coordinates in the array facetPositions
  33683. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  33684. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  33685. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  33686. }
  33687. if (computeFacetPartitioning && options) {
  33688. // store the facet indexes in arrays in the main facetPartitioning array :
  33689. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  33690. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  33691. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  33692. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  33693. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  33694. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  33695. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  33696. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  33697. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  33698. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  33699. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  33700. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  33701. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  33702. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  33703. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  33704. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  33705. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  33706. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  33707. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  33708. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  33709. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  33710. // push each facet index in each block containing the vertex
  33711. options.facetPartitioning[block_idx_v1].push(index);
  33712. if (block_idx_v2 != block_idx_v1) {
  33713. options.facetPartitioning[block_idx_v2].push(index);
  33714. }
  33715. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  33716. options.facetPartitioning[block_idx_v3].push(index);
  33717. }
  33718. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  33719. options.facetPartitioning[block_idx_o].push(index);
  33720. }
  33721. }
  33722. if (computeDepthSort && options && options.facetPositions) {
  33723. var dsf = depthSortedFacets[index];
  33724. dsf.ind = index * 3;
  33725. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  33726. }
  33727. // compute the normals anyway
  33728. normals[v1x] += faceNormalx; // accumulate all the normals per face
  33729. normals[v1y] += faceNormaly;
  33730. normals[v1z] += faceNormalz;
  33731. normals[v2x] += faceNormalx;
  33732. normals[v2y] += faceNormaly;
  33733. normals[v2z] += faceNormalz;
  33734. normals[v3x] += faceNormalx;
  33735. normals[v3y] += faceNormaly;
  33736. normals[v3z] += faceNormalz;
  33737. }
  33738. // last normalization of each normal
  33739. for (index = 0; index < normals.length / 3; index++) {
  33740. faceNormalx = normals[index * 3];
  33741. faceNormaly = normals[index * 3 + 1];
  33742. faceNormalz = normals[index * 3 + 2];
  33743. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  33744. length = (length === 0) ? 1.0 : length;
  33745. faceNormalx /= length;
  33746. faceNormaly /= length;
  33747. faceNormalz /= length;
  33748. normals[index * 3] = faceNormalx;
  33749. normals[index * 3 + 1] = faceNormaly;
  33750. normals[index * 3 + 2] = faceNormalz;
  33751. }
  33752. };
  33753. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  33754. var li = indices.length;
  33755. var ln = normals.length;
  33756. var i;
  33757. var n;
  33758. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33759. switch (sideOrientation) {
  33760. case BABYLON.Mesh.FRONTSIDE:
  33761. // nothing changed
  33762. break;
  33763. case BABYLON.Mesh.BACKSIDE:
  33764. var tmp;
  33765. // indices
  33766. for (i = 0; i < li; i += 3) {
  33767. tmp = indices[i];
  33768. indices[i] = indices[i + 2];
  33769. indices[i + 2] = tmp;
  33770. }
  33771. // normals
  33772. for (n = 0; n < ln; n++) {
  33773. normals[n] = -normals[n];
  33774. }
  33775. break;
  33776. case BABYLON.Mesh.DOUBLESIDE:
  33777. // positions
  33778. var lp = positions.length;
  33779. var l = lp / 3;
  33780. for (var p = 0; p < lp; p++) {
  33781. positions[lp + p] = positions[p];
  33782. }
  33783. // indices
  33784. for (i = 0; i < li; i += 3) {
  33785. indices[i + li] = indices[i + 2] + l;
  33786. indices[i + 1 + li] = indices[i + 1] + l;
  33787. indices[i + 2 + li] = indices[i] + l;
  33788. }
  33789. // normals
  33790. for (n = 0; n < ln; n++) {
  33791. normals[ln + n] = -normals[n];
  33792. }
  33793. // uvs
  33794. var lu = uvs.length;
  33795. var u = 0;
  33796. for (u = 0; u < lu; u++) {
  33797. uvs[u + lu] = uvs[u];
  33798. }
  33799. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  33800. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  33801. u = 0;
  33802. for (i = 0; i < lu / 2; i++) {
  33803. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  33804. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  33805. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  33806. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  33807. u += 2;
  33808. }
  33809. break;
  33810. }
  33811. };
  33812. /**
  33813. * Creates a new VertexData from the imported parameters.
  33814. */
  33815. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  33816. var vertexData = new VertexData();
  33817. // positions
  33818. var positions = parsedVertexData.positions;
  33819. if (positions) {
  33820. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  33821. }
  33822. // normals
  33823. var normals = parsedVertexData.normals;
  33824. if (normals) {
  33825. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  33826. }
  33827. // tangents
  33828. var tangents = parsedVertexData.tangents;
  33829. if (tangents) {
  33830. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  33831. }
  33832. // uvs
  33833. var uvs = parsedVertexData.uvs;
  33834. if (uvs) {
  33835. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  33836. }
  33837. // uv2s
  33838. var uv2s = parsedVertexData.uv2s;
  33839. if (uv2s) {
  33840. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  33841. }
  33842. // uv3s
  33843. var uv3s = parsedVertexData.uv3s;
  33844. if (uv3s) {
  33845. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  33846. }
  33847. // uv4s
  33848. var uv4s = parsedVertexData.uv4s;
  33849. if (uv4s) {
  33850. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  33851. }
  33852. // uv5s
  33853. var uv5s = parsedVertexData.uv5s;
  33854. if (uv5s) {
  33855. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  33856. }
  33857. // uv6s
  33858. var uv6s = parsedVertexData.uv6s;
  33859. if (uv6s) {
  33860. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  33861. }
  33862. // colors
  33863. var colors = parsedVertexData.colors;
  33864. if (colors) {
  33865. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  33866. }
  33867. // matricesIndices
  33868. var matricesIndices = parsedVertexData.matricesIndices;
  33869. if (matricesIndices) {
  33870. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  33871. }
  33872. // matricesWeights
  33873. var matricesWeights = parsedVertexData.matricesWeights;
  33874. if (matricesWeights) {
  33875. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  33876. }
  33877. // indices
  33878. var indices = parsedVertexData.indices;
  33879. if (indices) {
  33880. vertexData.indices = indices;
  33881. }
  33882. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  33883. };
  33884. return VertexData;
  33885. }());
  33886. BABYLON.VertexData = VertexData;
  33887. })(BABYLON || (BABYLON = {}));
  33888. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  33889. var BABYLON;
  33890. (function (BABYLON) {
  33891. /**
  33892. * Class used to store geometry data (vertex buffers + index buffer)
  33893. */
  33894. var Geometry = /** @class */ (function () {
  33895. /**
  33896. * Creates a new geometry
  33897. * @param id defines the unique ID
  33898. * @param scene defines the hosting scene
  33899. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  33900. * @param updatable defines if geometry must be updatable (false by default)
  33901. * @param mesh defines the mesh that will be associated with the geometry
  33902. */
  33903. function Geometry(id, scene, vertexData, updatable, mesh) {
  33904. if (updatable === void 0) { updatable = false; }
  33905. if (mesh === void 0) { mesh = null; }
  33906. /**
  33907. * Gets the delay loading state of the geometry (none by default which means not delayed)
  33908. */
  33909. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  33910. this._totalVertices = 0;
  33911. this._isDisposed = false;
  33912. this._indexBufferIsUpdatable = false;
  33913. this.id = id;
  33914. this._engine = scene.getEngine();
  33915. this._meshes = [];
  33916. this._scene = scene;
  33917. //Init vertex buffer cache
  33918. this._vertexBuffers = {};
  33919. this._indices = [];
  33920. this._updatable = updatable;
  33921. // vertexData
  33922. if (vertexData) {
  33923. this.setAllVerticesData(vertexData, updatable);
  33924. }
  33925. else {
  33926. this._totalVertices = 0;
  33927. this._indices = [];
  33928. }
  33929. if (this._engine.getCaps().vertexArrayObject) {
  33930. this._vertexArrayObjects = {};
  33931. }
  33932. // applyToMesh
  33933. if (mesh) {
  33934. if (mesh.getClassName() === "LinesMesh") {
  33935. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  33936. this.updateExtend();
  33937. }
  33938. this.applyToMesh(mesh);
  33939. mesh.computeWorldMatrix(true);
  33940. }
  33941. }
  33942. Object.defineProperty(Geometry.prototype, "boundingBias", {
  33943. /**
  33944. * 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
  33945. */
  33946. get: function () {
  33947. return this._boundingBias;
  33948. },
  33949. /**
  33950. * 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
  33951. */
  33952. set: function (value) {
  33953. if (this._boundingBias && this._boundingBias.equals(value)) {
  33954. return;
  33955. }
  33956. this._boundingBias = value.clone();
  33957. this.updateBoundingInfo(true, null);
  33958. },
  33959. enumerable: true,
  33960. configurable: true
  33961. });
  33962. /**
  33963. * Static function used to attach a new empty geometry to a mesh
  33964. * @param mesh defines the mesh to attach the geometry to
  33965. * @returns the new {BABYLON.Geometry}
  33966. */
  33967. Geometry.CreateGeometryForMesh = function (mesh) {
  33968. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  33969. geometry.applyToMesh(mesh);
  33970. return geometry;
  33971. };
  33972. Object.defineProperty(Geometry.prototype, "extend", {
  33973. /**
  33974. * Gets the current extend of the geometry
  33975. */
  33976. get: function () {
  33977. return this._extend;
  33978. },
  33979. enumerable: true,
  33980. configurable: true
  33981. });
  33982. /**
  33983. * Gets the hosting scene
  33984. * @returns the hosting {BABYLON.Scene}
  33985. */
  33986. Geometry.prototype.getScene = function () {
  33987. return this._scene;
  33988. };
  33989. /**
  33990. * Gets the hosting engine
  33991. * @returns the hosting {BABYLON.Engine}
  33992. */
  33993. Geometry.prototype.getEngine = function () {
  33994. return this._engine;
  33995. };
  33996. /**
  33997. * Defines if the geometry is ready to use
  33998. * @returns true if the geometry is ready to be used
  33999. */
  34000. Geometry.prototype.isReady = function () {
  34001. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  34002. };
  34003. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  34004. /**
  34005. * Gets a value indicating that the geometry should not be serialized
  34006. */
  34007. get: function () {
  34008. for (var index = 0; index < this._meshes.length; index++) {
  34009. if (!this._meshes[index].doNotSerialize) {
  34010. return false;
  34011. }
  34012. }
  34013. return true;
  34014. },
  34015. enumerable: true,
  34016. configurable: true
  34017. });
  34018. /** @ignore */
  34019. Geometry.prototype._rebuild = function () {
  34020. if (this._vertexArrayObjects) {
  34021. this._vertexArrayObjects = {};
  34022. }
  34023. // Index buffer
  34024. if (this._meshes.length !== 0 && this._indices) {
  34025. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  34026. }
  34027. // Vertex buffers
  34028. for (var key in this._vertexBuffers) {
  34029. var vertexBuffer = this._vertexBuffers[key];
  34030. vertexBuffer._rebuild();
  34031. }
  34032. };
  34033. /**
  34034. * Affects all gemetry data in one call
  34035. * @param vertexData defines the geometry data
  34036. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  34037. */
  34038. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  34039. vertexData.applyToGeometry(this, updatable);
  34040. this.notifyUpdate();
  34041. };
  34042. /**
  34043. * Set specific vertex data
  34044. * @param kind defines the data kind (Position, normal, etc...)
  34045. * @param data defines the vertex data to use
  34046. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  34047. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  34048. */
  34049. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  34050. if (updatable === void 0) { updatable = false; }
  34051. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  34052. this.setVerticesBuffer(buffer);
  34053. };
  34054. /**
  34055. * Removes a specific vertex data
  34056. * @param kind defines the data kind (Position, normal, etc...)
  34057. */
  34058. Geometry.prototype.removeVerticesData = function (kind) {
  34059. if (this._vertexBuffers[kind]) {
  34060. this._vertexBuffers[kind].dispose();
  34061. delete this._vertexBuffers[kind];
  34062. }
  34063. };
  34064. /**
  34065. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  34066. * @param buffer defines the vertex buffer to use
  34067. */
  34068. Geometry.prototype.setVerticesBuffer = function (buffer) {
  34069. var kind = buffer.getKind();
  34070. if (this._vertexBuffers[kind]) {
  34071. this._vertexBuffers[kind].dispose();
  34072. }
  34073. this._vertexBuffers[kind] = buffer;
  34074. if (kind === BABYLON.VertexBuffer.PositionKind) {
  34075. var data = buffer.getData();
  34076. var stride = buffer.getStrideSize();
  34077. this._totalVertices = data.length / stride;
  34078. this.updateExtend(data, stride);
  34079. this._resetPointsArrayCache();
  34080. var meshes = this._meshes;
  34081. var numOfMeshes = meshes.length;
  34082. for (var index = 0; index < numOfMeshes; index++) {
  34083. var mesh = meshes[index];
  34084. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  34085. mesh._createGlobalSubMesh(false);
  34086. mesh.computeWorldMatrix(true);
  34087. }
  34088. }
  34089. this.notifyUpdate(kind);
  34090. if (this._vertexArrayObjects) {
  34091. this._disposeVertexArrayObjects();
  34092. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  34093. }
  34094. };
  34095. /**
  34096. * Update a specific vertex buffer
  34097. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  34098. * It will do nothing if the buffer is not updatable
  34099. * @param kind defines the data kind (Position, normal, etc...)
  34100. * @param data defines the data to use
  34101. * @param offset defines the offset in the target buffer where to store the data
  34102. */
  34103. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  34104. var vertexBuffer = this.getVertexBuffer(kind);
  34105. if (!vertexBuffer) {
  34106. return;
  34107. }
  34108. vertexBuffer.updateDirectly(data, offset);
  34109. this.notifyUpdate(kind);
  34110. };
  34111. /**
  34112. * Update a specific vertex buffer
  34113. * This function will create a new buffer if the current one is not updatable
  34114. * @param kind defines the data kind (Position, normal, etc...)
  34115. * @param data defines the data to use
  34116. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  34117. */
  34118. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  34119. if (updateExtends === void 0) { updateExtends = false; }
  34120. var vertexBuffer = this.getVertexBuffer(kind);
  34121. if (!vertexBuffer) {
  34122. return;
  34123. }
  34124. vertexBuffer.update(data);
  34125. if (kind === BABYLON.VertexBuffer.PositionKind) {
  34126. var stride = vertexBuffer.getStrideSize();
  34127. this._totalVertices = data.length / stride;
  34128. this.updateBoundingInfo(updateExtends, data);
  34129. }
  34130. this.notifyUpdate(kind);
  34131. };
  34132. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  34133. if (updateExtends) {
  34134. this.updateExtend(data);
  34135. }
  34136. var meshes = this._meshes;
  34137. var numOfMeshes = meshes.length;
  34138. this._resetPointsArrayCache();
  34139. for (var index = 0; index < numOfMeshes; index++) {
  34140. var mesh = meshes[index];
  34141. if (updateExtends) {
  34142. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  34143. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  34144. var subMesh = mesh.subMeshes[subIndex];
  34145. subMesh.refreshBoundingInfo();
  34146. }
  34147. }
  34148. }
  34149. };
  34150. /** @ignore */
  34151. Geometry.prototype._bind = function (effect, indexToBind) {
  34152. if (!effect) {
  34153. return;
  34154. }
  34155. if (indexToBind === undefined) {
  34156. indexToBind = this._indexBuffer;
  34157. }
  34158. var vbs = this.getVertexBuffers();
  34159. if (!vbs) {
  34160. return;
  34161. }
  34162. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  34163. this._engine.bindBuffers(vbs, indexToBind, effect);
  34164. return;
  34165. }
  34166. // Using VAO
  34167. if (!this._vertexArrayObjects[effect.key]) {
  34168. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  34169. }
  34170. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  34171. };
  34172. /**
  34173. * Gets total number of vertices
  34174. * @returns the total number of vertices
  34175. */
  34176. Geometry.prototype.getTotalVertices = function () {
  34177. if (!this.isReady()) {
  34178. return 0;
  34179. }
  34180. return this._totalVertices;
  34181. };
  34182. /**
  34183. * Gets a specific vertex data attached to this geometry
  34184. * @param kind defines the data kind (Position, normal, etc...)
  34185. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  34186. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  34187. * @returns a float array containing vertex data
  34188. */
  34189. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  34190. var vertexBuffer = this.getVertexBuffer(kind);
  34191. if (!vertexBuffer) {
  34192. return null;
  34193. }
  34194. var orig = vertexBuffer.getData();
  34195. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  34196. return orig;
  34197. }
  34198. else {
  34199. var len = orig.length;
  34200. var copy = [];
  34201. for (var i = 0; i < len; i++) {
  34202. copy.push(orig[i]);
  34203. }
  34204. return copy;
  34205. }
  34206. };
  34207. /**
  34208. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  34209. * @param kind defines the data kind (Position, normal, etc...)
  34210. * @returns true if the vertex buffer with the specified kind is updatable
  34211. */
  34212. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  34213. var vb = this._vertexBuffers[kind];
  34214. if (!vb) {
  34215. return false;
  34216. }
  34217. return vb.isUpdatable();
  34218. };
  34219. /**
  34220. * Gets a specific vertex buffer
  34221. * @param kind defines the data kind (Position, normal, etc...)
  34222. * @returns a {BABYLON.VertexBuffer}
  34223. */
  34224. Geometry.prototype.getVertexBuffer = function (kind) {
  34225. if (!this.isReady()) {
  34226. return null;
  34227. }
  34228. return this._vertexBuffers[kind];
  34229. };
  34230. /**
  34231. * Returns all vertex buffers
  34232. * @return an object holding all vertex buffers indexed by kind
  34233. */
  34234. Geometry.prototype.getVertexBuffers = function () {
  34235. if (!this.isReady()) {
  34236. return null;
  34237. }
  34238. return this._vertexBuffers;
  34239. };
  34240. /**
  34241. * Gets a boolean indicating if specific vertex buffer is present
  34242. * @param kind defines the data kind (Position, normal, etc...)
  34243. * @returns true if data is present
  34244. */
  34245. Geometry.prototype.isVerticesDataPresent = function (kind) {
  34246. if (!this._vertexBuffers) {
  34247. if (this._delayInfo) {
  34248. return this._delayInfo.indexOf(kind) !== -1;
  34249. }
  34250. return false;
  34251. }
  34252. return this._vertexBuffers[kind] !== undefined;
  34253. };
  34254. /**
  34255. * Gets a list of all attached data kinds (Position, normal, etc...)
  34256. * @returns a list of string containing all kinds
  34257. */
  34258. Geometry.prototype.getVerticesDataKinds = function () {
  34259. var result = [];
  34260. var kind;
  34261. if (!this._vertexBuffers && this._delayInfo) {
  34262. for (kind in this._delayInfo) {
  34263. result.push(kind);
  34264. }
  34265. }
  34266. else {
  34267. for (kind in this._vertexBuffers) {
  34268. result.push(kind);
  34269. }
  34270. }
  34271. return result;
  34272. };
  34273. /**
  34274. * Update index buffer
  34275. * @param indices defines the indices to store in the index buffer
  34276. * @param offset defines the offset in the target buffer where to store the data
  34277. */
  34278. Geometry.prototype.updateIndices = function (indices, offset) {
  34279. if (!this._indexBuffer) {
  34280. return;
  34281. }
  34282. if (!this._indexBufferIsUpdatable) {
  34283. this.setIndices(indices, null, true);
  34284. }
  34285. else {
  34286. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  34287. }
  34288. };
  34289. /**
  34290. * Creates a new index buffer
  34291. * @param indices defines the indices to store in the index buffer
  34292. * @param totalVertices defines the total number of vertices (could be null)
  34293. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  34294. */
  34295. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  34296. if (totalVertices === void 0) { totalVertices = null; }
  34297. if (updatable === void 0) { updatable = false; }
  34298. if (this._indexBuffer) {
  34299. this._engine._releaseBuffer(this._indexBuffer);
  34300. }
  34301. this._disposeVertexArrayObjects();
  34302. this._indices = indices;
  34303. this._indexBufferIsUpdatable = updatable;
  34304. if (this._meshes.length !== 0 && this._indices) {
  34305. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  34306. }
  34307. if (totalVertices != undefined) {
  34308. this._totalVertices = totalVertices;
  34309. }
  34310. var meshes = this._meshes;
  34311. var numOfMeshes = meshes.length;
  34312. for (var index = 0; index < numOfMeshes; index++) {
  34313. meshes[index]._createGlobalSubMesh(true);
  34314. }
  34315. this.notifyUpdate();
  34316. };
  34317. /**
  34318. * Return the total number of indices
  34319. * @returns the total number of indices
  34320. */
  34321. Geometry.prototype.getTotalIndices = function () {
  34322. if (!this.isReady()) {
  34323. return 0;
  34324. }
  34325. return this._indices.length;
  34326. };
  34327. /**
  34328. * Gets the index buffer array
  34329. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  34330. * @returns the index buffer array
  34331. */
  34332. Geometry.prototype.getIndices = function (copyWhenShared) {
  34333. if (!this.isReady()) {
  34334. return null;
  34335. }
  34336. var orig = this._indices;
  34337. if (!copyWhenShared || this._meshes.length === 1) {
  34338. return orig;
  34339. }
  34340. else {
  34341. var len = orig.length;
  34342. var copy = [];
  34343. for (var i = 0; i < len; i++) {
  34344. copy.push(orig[i]);
  34345. }
  34346. return copy;
  34347. }
  34348. };
  34349. /**
  34350. * Gets the index buffer
  34351. * @return the index buffer
  34352. */
  34353. Geometry.prototype.getIndexBuffer = function () {
  34354. if (!this.isReady()) {
  34355. return null;
  34356. }
  34357. return this._indexBuffer;
  34358. };
  34359. /** @ignore */
  34360. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  34361. if (effect === void 0) { effect = null; }
  34362. if (!effect || !this._vertexArrayObjects) {
  34363. return;
  34364. }
  34365. if (this._vertexArrayObjects[effect.key]) {
  34366. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  34367. delete this._vertexArrayObjects[effect.key];
  34368. }
  34369. };
  34370. /**
  34371. * Release the associated resources for a specific mesh
  34372. * @param mesh defines the source mesh
  34373. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  34374. */
  34375. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  34376. var meshes = this._meshes;
  34377. var index = meshes.indexOf(mesh);
  34378. if (index === -1) {
  34379. return;
  34380. }
  34381. meshes.splice(index, 1);
  34382. mesh._geometry = null;
  34383. if (meshes.length === 0 && shouldDispose) {
  34384. this.dispose();
  34385. }
  34386. };
  34387. /**
  34388. * Apply current geometry to a given mesh
  34389. * @param mesh defines the mesh to apply geometry to
  34390. */
  34391. Geometry.prototype.applyToMesh = function (mesh) {
  34392. if (mesh._geometry === this) {
  34393. return;
  34394. }
  34395. var previousGeometry = mesh._geometry;
  34396. if (previousGeometry) {
  34397. previousGeometry.releaseForMesh(mesh);
  34398. }
  34399. var meshes = this._meshes;
  34400. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  34401. mesh._geometry = this;
  34402. this._scene.pushGeometry(this);
  34403. meshes.push(mesh);
  34404. if (this.isReady()) {
  34405. this._applyToMesh(mesh);
  34406. }
  34407. else {
  34408. mesh._boundingInfo = this._boundingInfo;
  34409. }
  34410. };
  34411. Geometry.prototype.updateExtend = function (data, stride) {
  34412. if (data === void 0) { data = null; }
  34413. if (!data) {
  34414. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  34415. }
  34416. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  34417. };
  34418. Geometry.prototype._applyToMesh = function (mesh) {
  34419. var numOfMeshes = this._meshes.length;
  34420. // vertexBuffers
  34421. for (var kind in this._vertexBuffers) {
  34422. if (numOfMeshes === 1) {
  34423. this._vertexBuffers[kind].create();
  34424. }
  34425. var buffer = this._vertexBuffers[kind].getBuffer();
  34426. if (buffer)
  34427. buffer.references = numOfMeshes;
  34428. if (kind === BABYLON.VertexBuffer.PositionKind) {
  34429. if (!this._extend) {
  34430. this.updateExtend(this._vertexBuffers[kind].getData());
  34431. }
  34432. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  34433. mesh._createGlobalSubMesh(false);
  34434. //bounding info was just created again, world matrix should be applied again.
  34435. mesh._updateBoundingInfo();
  34436. }
  34437. }
  34438. // indexBuffer
  34439. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  34440. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  34441. }
  34442. if (this._indexBuffer) {
  34443. this._indexBuffer.references = numOfMeshes;
  34444. }
  34445. };
  34446. Geometry.prototype.notifyUpdate = function (kind) {
  34447. if (this.onGeometryUpdated) {
  34448. this.onGeometryUpdated(this, kind);
  34449. }
  34450. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  34451. var mesh = _a[_i];
  34452. mesh._markSubMeshesAsAttributesDirty();
  34453. }
  34454. };
  34455. /**
  34456. * Load the geometry if it was flagged as delay loaded
  34457. * @param scene defines the hosting scene
  34458. * @param onLoaded defines a callback called when the geometry is loaded
  34459. */
  34460. Geometry.prototype.load = function (scene, onLoaded) {
  34461. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  34462. return;
  34463. }
  34464. if (this.isReady()) {
  34465. if (onLoaded) {
  34466. onLoaded();
  34467. }
  34468. return;
  34469. }
  34470. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  34471. this._queueLoad(scene, onLoaded);
  34472. };
  34473. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  34474. var _this = this;
  34475. if (!this.delayLoadingFile) {
  34476. return;
  34477. }
  34478. scene._addPendingData(this);
  34479. scene._loadFile(this.delayLoadingFile, function (data) {
  34480. if (!_this._delayLoadingFunction) {
  34481. return;
  34482. }
  34483. _this._delayLoadingFunction(JSON.parse(data), _this);
  34484. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  34485. _this._delayInfo = [];
  34486. scene._removePendingData(_this);
  34487. var meshes = _this._meshes;
  34488. var numOfMeshes = meshes.length;
  34489. for (var index = 0; index < numOfMeshes; index++) {
  34490. _this._applyToMesh(meshes[index]);
  34491. }
  34492. if (onLoaded) {
  34493. onLoaded();
  34494. }
  34495. }, undefined, true);
  34496. };
  34497. /**
  34498. * Invert the geometry to move from a right handed system to a left handed one.
  34499. */
  34500. Geometry.prototype.toLeftHanded = function () {
  34501. // Flip faces
  34502. var tIndices = this.getIndices(false);
  34503. if (tIndices != null && tIndices.length > 0) {
  34504. for (var i = 0; i < tIndices.length; i += 3) {
  34505. var tTemp = tIndices[i + 0];
  34506. tIndices[i + 0] = tIndices[i + 2];
  34507. tIndices[i + 2] = tTemp;
  34508. }
  34509. this.setIndices(tIndices);
  34510. }
  34511. // Negate position.z
  34512. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  34513. if (tPositions != null && tPositions.length > 0) {
  34514. for (var i = 0; i < tPositions.length; i += 3) {
  34515. tPositions[i + 2] = -tPositions[i + 2];
  34516. }
  34517. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  34518. }
  34519. // Negate normal.z
  34520. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  34521. if (tNormals != null && tNormals.length > 0) {
  34522. for (var i = 0; i < tNormals.length; i += 3) {
  34523. tNormals[i + 2] = -tNormals[i + 2];
  34524. }
  34525. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  34526. }
  34527. };
  34528. // Cache
  34529. /** @ignore */
  34530. Geometry.prototype._resetPointsArrayCache = function () {
  34531. this._positions = null;
  34532. };
  34533. /** @ignore */
  34534. Geometry.prototype._generatePointsArray = function () {
  34535. if (this._positions)
  34536. return true;
  34537. this._positions = [];
  34538. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34539. if (!data) {
  34540. return false;
  34541. }
  34542. for (var index = 0; index < data.length; index += 3) {
  34543. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  34544. }
  34545. return true;
  34546. };
  34547. /**
  34548. * Gets a value indicating if the geometry is disposed
  34549. * @returns true if the geometry was disposed
  34550. */
  34551. Geometry.prototype.isDisposed = function () {
  34552. return this._isDisposed;
  34553. };
  34554. Geometry.prototype._disposeVertexArrayObjects = function () {
  34555. if (this._vertexArrayObjects) {
  34556. for (var kind in this._vertexArrayObjects) {
  34557. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  34558. }
  34559. this._vertexArrayObjects = {};
  34560. }
  34561. };
  34562. /**
  34563. * Free all associated resources
  34564. */
  34565. Geometry.prototype.dispose = function () {
  34566. var meshes = this._meshes;
  34567. var numOfMeshes = meshes.length;
  34568. var index;
  34569. for (index = 0; index < numOfMeshes; index++) {
  34570. this.releaseForMesh(meshes[index]);
  34571. }
  34572. this._meshes = [];
  34573. this._disposeVertexArrayObjects();
  34574. for (var kind in this._vertexBuffers) {
  34575. this._vertexBuffers[kind].dispose();
  34576. }
  34577. this._vertexBuffers = {};
  34578. this._totalVertices = 0;
  34579. if (this._indexBuffer) {
  34580. this._engine._releaseBuffer(this._indexBuffer);
  34581. }
  34582. this._indexBuffer = null;
  34583. this._indices = [];
  34584. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  34585. this.delayLoadingFile = null;
  34586. this._delayLoadingFunction = null;
  34587. this._delayInfo = [];
  34588. this._boundingInfo = null;
  34589. this._scene.removeGeometry(this);
  34590. this._isDisposed = true;
  34591. };
  34592. /**
  34593. * Clone the current geometry into a new geometry
  34594. * @param id defines the unique ID of the new geometry
  34595. * @returns a new geometry object
  34596. */
  34597. Geometry.prototype.copy = function (id) {
  34598. var vertexData = new BABYLON.VertexData();
  34599. vertexData.indices = [];
  34600. var indices = this.getIndices();
  34601. if (indices) {
  34602. for (var index = 0; index < indices.length; index++) {
  34603. vertexData.indices.push(indices[index]);
  34604. }
  34605. }
  34606. var updatable = false;
  34607. var stopChecking = false;
  34608. var kind;
  34609. for (kind in this._vertexBuffers) {
  34610. // using slice() to make a copy of the array and not just reference it
  34611. var data = this.getVerticesData(kind);
  34612. if (data instanceof Float32Array) {
  34613. vertexData.set(new Float32Array(data), kind);
  34614. }
  34615. else {
  34616. vertexData.set(data.slice(0), kind);
  34617. }
  34618. if (!stopChecking) {
  34619. var vb = this.getVertexBuffer(kind);
  34620. if (vb) {
  34621. updatable = vb.isUpdatable();
  34622. stopChecking = !updatable;
  34623. }
  34624. }
  34625. }
  34626. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  34627. geometry.delayLoadState = this.delayLoadState;
  34628. geometry.delayLoadingFile = this.delayLoadingFile;
  34629. geometry._delayLoadingFunction = this._delayLoadingFunction;
  34630. for (kind in this._delayInfo) {
  34631. geometry._delayInfo = geometry._delayInfo || [];
  34632. geometry._delayInfo.push(kind);
  34633. }
  34634. // Bounding info
  34635. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  34636. return geometry;
  34637. };
  34638. /**
  34639. * Serialize the current geometry info (and not the vertices data) into a JSON object
  34640. * @return a JSON representation of the current geometry data (without the vertices data)
  34641. */
  34642. Geometry.prototype.serialize = function () {
  34643. var serializationObject = {};
  34644. serializationObject.id = this.id;
  34645. serializationObject.updatable = this._updatable;
  34646. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  34647. serializationObject.tags = BABYLON.Tags.GetTags(this);
  34648. }
  34649. return serializationObject;
  34650. };
  34651. Geometry.prototype.toNumberArray = function (origin) {
  34652. if (Array.isArray(origin)) {
  34653. return origin;
  34654. }
  34655. else {
  34656. return Array.prototype.slice.call(origin);
  34657. }
  34658. };
  34659. /**
  34660. * Serialize all vertices data into a JSON oject
  34661. * @returns a JSON representation of the current geometry data
  34662. */
  34663. Geometry.prototype.serializeVerticeData = function () {
  34664. var serializationObject = this.serialize();
  34665. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  34666. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  34667. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  34668. serializationObject.positions._updatable = true;
  34669. }
  34670. }
  34671. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  34672. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  34673. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  34674. serializationObject.normals._updatable = true;
  34675. }
  34676. }
  34677. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  34678. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  34679. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  34680. serializationObject.tangets._updatable = true;
  34681. }
  34682. }
  34683. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  34684. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  34685. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  34686. serializationObject.uvs._updatable = true;
  34687. }
  34688. }
  34689. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  34690. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  34691. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  34692. serializationObject.uv2s._updatable = true;
  34693. }
  34694. }
  34695. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  34696. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  34697. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  34698. serializationObject.uv3s._updatable = true;
  34699. }
  34700. }
  34701. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  34702. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  34703. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  34704. serializationObject.uv4s._updatable = true;
  34705. }
  34706. }
  34707. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  34708. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  34709. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  34710. serializationObject.uv5s._updatable = true;
  34711. }
  34712. }
  34713. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  34714. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  34715. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  34716. serializationObject.uv6s._updatable = true;
  34717. }
  34718. }
  34719. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  34720. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  34721. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  34722. serializationObject.colors._updatable = true;
  34723. }
  34724. }
  34725. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  34726. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  34727. serializationObject.matricesIndices._isExpanded = true;
  34728. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  34729. serializationObject.matricesIndices._updatable = true;
  34730. }
  34731. }
  34732. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  34733. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  34734. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  34735. serializationObject.matricesWeights._updatable = true;
  34736. }
  34737. }
  34738. serializationObject.indices = this.toNumberArray(this.getIndices());
  34739. return serializationObject;
  34740. };
  34741. // Statics
  34742. /**
  34743. * Extracts a clone of a mesh geometry
  34744. * @param mesh defines the source mesh
  34745. * @param id defines the unique ID of the new geometry object
  34746. * @returns the new geometry object
  34747. */
  34748. Geometry.ExtractFromMesh = function (mesh, id) {
  34749. var geometry = mesh._geometry;
  34750. if (!geometry) {
  34751. return null;
  34752. }
  34753. return geometry.copy(id);
  34754. };
  34755. /**
  34756. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  34757. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  34758. * Be aware Math.random() could cause collisions, but:
  34759. * "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"
  34760. * @returns a string containing a new GUID
  34761. */
  34762. Geometry.RandomId = function () {
  34763. return BABYLON.Tools.RandomId();
  34764. };
  34765. /** @ignore */
  34766. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  34767. var scene = mesh.getScene();
  34768. // Geometry
  34769. var geometryId = parsedGeometry.geometryId;
  34770. if (geometryId) {
  34771. var geometry = scene.getGeometryByID(geometryId);
  34772. if (geometry) {
  34773. geometry.applyToMesh(mesh);
  34774. }
  34775. }
  34776. else if (parsedGeometry instanceof ArrayBuffer) {
  34777. var binaryInfo = mesh._binaryInfo;
  34778. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  34779. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  34780. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  34781. }
  34782. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  34783. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  34784. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  34785. }
  34786. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  34787. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  34788. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  34789. }
  34790. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  34791. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  34792. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  34793. }
  34794. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  34795. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  34796. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  34797. }
  34798. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  34799. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  34800. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  34801. }
  34802. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  34803. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  34804. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  34805. }
  34806. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  34807. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  34808. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  34809. }
  34810. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  34811. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  34812. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  34813. }
  34814. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  34815. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  34816. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  34817. }
  34818. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  34819. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  34820. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  34821. }
  34822. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  34823. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  34824. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  34825. }
  34826. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  34827. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  34828. mesh.setIndices(indicesData, null);
  34829. }
  34830. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  34831. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  34832. mesh.subMeshes = [];
  34833. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  34834. var materialIndex = subMeshesData[(i * 5) + 0];
  34835. var verticesStart = subMeshesData[(i * 5) + 1];
  34836. var verticesCount = subMeshesData[(i * 5) + 2];
  34837. var indexStart = subMeshesData[(i * 5) + 3];
  34838. var indexCount = subMeshesData[(i * 5) + 4];
  34839. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  34840. }
  34841. }
  34842. }
  34843. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  34844. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  34845. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  34846. if (parsedGeometry.tangents) {
  34847. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  34848. }
  34849. if (parsedGeometry.uvs) {
  34850. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  34851. }
  34852. if (parsedGeometry.uvs2) {
  34853. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  34854. }
  34855. if (parsedGeometry.uvs3) {
  34856. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  34857. }
  34858. if (parsedGeometry.uvs4) {
  34859. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  34860. }
  34861. if (parsedGeometry.uvs5) {
  34862. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  34863. }
  34864. if (parsedGeometry.uvs6) {
  34865. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  34866. }
  34867. if (parsedGeometry.colors) {
  34868. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  34869. }
  34870. if (parsedGeometry.matricesIndices) {
  34871. if (!parsedGeometry.matricesIndices._isExpanded) {
  34872. var floatIndices = [];
  34873. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  34874. var matricesIndex = parsedGeometry.matricesIndices[i];
  34875. floatIndices.push(matricesIndex & 0x000000FF);
  34876. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  34877. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  34878. floatIndices.push(matricesIndex >> 24);
  34879. }
  34880. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  34881. }
  34882. else {
  34883. delete parsedGeometry.matricesIndices._isExpanded;
  34884. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  34885. }
  34886. }
  34887. if (parsedGeometry.matricesIndicesExtra) {
  34888. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  34889. var floatIndices = [];
  34890. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  34891. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  34892. floatIndices.push(matricesIndex & 0x000000FF);
  34893. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  34894. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  34895. floatIndices.push(matricesIndex >> 24);
  34896. }
  34897. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  34898. }
  34899. else {
  34900. delete parsedGeometry.matricesIndices._isExpanded;
  34901. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  34902. }
  34903. }
  34904. if (parsedGeometry.matricesWeights) {
  34905. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  34906. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  34907. }
  34908. if (parsedGeometry.matricesWeightsExtra) {
  34909. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  34910. }
  34911. mesh.setIndices(parsedGeometry.indices, null);
  34912. }
  34913. // SubMeshes
  34914. if (parsedGeometry.subMeshes) {
  34915. mesh.subMeshes = [];
  34916. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  34917. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  34918. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  34919. }
  34920. }
  34921. // Flat shading
  34922. if (mesh._shouldGenerateFlatShading) {
  34923. mesh.convertToFlatShadedMesh();
  34924. delete mesh._shouldGenerateFlatShading;
  34925. }
  34926. // Update
  34927. mesh.computeWorldMatrix(true);
  34928. // Octree
  34929. var sceneOctree = scene.selectionOctree;
  34930. if (sceneOctree !== undefined && sceneOctree !== null) {
  34931. sceneOctree.addMesh(mesh);
  34932. }
  34933. };
  34934. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  34935. var epsilon = 1e-3;
  34936. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  34937. return;
  34938. }
  34939. var noInfluenceBoneIndex = 0.0;
  34940. if (parsedGeometry.skeletonId > -1) {
  34941. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  34942. if (!skeleton) {
  34943. return;
  34944. }
  34945. noInfluenceBoneIndex = skeleton.bones.length;
  34946. }
  34947. else {
  34948. return;
  34949. }
  34950. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  34951. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  34952. var matricesWeights = parsedGeometry.matricesWeights;
  34953. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  34954. var influencers = parsedGeometry.numBoneInfluencer;
  34955. var size = matricesWeights.length;
  34956. for (var i = 0; i < size; i += 4) {
  34957. var weight = 0.0;
  34958. var firstZeroWeight = -1;
  34959. for (var j = 0; j < 4; j++) {
  34960. var w = matricesWeights[i + j];
  34961. weight += w;
  34962. if (w < epsilon && firstZeroWeight < 0) {
  34963. firstZeroWeight = j;
  34964. }
  34965. }
  34966. if (matricesWeightsExtra) {
  34967. for (var j = 0; j < 4; j++) {
  34968. var w = matricesWeightsExtra[i + j];
  34969. weight += w;
  34970. if (w < epsilon && firstZeroWeight < 0) {
  34971. firstZeroWeight = j + 4;
  34972. }
  34973. }
  34974. }
  34975. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  34976. firstZeroWeight = influencers - 1;
  34977. }
  34978. if (weight > epsilon) {
  34979. var mweight = 1.0 / weight;
  34980. for (var j = 0; j < 4; j++) {
  34981. matricesWeights[i + j] *= mweight;
  34982. }
  34983. if (matricesWeightsExtra) {
  34984. for (var j = 0; j < 4; j++) {
  34985. matricesWeightsExtra[i + j] *= mweight;
  34986. }
  34987. }
  34988. }
  34989. else {
  34990. if (firstZeroWeight >= 4) {
  34991. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  34992. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  34993. }
  34994. else {
  34995. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  34996. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  34997. }
  34998. }
  34999. }
  35000. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  35001. if (parsedGeometry.matricesWeightsExtra) {
  35002. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  35003. }
  35004. };
  35005. /**
  35006. * Create a new geometry from persisted data (Using .babylon file format)
  35007. * @param parsedVertexData defines the persisted data
  35008. * @param scene defines the hosting scene
  35009. * @param rootUrl defines the root url to use to load assets (like delayed data)
  35010. * @returns the new geometry object
  35011. */
  35012. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  35013. if (scene.getGeometryByID(parsedVertexData.id)) {
  35014. return null; // null since geometry could be something else than a box...
  35015. }
  35016. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  35017. if (BABYLON.Tags) {
  35018. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  35019. }
  35020. if (parsedVertexData.delayLoadingFile) {
  35021. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  35022. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  35023. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  35024. geometry._delayInfo = [];
  35025. if (parsedVertexData.hasUVs) {
  35026. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  35027. }
  35028. if (parsedVertexData.hasUVs2) {
  35029. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  35030. }
  35031. if (parsedVertexData.hasUVs3) {
  35032. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  35033. }
  35034. if (parsedVertexData.hasUVs4) {
  35035. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  35036. }
  35037. if (parsedVertexData.hasUVs5) {
  35038. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  35039. }
  35040. if (parsedVertexData.hasUVs6) {
  35041. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  35042. }
  35043. if (parsedVertexData.hasColors) {
  35044. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  35045. }
  35046. if (parsedVertexData.hasMatricesIndices) {
  35047. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  35048. }
  35049. if (parsedVertexData.hasMatricesWeights) {
  35050. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  35051. }
  35052. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  35053. }
  35054. else {
  35055. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  35056. }
  35057. scene.pushGeometry(geometry, true);
  35058. return geometry;
  35059. };
  35060. return Geometry;
  35061. }());
  35062. BABYLON.Geometry = Geometry;
  35063. // Primitives
  35064. /// Abstract class
  35065. /**
  35066. * Abstract class used to provide common services for all typed geometries
  35067. */
  35068. var _PrimitiveGeometry = /** @class */ (function (_super) {
  35069. __extends(_PrimitiveGeometry, _super);
  35070. /**
  35071. * Creates a new typed geometry
  35072. * @param id defines the unique ID of the geometry
  35073. * @param scene defines the hosting scene
  35074. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35075. * @param mesh defines the hosting mesh (can be null)
  35076. */
  35077. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  35078. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  35079. if (mesh === void 0) { mesh = null; }
  35080. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  35081. _this._canBeRegenerated = _canBeRegenerated;
  35082. _this._beingRegenerated = true;
  35083. _this.regenerate();
  35084. _this._beingRegenerated = false;
  35085. return _this;
  35086. }
  35087. /**
  35088. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  35089. * @returns true if the geometry can be regenerated
  35090. */
  35091. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  35092. return this._canBeRegenerated;
  35093. };
  35094. /**
  35095. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  35096. */
  35097. _PrimitiveGeometry.prototype.regenerate = function () {
  35098. if (!this._canBeRegenerated) {
  35099. return;
  35100. }
  35101. this._beingRegenerated = true;
  35102. this.setAllVerticesData(this._regenerateVertexData(), false);
  35103. this._beingRegenerated = false;
  35104. };
  35105. /**
  35106. * Clone the geometry
  35107. * @param id defines the unique ID of the new geometry
  35108. * @returns the new geometry
  35109. */
  35110. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  35111. return _super.prototype.copy.call(this, id);
  35112. };
  35113. // overrides
  35114. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  35115. if (!this._beingRegenerated) {
  35116. return;
  35117. }
  35118. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  35119. };
  35120. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  35121. if (!this._beingRegenerated) {
  35122. return;
  35123. }
  35124. _super.prototype.setVerticesData.call(this, kind, data, false);
  35125. };
  35126. // to override
  35127. /** @ignore */
  35128. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  35129. throw new Error("Abstract method");
  35130. };
  35131. _PrimitiveGeometry.prototype.copy = function (id) {
  35132. throw new Error("Must be overriden in sub-classes.");
  35133. };
  35134. _PrimitiveGeometry.prototype.serialize = function () {
  35135. var serializationObject = _super.prototype.serialize.call(this);
  35136. serializationObject.canBeRegenerated = this.canBeRegenerated();
  35137. return serializationObject;
  35138. };
  35139. return _PrimitiveGeometry;
  35140. }(Geometry));
  35141. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  35142. /**
  35143. * Creates a ribbon geometry
  35144. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  35145. */
  35146. var RibbonGeometry = /** @class */ (function (_super) {
  35147. __extends(RibbonGeometry, _super);
  35148. /**
  35149. * Creates a ribbon geometry
  35150. * @param id defines the unique ID of the geometry
  35151. * @param scene defines the hosting scene
  35152. * @param pathArray defines the array of paths to use
  35153. * @param closeArray defines if the last path and the first path must be joined
  35154. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  35155. * @param offset defines the offset between points
  35156. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35157. * @param mesh defines the hosting mesh (can be null)
  35158. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35159. */
  35160. function RibbonGeometry(id, scene,
  35161. /**
  35162. * Defines the array of paths to use
  35163. */
  35164. pathArray,
  35165. /**
  35166. * Defines if the last and first points of each path in your pathArray must be joined
  35167. */
  35168. closeArray,
  35169. /**
  35170. * Defines if the last and first points of each path in your pathArray must be joined
  35171. */
  35172. closePath,
  35173. /**
  35174. * Defines the offset between points
  35175. */
  35176. offset, canBeRegenerated, mesh,
  35177. /**
  35178. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35179. */
  35180. side) {
  35181. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35182. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35183. _this.pathArray = pathArray;
  35184. _this.closeArray = closeArray;
  35185. _this.closePath = closePath;
  35186. _this.offset = offset;
  35187. _this.side = side;
  35188. return _this;
  35189. }
  35190. /** @ignore */
  35191. RibbonGeometry.prototype._regenerateVertexData = function () {
  35192. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  35193. };
  35194. RibbonGeometry.prototype.copy = function (id) {
  35195. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  35196. };
  35197. return RibbonGeometry;
  35198. }(_PrimitiveGeometry));
  35199. BABYLON.RibbonGeometry = RibbonGeometry;
  35200. /**
  35201. * Creates a box geometry
  35202. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  35203. */
  35204. var BoxGeometry = /** @class */ (function (_super) {
  35205. __extends(BoxGeometry, _super);
  35206. /**
  35207. * Creates a box geometry
  35208. * @param id defines the unique ID of the geometry
  35209. * @param scene defines the hosting scene
  35210. * @param size defines the zise of the box (width, height and depth are the same)
  35211. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35212. * @param mesh defines the hosting mesh (can be null)
  35213. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35214. */
  35215. function BoxGeometry(id, scene,
  35216. /**
  35217. * Defines the zise of the box (width, height and depth are the same)
  35218. */
  35219. size, canBeRegenerated, mesh,
  35220. /**
  35221. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35222. */
  35223. side) {
  35224. if (mesh === void 0) { mesh = null; }
  35225. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35226. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35227. _this.size = size;
  35228. _this.side = side;
  35229. return _this;
  35230. }
  35231. BoxGeometry.prototype._regenerateVertexData = function () {
  35232. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  35233. };
  35234. BoxGeometry.prototype.copy = function (id) {
  35235. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  35236. };
  35237. BoxGeometry.prototype.serialize = function () {
  35238. var serializationObject = _super.prototype.serialize.call(this);
  35239. serializationObject.size = this.size;
  35240. return serializationObject;
  35241. };
  35242. BoxGeometry.Parse = function (parsedBox, scene) {
  35243. if (scene.getGeometryByID(parsedBox.id)) {
  35244. return null; // null since geometry could be something else than a box...
  35245. }
  35246. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  35247. if (BABYLON.Tags) {
  35248. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  35249. }
  35250. scene.pushGeometry(box, true);
  35251. return box;
  35252. };
  35253. return BoxGeometry;
  35254. }(_PrimitiveGeometry));
  35255. BABYLON.BoxGeometry = BoxGeometry;
  35256. /**
  35257. * Creates a sphere geometry
  35258. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  35259. */
  35260. var SphereGeometry = /** @class */ (function (_super) {
  35261. __extends(SphereGeometry, _super);
  35262. /**
  35263. * Create a new sphere geometry
  35264. * @param id defines the unique ID of the geometry
  35265. * @param scene defines the hosting scene
  35266. * @param segments defines the number of segments to use to create the sphere
  35267. * @param diameter defines the diameter of the sphere
  35268. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35269. * @param mesh defines the hosting mesh (can be null)
  35270. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35271. */
  35272. function SphereGeometry(id, scene,
  35273. /**
  35274. * Defines the number of segments to use to create the sphere
  35275. */
  35276. segments,
  35277. /**
  35278. * Defines the diameter of the sphere
  35279. */
  35280. diameter, canBeRegenerated, mesh,
  35281. /**
  35282. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35283. */
  35284. side) {
  35285. if (mesh === void 0) { mesh = null; }
  35286. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35287. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35288. _this.segments = segments;
  35289. _this.diameter = diameter;
  35290. _this.side = side;
  35291. return _this;
  35292. }
  35293. SphereGeometry.prototype._regenerateVertexData = function () {
  35294. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  35295. };
  35296. SphereGeometry.prototype.copy = function (id) {
  35297. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  35298. };
  35299. SphereGeometry.prototype.serialize = function () {
  35300. var serializationObject = _super.prototype.serialize.call(this);
  35301. serializationObject.segments = this.segments;
  35302. serializationObject.diameter = this.diameter;
  35303. return serializationObject;
  35304. };
  35305. SphereGeometry.Parse = function (parsedSphere, scene) {
  35306. if (scene.getGeometryByID(parsedSphere.id)) {
  35307. return null; // null since geometry could be something else than a sphere...
  35308. }
  35309. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  35310. if (BABYLON.Tags) {
  35311. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  35312. }
  35313. scene.pushGeometry(sphere, true);
  35314. return sphere;
  35315. };
  35316. return SphereGeometry;
  35317. }(_PrimitiveGeometry));
  35318. BABYLON.SphereGeometry = SphereGeometry;
  35319. /**
  35320. * Creates a disc geometry
  35321. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  35322. */
  35323. var DiscGeometry = /** @class */ (function (_super) {
  35324. __extends(DiscGeometry, _super);
  35325. /**
  35326. * Creates a new disc geometry
  35327. * @param id defines the unique ID of the geometry
  35328. * @param scene defines the hosting scene
  35329. * @param radius defines the radius of the disc
  35330. * @param tessellation defines the tesselation factor to apply to the disc
  35331. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35332. * @param mesh defines the hosting mesh (can be null)
  35333. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35334. */
  35335. function DiscGeometry(id, scene,
  35336. /**
  35337. * Defines the radius of the disc
  35338. */
  35339. radius,
  35340. /**
  35341. * Defines the tesselation factor to apply to the disc
  35342. */
  35343. tessellation, canBeRegenerated, mesh,
  35344. /**
  35345. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35346. */
  35347. side) {
  35348. if (mesh === void 0) { mesh = null; }
  35349. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35350. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35351. _this.radius = radius;
  35352. _this.tessellation = tessellation;
  35353. _this.side = side;
  35354. return _this;
  35355. }
  35356. DiscGeometry.prototype._regenerateVertexData = function () {
  35357. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  35358. };
  35359. DiscGeometry.prototype.copy = function (id) {
  35360. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  35361. };
  35362. return DiscGeometry;
  35363. }(_PrimitiveGeometry));
  35364. BABYLON.DiscGeometry = DiscGeometry;
  35365. /**
  35366. * Creates a new cylinder geometry
  35367. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  35368. */
  35369. var CylinderGeometry = /** @class */ (function (_super) {
  35370. __extends(CylinderGeometry, _super);
  35371. /**
  35372. * Creates a new cylinder geometry
  35373. * @param id defines the unique ID of the geometry
  35374. * @param scene defines the hosting scene
  35375. * @param height defines the height of the cylinder
  35376. * @param diameterTop defines the diameter of the cylinder's top cap
  35377. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  35378. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  35379. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  35380. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35381. * @param mesh defines the hosting mesh (can be null)
  35382. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35383. */
  35384. function CylinderGeometry(id, scene,
  35385. /**
  35386. * Defines the height of the cylinder
  35387. */
  35388. height,
  35389. /**
  35390. * Defines the diameter of the cylinder's top cap
  35391. */
  35392. diameterTop,
  35393. /**
  35394. * Defines the diameter of the cylinder's bottom cap
  35395. */
  35396. diameterBottom,
  35397. /**
  35398. * Defines the tessellation factor to apply to the cylinder
  35399. */
  35400. tessellation,
  35401. /**
  35402. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  35403. */
  35404. subdivisions, canBeRegenerated, mesh,
  35405. /**
  35406. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35407. */
  35408. side) {
  35409. if (subdivisions === void 0) { subdivisions = 1; }
  35410. if (mesh === void 0) { mesh = null; }
  35411. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35412. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35413. _this.height = height;
  35414. _this.diameterTop = diameterTop;
  35415. _this.diameterBottom = diameterBottom;
  35416. _this.tessellation = tessellation;
  35417. _this.subdivisions = subdivisions;
  35418. _this.side = side;
  35419. return _this;
  35420. }
  35421. CylinderGeometry.prototype._regenerateVertexData = function () {
  35422. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  35423. };
  35424. CylinderGeometry.prototype.copy = function (id) {
  35425. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  35426. };
  35427. CylinderGeometry.prototype.serialize = function () {
  35428. var serializationObject = _super.prototype.serialize.call(this);
  35429. serializationObject.height = this.height;
  35430. serializationObject.diameterTop = this.diameterTop;
  35431. serializationObject.diameterBottom = this.diameterBottom;
  35432. serializationObject.tessellation = this.tessellation;
  35433. return serializationObject;
  35434. };
  35435. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  35436. if (scene.getGeometryByID(parsedCylinder.id)) {
  35437. return null; // null since geometry could be something else than a cylinder...
  35438. }
  35439. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  35440. if (BABYLON.Tags) {
  35441. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  35442. }
  35443. scene.pushGeometry(cylinder, true);
  35444. return cylinder;
  35445. };
  35446. return CylinderGeometry;
  35447. }(_PrimitiveGeometry));
  35448. BABYLON.CylinderGeometry = CylinderGeometry;
  35449. /**
  35450. * Creates a new torus geometry
  35451. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  35452. */
  35453. var TorusGeometry = /** @class */ (function (_super) {
  35454. __extends(TorusGeometry, _super);
  35455. /**
  35456. * Creates a new torus geometry
  35457. * @param id defines the unique ID of the geometry
  35458. * @param scene defines the hosting scene
  35459. * @param diameter defines the diameter of the torus
  35460. * @param thickness defines the thickness of the torus (ie. internal diameter)
  35461. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  35462. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35463. * @param mesh defines the hosting mesh (can be null)
  35464. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35465. */
  35466. function TorusGeometry(id, scene,
  35467. /**
  35468. * Defines the diameter of the torus
  35469. */
  35470. diameter,
  35471. /**
  35472. * Defines the thickness of the torus (ie. internal diameter)
  35473. */
  35474. thickness,
  35475. /**
  35476. * Defines the tesselation factor to apply to the torus
  35477. */
  35478. tessellation, canBeRegenerated, mesh,
  35479. /**
  35480. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35481. */
  35482. side) {
  35483. if (mesh === void 0) { mesh = null; }
  35484. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35485. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35486. _this.diameter = diameter;
  35487. _this.thickness = thickness;
  35488. _this.tessellation = tessellation;
  35489. _this.side = side;
  35490. return _this;
  35491. }
  35492. TorusGeometry.prototype._regenerateVertexData = function () {
  35493. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  35494. };
  35495. TorusGeometry.prototype.copy = function (id) {
  35496. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  35497. };
  35498. TorusGeometry.prototype.serialize = function () {
  35499. var serializationObject = _super.prototype.serialize.call(this);
  35500. serializationObject.diameter = this.diameter;
  35501. serializationObject.thickness = this.thickness;
  35502. serializationObject.tessellation = this.tessellation;
  35503. return serializationObject;
  35504. };
  35505. TorusGeometry.Parse = function (parsedTorus, scene) {
  35506. if (scene.getGeometryByID(parsedTorus.id)) {
  35507. return null; // null since geometry could be something else than a torus...
  35508. }
  35509. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  35510. if (BABYLON.Tags) {
  35511. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  35512. }
  35513. scene.pushGeometry(torus, true);
  35514. return torus;
  35515. };
  35516. return TorusGeometry;
  35517. }(_PrimitiveGeometry));
  35518. BABYLON.TorusGeometry = TorusGeometry;
  35519. /**
  35520. * Creates a new ground geometry
  35521. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  35522. */
  35523. var GroundGeometry = /** @class */ (function (_super) {
  35524. __extends(GroundGeometry, _super);
  35525. /**
  35526. * Creates a new ground geometry
  35527. * @param id defines the unique ID of the geometry
  35528. * @param scene defines the hosting scene
  35529. * @param width defines the width of the ground
  35530. * @param height defines the height of the ground
  35531. * @param subdivisions defines the subdivisions to apply to the ground
  35532. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35533. * @param mesh defines the hosting mesh (can be null)
  35534. */
  35535. function GroundGeometry(id, scene,
  35536. /**
  35537. * Defines the width of the ground
  35538. */
  35539. width,
  35540. /**
  35541. * Defines the height of the ground
  35542. */
  35543. height,
  35544. /**
  35545. * Defines the subdivisions to apply to the ground
  35546. */
  35547. subdivisions, canBeRegenerated, mesh) {
  35548. if (mesh === void 0) { mesh = null; }
  35549. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35550. _this.width = width;
  35551. _this.height = height;
  35552. _this.subdivisions = subdivisions;
  35553. return _this;
  35554. }
  35555. GroundGeometry.prototype._regenerateVertexData = function () {
  35556. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  35557. };
  35558. GroundGeometry.prototype.copy = function (id) {
  35559. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  35560. };
  35561. GroundGeometry.prototype.serialize = function () {
  35562. var serializationObject = _super.prototype.serialize.call(this);
  35563. serializationObject.width = this.width;
  35564. serializationObject.height = this.height;
  35565. serializationObject.subdivisions = this.subdivisions;
  35566. return serializationObject;
  35567. };
  35568. GroundGeometry.Parse = function (parsedGround, scene) {
  35569. if (scene.getGeometryByID(parsedGround.id)) {
  35570. return null; // null since geometry could be something else than a ground...
  35571. }
  35572. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  35573. if (BABYLON.Tags) {
  35574. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  35575. }
  35576. scene.pushGeometry(ground, true);
  35577. return ground;
  35578. };
  35579. return GroundGeometry;
  35580. }(_PrimitiveGeometry));
  35581. BABYLON.GroundGeometry = GroundGeometry;
  35582. /**
  35583. * Creates a tiled ground geometry
  35584. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  35585. */
  35586. var TiledGroundGeometry = /** @class */ (function (_super) {
  35587. __extends(TiledGroundGeometry, _super);
  35588. /**
  35589. * Creates a tiled ground geometry
  35590. * @param id defines the unique ID of the geometry
  35591. * @param scene defines the hosting scene
  35592. * @param xmin defines the minimum value on X axis
  35593. * @param zmin defines the minimum value on Z axis
  35594. * @param xmax defines the maximum value on X axis
  35595. * @param zmax defines the maximum value on Z axis
  35596. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  35597. * @param precision defines the precision to use when computing the tiles
  35598. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35599. * @param mesh defines the hosting mesh (can be null)
  35600. */
  35601. function TiledGroundGeometry(id, scene,
  35602. /**
  35603. * Defines the minimum value on X axis
  35604. */
  35605. xmin,
  35606. /**
  35607. * Defines the minimum value on Z axis
  35608. */
  35609. zmin,
  35610. /**
  35611. * Defines the maximum value on X axis
  35612. */
  35613. xmax,
  35614. /**
  35615. * Defines the maximum value on Z axis
  35616. */
  35617. zmax,
  35618. /**
  35619. * Defines the subdivisions to apply to the ground
  35620. */
  35621. subdivisions,
  35622. /**
  35623. * Defines the precision to use when computing the tiles
  35624. */
  35625. precision, canBeRegenerated, mesh) {
  35626. if (mesh === void 0) { mesh = null; }
  35627. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35628. _this.xmin = xmin;
  35629. _this.zmin = zmin;
  35630. _this.xmax = xmax;
  35631. _this.zmax = zmax;
  35632. _this.subdivisions = subdivisions;
  35633. _this.precision = precision;
  35634. return _this;
  35635. }
  35636. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  35637. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  35638. };
  35639. TiledGroundGeometry.prototype.copy = function (id) {
  35640. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  35641. };
  35642. return TiledGroundGeometry;
  35643. }(_PrimitiveGeometry));
  35644. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  35645. /**
  35646. * Creates a plane geometry
  35647. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  35648. */
  35649. var PlaneGeometry = /** @class */ (function (_super) {
  35650. __extends(PlaneGeometry, _super);
  35651. /**
  35652. * Creates a plane geometry
  35653. * @param id defines the unique ID of the geometry
  35654. * @param scene defines the hosting scene
  35655. * @param size defines the size of the plane (width === height)
  35656. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35657. * @param mesh defines the hosting mesh (can be null)
  35658. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35659. */
  35660. function PlaneGeometry(id, scene,
  35661. /**
  35662. * Defines the size of the plane (width === height)
  35663. */
  35664. size, canBeRegenerated, mesh,
  35665. /**
  35666. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35667. */
  35668. side) {
  35669. if (mesh === void 0) { mesh = null; }
  35670. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35671. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35672. _this.size = size;
  35673. _this.side = side;
  35674. return _this;
  35675. }
  35676. PlaneGeometry.prototype._regenerateVertexData = function () {
  35677. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  35678. };
  35679. PlaneGeometry.prototype.copy = function (id) {
  35680. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  35681. };
  35682. PlaneGeometry.prototype.serialize = function () {
  35683. var serializationObject = _super.prototype.serialize.call(this);
  35684. serializationObject.size = this.size;
  35685. return serializationObject;
  35686. };
  35687. PlaneGeometry.Parse = function (parsedPlane, scene) {
  35688. if (scene.getGeometryByID(parsedPlane.id)) {
  35689. return null; // null since geometry could be something else than a ground...
  35690. }
  35691. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  35692. if (BABYLON.Tags) {
  35693. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  35694. }
  35695. scene.pushGeometry(plane, true);
  35696. return plane;
  35697. };
  35698. return PlaneGeometry;
  35699. }(_PrimitiveGeometry));
  35700. BABYLON.PlaneGeometry = PlaneGeometry;
  35701. /**
  35702. * Creates a torus knot geometry
  35703. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  35704. */
  35705. var TorusKnotGeometry = /** @class */ (function (_super) {
  35706. __extends(TorusKnotGeometry, _super);
  35707. /**
  35708. * Creates a torus knot geometry
  35709. * @param id defines the unique ID of the geometry
  35710. * @param scene defines the hosting scene
  35711. * @param radius defines the radius of the torus knot
  35712. * @param tube defines the thickness of the torus knot tube
  35713. * @param radialSegments defines the number of radial segments
  35714. * @param tubularSegments defines the number of tubular segments
  35715. * @param p defines the first number of windings
  35716. * @param q defines the second number of windings
  35717. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35718. * @param mesh defines the hosting mesh (can be null)
  35719. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35720. */
  35721. function TorusKnotGeometry(id, scene,
  35722. /**
  35723. * Defines the radius of the torus knot
  35724. */
  35725. radius,
  35726. /**
  35727. * Defines the thickness of the torus knot tube
  35728. */
  35729. tube,
  35730. /**
  35731. * Defines the number of radial segments
  35732. */
  35733. radialSegments,
  35734. /**
  35735. * Defines the number of tubular segments
  35736. */
  35737. tubularSegments,
  35738. /**
  35739. * Defines the first number of windings
  35740. */
  35741. p,
  35742. /**
  35743. * Defines the second number of windings
  35744. */
  35745. q, canBeRegenerated, mesh,
  35746. /**
  35747. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35748. */
  35749. side) {
  35750. if (mesh === void 0) { mesh = null; }
  35751. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35752. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35753. _this.radius = radius;
  35754. _this.tube = tube;
  35755. _this.radialSegments = radialSegments;
  35756. _this.tubularSegments = tubularSegments;
  35757. _this.p = p;
  35758. _this.q = q;
  35759. _this.side = side;
  35760. return _this;
  35761. }
  35762. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  35763. 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 });
  35764. };
  35765. TorusKnotGeometry.prototype.copy = function (id) {
  35766. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  35767. };
  35768. TorusKnotGeometry.prototype.serialize = function () {
  35769. var serializationObject = _super.prototype.serialize.call(this);
  35770. serializationObject.radius = this.radius;
  35771. serializationObject.tube = this.tube;
  35772. serializationObject.radialSegments = this.radialSegments;
  35773. serializationObject.tubularSegments = this.tubularSegments;
  35774. serializationObject.p = this.p;
  35775. serializationObject.q = this.q;
  35776. return serializationObject;
  35777. };
  35778. ;
  35779. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  35780. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  35781. return null; // null since geometry could be something else than a ground...
  35782. }
  35783. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  35784. if (BABYLON.Tags) {
  35785. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  35786. }
  35787. scene.pushGeometry(torusKnot, true);
  35788. return torusKnot;
  35789. };
  35790. return TorusKnotGeometry;
  35791. }(_PrimitiveGeometry));
  35792. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  35793. //}
  35794. })(BABYLON || (BABYLON = {}));
  35795. //# sourceMappingURL=babylon.geometry.js.map
  35796. var BABYLON;
  35797. (function (BABYLON) {
  35798. /**
  35799. * PostProcessManager is used to manage one or more post processes or post process pipelines
  35800. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  35801. */
  35802. var PostProcessManager = /** @class */ (function () {
  35803. /**
  35804. * Creates a new instance of @see PostProcess
  35805. * @param scene The scene that the post process is associated with.
  35806. */
  35807. function PostProcessManager(scene) {
  35808. this._vertexBuffers = {};
  35809. this._scene = scene;
  35810. }
  35811. PostProcessManager.prototype._prepareBuffers = function () {
  35812. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  35813. return;
  35814. }
  35815. // VBO
  35816. var vertices = [];
  35817. vertices.push(1, 1);
  35818. vertices.push(-1, 1);
  35819. vertices.push(-1, -1);
  35820. vertices.push(1, -1);
  35821. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  35822. this._buildIndexBuffer();
  35823. };
  35824. PostProcessManager.prototype._buildIndexBuffer = function () {
  35825. // Indices
  35826. var indices = [];
  35827. indices.push(0);
  35828. indices.push(1);
  35829. indices.push(2);
  35830. indices.push(0);
  35831. indices.push(2);
  35832. indices.push(3);
  35833. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  35834. };
  35835. /**
  35836. * Rebuilds the vertex buffers of the manager.
  35837. */
  35838. PostProcessManager.prototype._rebuild = function () {
  35839. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  35840. if (!vb) {
  35841. return;
  35842. }
  35843. vb._rebuild();
  35844. this._buildIndexBuffer();
  35845. };
  35846. // Methods
  35847. /**
  35848. * Prepares a frame to be run through a post process.
  35849. * @param sourceTexture The input texture to the post procesess. (default: null)
  35850. * @param postProcesses An array of post processes to be run. (default: null)
  35851. * @returns True if the post processes were able to be run.
  35852. */
  35853. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  35854. if (sourceTexture === void 0) { sourceTexture = null; }
  35855. if (postProcesses === void 0) { postProcesses = null; }
  35856. var camera = this._scene.activeCamera;
  35857. if (!camera) {
  35858. return false;
  35859. }
  35860. var postProcesses = postProcesses || camera._postProcesses;
  35861. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  35862. return false;
  35863. }
  35864. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  35865. return true;
  35866. };
  35867. /**
  35868. * Manually render a set of post processes to a texture.
  35869. * @param postProcesses An array of post processes to be run.
  35870. * @param targetTexture The target texture to render to.
  35871. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  35872. */
  35873. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  35874. if (targetTexture === void 0) { targetTexture = null; }
  35875. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  35876. var engine = this._scene.getEngine();
  35877. for (var index = 0; index < postProcesses.length; index++) {
  35878. if (index < postProcesses.length - 1) {
  35879. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  35880. }
  35881. else {
  35882. if (targetTexture) {
  35883. engine.bindFramebuffer(targetTexture, 0, undefined, undefined, forceFullscreenViewport);
  35884. }
  35885. else {
  35886. engine.restoreDefaultFramebuffer();
  35887. }
  35888. }
  35889. var pp = postProcesses[index];
  35890. var effect = pp.apply();
  35891. if (effect) {
  35892. pp.onBeforeRenderObservable.notifyObservers(effect);
  35893. // VBOs
  35894. this._prepareBuffers();
  35895. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  35896. // Draw order
  35897. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  35898. pp.onAfterRenderObservable.notifyObservers(effect);
  35899. }
  35900. }
  35901. // Restore depth buffer
  35902. engine.setDepthBuffer(true);
  35903. engine.setDepthWrite(true);
  35904. };
  35905. /**
  35906. * Finalize the result of the output of the postprocesses.
  35907. * @param doNotPresent If true the result will not be displayed to the screen.
  35908. * @param targetTexture The target texture to render to.
  35909. * @param faceIndex The index of the face to bind the target texture to.
  35910. * @param postProcesses The array of post processes to render.
  35911. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  35912. */
  35913. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  35914. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  35915. var camera = this._scene.activeCamera;
  35916. if (!camera) {
  35917. return;
  35918. }
  35919. postProcesses = postProcesses || camera._postProcesses;
  35920. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  35921. return;
  35922. }
  35923. var engine = this._scene.getEngine();
  35924. for (var index = 0, len = postProcesses.length; index < len; index++) {
  35925. if (index < len - 1) {
  35926. postProcesses[index + 1].activate(camera, targetTexture);
  35927. }
  35928. else {
  35929. if (targetTexture) {
  35930. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  35931. }
  35932. else {
  35933. engine.restoreDefaultFramebuffer();
  35934. }
  35935. }
  35936. if (doNotPresent) {
  35937. break;
  35938. }
  35939. var pp = postProcesses[index];
  35940. var effect = pp.apply();
  35941. if (effect) {
  35942. pp.onBeforeRenderObservable.notifyObservers(effect);
  35943. // VBOs
  35944. this._prepareBuffers();
  35945. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  35946. // Draw order
  35947. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  35948. pp.onAfterRenderObservable.notifyObservers(effect);
  35949. }
  35950. }
  35951. // Restore states
  35952. engine.setDepthBuffer(true);
  35953. engine.setDepthWrite(true);
  35954. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  35955. };
  35956. /**
  35957. * Disposes of the post process manager.
  35958. */
  35959. PostProcessManager.prototype.dispose = function () {
  35960. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  35961. if (buffer) {
  35962. buffer.dispose();
  35963. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  35964. }
  35965. if (this._indexBuffer) {
  35966. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  35967. this._indexBuffer = null;
  35968. }
  35969. };
  35970. return PostProcessManager;
  35971. }());
  35972. BABYLON.PostProcessManager = PostProcessManager;
  35973. })(BABYLON || (BABYLON = {}));
  35974. //# sourceMappingURL=babylon.postProcessManager.js.map
  35975. var BABYLON;
  35976. (function (BABYLON) {
  35977. /**
  35978. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  35979. */
  35980. var PerformanceMonitor = /** @class */ (function () {
  35981. /**
  35982. * constructor
  35983. * @param frameSampleSize The number of samples required to saturate the sliding window
  35984. */
  35985. function PerformanceMonitor(frameSampleSize) {
  35986. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  35987. this._enabled = true;
  35988. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  35989. }
  35990. /**
  35991. * Samples current frame
  35992. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  35993. */
  35994. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  35995. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  35996. if (!this._enabled)
  35997. return;
  35998. if (this._lastFrameTimeMs != null) {
  35999. var dt = timeMs - this._lastFrameTimeMs;
  36000. this._rollingFrameTime.add(dt);
  36001. }
  36002. this._lastFrameTimeMs = timeMs;
  36003. };
  36004. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  36005. /**
  36006. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  36007. * @return Average frame time in milliseconds
  36008. */
  36009. get: function () {
  36010. return this._rollingFrameTime.average;
  36011. },
  36012. enumerable: true,
  36013. configurable: true
  36014. });
  36015. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  36016. /**
  36017. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  36018. * @return Frame time variance in milliseconds squared
  36019. */
  36020. get: function () {
  36021. return this._rollingFrameTime.variance;
  36022. },
  36023. enumerable: true,
  36024. configurable: true
  36025. });
  36026. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  36027. /**
  36028. * Returns the frame time of the most recent frame
  36029. * @return Frame time in milliseconds
  36030. */
  36031. get: function () {
  36032. return this._rollingFrameTime.history(0);
  36033. },
  36034. enumerable: true,
  36035. configurable: true
  36036. });
  36037. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  36038. /**
  36039. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  36040. * @return Framerate in frames per second
  36041. */
  36042. get: function () {
  36043. return 1000.0 / this._rollingFrameTime.average;
  36044. },
  36045. enumerable: true,
  36046. configurable: true
  36047. });
  36048. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  36049. /**
  36050. * Returns the average framerate in frames per second using the most recent frame time
  36051. * @return Framerate in frames per second
  36052. */
  36053. get: function () {
  36054. var history = this._rollingFrameTime.history(0);
  36055. if (history === 0) {
  36056. return 0;
  36057. }
  36058. return 1000.0 / history;
  36059. },
  36060. enumerable: true,
  36061. configurable: true
  36062. });
  36063. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  36064. /**
  36065. * Returns true if enough samples have been taken to completely fill the sliding window
  36066. * @return true if saturated
  36067. */
  36068. get: function () {
  36069. return this._rollingFrameTime.isSaturated();
  36070. },
  36071. enumerable: true,
  36072. configurable: true
  36073. });
  36074. /**
  36075. * Enables contributions to the sliding window sample set
  36076. */
  36077. PerformanceMonitor.prototype.enable = function () {
  36078. this._enabled = true;
  36079. };
  36080. /**
  36081. * Disables contributions to the sliding window sample set
  36082. * Samples will not be interpolated over the disabled period
  36083. */
  36084. PerformanceMonitor.prototype.disable = function () {
  36085. this._enabled = false;
  36086. //clear last sample to avoid interpolating over the disabled period when next enabled
  36087. this._lastFrameTimeMs = null;
  36088. };
  36089. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  36090. /**
  36091. * Returns true if sampling is enabled
  36092. * @return true if enabled
  36093. */
  36094. get: function () {
  36095. return this._enabled;
  36096. },
  36097. enumerable: true,
  36098. configurable: true
  36099. });
  36100. /**
  36101. * Resets performance monitor
  36102. */
  36103. PerformanceMonitor.prototype.reset = function () {
  36104. //clear last sample to avoid interpolating over the disabled period when next enabled
  36105. this._lastFrameTimeMs = null;
  36106. //wipe record
  36107. this._rollingFrameTime.reset();
  36108. };
  36109. return PerformanceMonitor;
  36110. }());
  36111. BABYLON.PerformanceMonitor = PerformanceMonitor;
  36112. /**
  36113. * RollingAverage
  36114. *
  36115. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  36116. */
  36117. var RollingAverage = /** @class */ (function () {
  36118. /**
  36119. * constructor
  36120. * @param length The number of samples required to saturate the sliding window
  36121. */
  36122. function RollingAverage(length) {
  36123. this._samples = new Array(length);
  36124. this.reset();
  36125. }
  36126. /**
  36127. * Adds a sample to the sample set
  36128. * @param v The sample value
  36129. */
  36130. RollingAverage.prototype.add = function (v) {
  36131. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  36132. var delta;
  36133. //we need to check if we've already wrapped round
  36134. if (this.isSaturated()) {
  36135. //remove bottom of stack from mean
  36136. var bottomValue = this._samples[this._pos];
  36137. delta = bottomValue - this.average;
  36138. this.average -= delta / (this._sampleCount - 1);
  36139. this._m2 -= delta * (bottomValue - this.average);
  36140. }
  36141. else {
  36142. this._sampleCount++;
  36143. }
  36144. //add new value to mean
  36145. delta = v - this.average;
  36146. this.average += delta / (this._sampleCount);
  36147. this._m2 += delta * (v - this.average);
  36148. //set the new variance
  36149. this.variance = this._m2 / (this._sampleCount - 1);
  36150. this._samples[this._pos] = v;
  36151. this._pos++;
  36152. this._pos %= this._samples.length; //positive wrap around
  36153. };
  36154. /**
  36155. * Returns previously added values or null if outside of history or outside the sliding window domain
  36156. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  36157. * @return Value previously recorded with add() or null if outside of range
  36158. */
  36159. RollingAverage.prototype.history = function (i) {
  36160. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  36161. return 0;
  36162. }
  36163. var i0 = this._wrapPosition(this._pos - 1.0);
  36164. return this._samples[this._wrapPosition(i0 - i)];
  36165. };
  36166. /**
  36167. * Returns true if enough samples have been taken to completely fill the sliding window
  36168. * @return true if sample-set saturated
  36169. */
  36170. RollingAverage.prototype.isSaturated = function () {
  36171. return this._sampleCount >= this._samples.length;
  36172. };
  36173. /**
  36174. * Resets the rolling average (equivalent to 0 samples taken so far)
  36175. */
  36176. RollingAverage.prototype.reset = function () {
  36177. this.average = 0;
  36178. this.variance = 0;
  36179. this._sampleCount = 0;
  36180. this._pos = 0;
  36181. this._m2 = 0;
  36182. };
  36183. /**
  36184. * Wraps a value around the sample range boundaries
  36185. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  36186. * @return Wrapped position in sample range
  36187. */
  36188. RollingAverage.prototype._wrapPosition = function (i) {
  36189. var max = this._samples.length;
  36190. return ((i % max) + max) % max;
  36191. };
  36192. return RollingAverage;
  36193. }());
  36194. BABYLON.RollingAverage = RollingAverage;
  36195. })(BABYLON || (BABYLON = {}));
  36196. //# sourceMappingURL=babylon.performanceMonitor.js.map
  36197. var BABYLON;
  36198. (function (BABYLON) {
  36199. /**
  36200. * This groups together the common properties used for image processing either in direct forward pass
  36201. * or through post processing effect depending on the use of the image processing pipeline in your scene
  36202. * or not.
  36203. */
  36204. var ImageProcessingConfiguration = /** @class */ (function () {
  36205. function ImageProcessingConfiguration() {
  36206. /**
  36207. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  36208. */
  36209. this.colorCurves = new BABYLON.ColorCurves();
  36210. this._colorCurvesEnabled = false;
  36211. this._colorGradingEnabled = false;
  36212. this._colorGradingWithGreenDepth = true;
  36213. this._colorGradingBGR = true;
  36214. this._exposure = 1.0;
  36215. this._toneMappingEnabled = false;
  36216. this._contrast = 1.0;
  36217. /**
  36218. * Vignette stretch size.
  36219. */
  36220. this.vignetteStretch = 0;
  36221. /**
  36222. * Vignette centre X Offset.
  36223. */
  36224. this.vignetteCentreX = 0;
  36225. /**
  36226. * Vignette centre Y Offset.
  36227. */
  36228. this.vignetteCentreY = 0;
  36229. /**
  36230. * Vignette weight or intensity of the vignette effect.
  36231. */
  36232. this.vignetteWeight = 1.5;
  36233. /**
  36234. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  36235. * if vignetteEnabled is set to true.
  36236. */
  36237. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  36238. /**
  36239. * Camera field of view used by the Vignette effect.
  36240. */
  36241. this.vignetteCameraFov = 0.5;
  36242. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  36243. this._vignetteEnabled = false;
  36244. this._applyByPostProcess = false;
  36245. this._isEnabled = true;
  36246. /**
  36247. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  36248. * @type {BABYLON.Observable}
  36249. */
  36250. this.onUpdateParameters = new BABYLON.Observable();
  36251. }
  36252. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  36253. /**
  36254. * Gets wether the color curves effect is enabled.
  36255. */
  36256. get: function () {
  36257. return this._colorCurvesEnabled;
  36258. },
  36259. /**
  36260. * Sets wether the color curves effect is enabled.
  36261. */
  36262. set: function (value) {
  36263. if (this._colorCurvesEnabled === value) {
  36264. return;
  36265. }
  36266. this._colorCurvesEnabled = value;
  36267. this._updateParameters();
  36268. },
  36269. enumerable: true,
  36270. configurable: true
  36271. });
  36272. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  36273. /**
  36274. * Gets wether the color grading effect is enabled.
  36275. */
  36276. get: function () {
  36277. return this._colorGradingEnabled;
  36278. },
  36279. /**
  36280. * Sets wether the color grading effect is enabled.
  36281. */
  36282. set: function (value) {
  36283. if (this._colorGradingEnabled === value) {
  36284. return;
  36285. }
  36286. this._colorGradingEnabled = value;
  36287. this._updateParameters();
  36288. },
  36289. enumerable: true,
  36290. configurable: true
  36291. });
  36292. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  36293. /**
  36294. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  36295. */
  36296. get: function () {
  36297. return this._colorGradingWithGreenDepth;
  36298. },
  36299. /**
  36300. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  36301. */
  36302. set: function (value) {
  36303. if (this._colorGradingWithGreenDepth === value) {
  36304. return;
  36305. }
  36306. this._colorGradingWithGreenDepth = value;
  36307. this._updateParameters();
  36308. },
  36309. enumerable: true,
  36310. configurable: true
  36311. });
  36312. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  36313. /**
  36314. * Gets wether the color grading texture contains BGR values.
  36315. */
  36316. get: function () {
  36317. return this._colorGradingBGR;
  36318. },
  36319. /**
  36320. * Sets wether the color grading texture contains BGR values.
  36321. */
  36322. set: function (value) {
  36323. if (this._colorGradingBGR === value) {
  36324. return;
  36325. }
  36326. this._colorGradingBGR = value;
  36327. this._updateParameters();
  36328. },
  36329. enumerable: true,
  36330. configurable: true
  36331. });
  36332. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  36333. /**
  36334. * Gets the Exposure used in the effect.
  36335. */
  36336. get: function () {
  36337. return this._exposure;
  36338. },
  36339. /**
  36340. * Sets the Exposure used in the effect.
  36341. */
  36342. set: function (value) {
  36343. if (this._exposure === value) {
  36344. return;
  36345. }
  36346. this._exposure = value;
  36347. this._updateParameters();
  36348. },
  36349. enumerable: true,
  36350. configurable: true
  36351. });
  36352. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  36353. /**
  36354. * Gets wether the tone mapping effect is enabled.
  36355. */
  36356. get: function () {
  36357. return this._toneMappingEnabled;
  36358. },
  36359. /**
  36360. * Sets wether the tone mapping effect is enabled.
  36361. */
  36362. set: function (value) {
  36363. if (this._toneMappingEnabled === value) {
  36364. return;
  36365. }
  36366. this._toneMappingEnabled = value;
  36367. this._updateParameters();
  36368. },
  36369. enumerable: true,
  36370. configurable: true
  36371. });
  36372. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  36373. /**
  36374. * Gets the contrast used in the effect.
  36375. */
  36376. get: function () {
  36377. return this._contrast;
  36378. },
  36379. /**
  36380. * Sets the contrast used in the effect.
  36381. */
  36382. set: function (value) {
  36383. if (this._contrast === value) {
  36384. return;
  36385. }
  36386. this._contrast = value;
  36387. this._updateParameters();
  36388. },
  36389. enumerable: true,
  36390. configurable: true
  36391. });
  36392. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  36393. /**
  36394. * Gets the vignette blend mode allowing different kind of effect.
  36395. */
  36396. get: function () {
  36397. return this._vignetteBlendMode;
  36398. },
  36399. /**
  36400. * Sets the vignette blend mode allowing different kind of effect.
  36401. */
  36402. set: function (value) {
  36403. if (this._vignetteBlendMode === value) {
  36404. return;
  36405. }
  36406. this._vignetteBlendMode = value;
  36407. this._updateParameters();
  36408. },
  36409. enumerable: true,
  36410. configurable: true
  36411. });
  36412. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  36413. /**
  36414. * Gets wether the vignette effect is enabled.
  36415. */
  36416. get: function () {
  36417. return this._vignetteEnabled;
  36418. },
  36419. /**
  36420. * Sets wether the vignette effect is enabled.
  36421. */
  36422. set: function (value) {
  36423. if (this._vignetteEnabled === value) {
  36424. return;
  36425. }
  36426. this._vignetteEnabled = value;
  36427. this._updateParameters();
  36428. },
  36429. enumerable: true,
  36430. configurable: true
  36431. });
  36432. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  36433. /**
  36434. * Gets wether the image processing is applied through a post process or not.
  36435. */
  36436. get: function () {
  36437. return this._applyByPostProcess;
  36438. },
  36439. /**
  36440. * Sets wether the image processing is applied through a post process or not.
  36441. */
  36442. set: function (value) {
  36443. if (this._applyByPostProcess === value) {
  36444. return;
  36445. }
  36446. this._applyByPostProcess = value;
  36447. this._updateParameters();
  36448. },
  36449. enumerable: true,
  36450. configurable: true
  36451. });
  36452. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  36453. /**
  36454. * Gets wether the image processing is enabled or not.
  36455. */
  36456. get: function () {
  36457. return this._isEnabled;
  36458. },
  36459. /**
  36460. * Sets wether the image processing is enabled or not.
  36461. */
  36462. set: function (value) {
  36463. if (this._isEnabled === value) {
  36464. return;
  36465. }
  36466. this._isEnabled = value;
  36467. this._updateParameters();
  36468. },
  36469. enumerable: true,
  36470. configurable: true
  36471. });
  36472. /**
  36473. * Method called each time the image processing information changes requires to recompile the effect.
  36474. */
  36475. ImageProcessingConfiguration.prototype._updateParameters = function () {
  36476. this.onUpdateParameters.notifyObservers(this);
  36477. };
  36478. ImageProcessingConfiguration.prototype.getClassName = function () {
  36479. return "ImageProcessingConfiguration";
  36480. };
  36481. /**
  36482. * Prepare the list of uniforms associated with the Image Processing effects.
  36483. * @param uniformsList The list of uniforms used in the effect
  36484. * @param defines the list of defines currently in use
  36485. */
  36486. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  36487. if (defines.EXPOSURE) {
  36488. uniforms.push("exposureLinear");
  36489. }
  36490. if (defines.CONTRAST) {
  36491. uniforms.push("contrast");
  36492. }
  36493. if (defines.COLORGRADING) {
  36494. uniforms.push("colorTransformSettings");
  36495. }
  36496. if (defines.VIGNETTE) {
  36497. uniforms.push("vInverseScreenSize");
  36498. uniforms.push("vignetteSettings1");
  36499. uniforms.push("vignetteSettings2");
  36500. }
  36501. if (defines.COLORCURVES) {
  36502. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  36503. }
  36504. };
  36505. /**
  36506. * Prepare the list of samplers associated with the Image Processing effects.
  36507. * @param uniformsList The list of uniforms used in the effect
  36508. * @param defines the list of defines currently in use
  36509. */
  36510. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  36511. if (defines.COLORGRADING) {
  36512. samplersList.push("txColorTransform");
  36513. }
  36514. };
  36515. /**
  36516. * Prepare the list of defines associated to the shader.
  36517. * @param defines the list of defines to complete
  36518. */
  36519. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  36520. if (forPostProcess === void 0) { forPostProcess = false; }
  36521. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  36522. defines.VIGNETTE = false;
  36523. defines.TONEMAPPING = false;
  36524. defines.CONTRAST = false;
  36525. defines.EXPOSURE = false;
  36526. defines.COLORCURVES = false;
  36527. defines.COLORGRADING = false;
  36528. defines.COLORGRADING3D = false;
  36529. defines.IMAGEPROCESSING = false;
  36530. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  36531. return;
  36532. }
  36533. defines.VIGNETTE = this.vignetteEnabled;
  36534. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  36535. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  36536. defines.TONEMAPPING = this.toneMappingEnabled;
  36537. defines.CONTRAST = (this.contrast !== 1.0);
  36538. defines.EXPOSURE = (this.exposure !== 1.0);
  36539. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  36540. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  36541. if (defines.COLORGRADING) {
  36542. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  36543. }
  36544. else {
  36545. defines.COLORGRADING3D = false;
  36546. }
  36547. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  36548. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  36549. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  36550. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  36551. };
  36552. /**
  36553. * Returns true if all the image processing information are ready.
  36554. */
  36555. ImageProcessingConfiguration.prototype.isReady = function () {
  36556. // Color Grading texure can not be none blocking.
  36557. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  36558. };
  36559. /**
  36560. * Binds the image processing to the shader.
  36561. * @param effect The effect to bind to
  36562. */
  36563. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  36564. if (aspectRatio === void 0) { aspectRatio = 1; }
  36565. // Color Curves
  36566. if (this._colorCurvesEnabled && this.colorCurves) {
  36567. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  36568. }
  36569. // Vignette
  36570. if (this._vignetteEnabled) {
  36571. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  36572. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  36573. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  36574. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  36575. var vignetteScaleX = vignetteScaleY * aspectRatio;
  36576. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  36577. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  36578. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  36579. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  36580. var vignettePower = -2.0 * this.vignetteWeight;
  36581. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  36582. }
  36583. // Exposure
  36584. effect.setFloat("exposureLinear", this.exposure);
  36585. // Contrast
  36586. effect.setFloat("contrast", this.contrast);
  36587. // Color transform settings
  36588. if (this.colorGradingTexture) {
  36589. effect.setTexture("txColorTransform", this.colorGradingTexture);
  36590. var textureSize = this.colorGradingTexture.getSize().height;
  36591. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  36592. 0.5 / textureSize, // textureOffset
  36593. textureSize, // textureSize
  36594. this.colorGradingTexture.level // weight
  36595. );
  36596. }
  36597. };
  36598. /**
  36599. * Clones the current image processing instance.
  36600. * @return The cloned image processing
  36601. */
  36602. ImageProcessingConfiguration.prototype.clone = function () {
  36603. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  36604. };
  36605. /**
  36606. * Serializes the current image processing instance to a json representation.
  36607. * @return a JSON representation
  36608. */
  36609. ImageProcessingConfiguration.prototype.serialize = function () {
  36610. return BABYLON.SerializationHelper.Serialize(this);
  36611. };
  36612. /**
  36613. * Parses the image processing from a json representation.
  36614. * @param source the JSON source to parse
  36615. * @return The parsed image processing
  36616. */
  36617. ImageProcessingConfiguration.Parse = function (source) {
  36618. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  36619. };
  36620. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  36621. /**
  36622. * Used to apply the vignette as a mix with the pixel color.
  36623. */
  36624. get: function () {
  36625. return this._VIGNETTEMODE_MULTIPLY;
  36626. },
  36627. enumerable: true,
  36628. configurable: true
  36629. });
  36630. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  36631. /**
  36632. * Used to apply the vignette as a replacement of the pixel color.
  36633. */
  36634. get: function () {
  36635. return this._VIGNETTEMODE_OPAQUE;
  36636. },
  36637. enumerable: true,
  36638. configurable: true
  36639. });
  36640. // Static constants associated to the image processing.
  36641. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  36642. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  36643. __decorate([
  36644. BABYLON.serializeAsColorCurves()
  36645. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  36646. __decorate([
  36647. BABYLON.serialize()
  36648. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  36649. __decorate([
  36650. BABYLON.serializeAsTexture()
  36651. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  36652. __decorate([
  36653. BABYLON.serialize()
  36654. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  36655. __decorate([
  36656. BABYLON.serialize()
  36657. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  36658. __decorate([
  36659. BABYLON.serialize()
  36660. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  36661. __decorate([
  36662. BABYLON.serialize()
  36663. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  36664. __decorate([
  36665. BABYLON.serialize()
  36666. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  36667. __decorate([
  36668. BABYLON.serialize()
  36669. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  36670. __decorate([
  36671. BABYLON.serialize()
  36672. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  36673. __decorate([
  36674. BABYLON.serialize()
  36675. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  36676. __decorate([
  36677. BABYLON.serialize()
  36678. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  36679. __decorate([
  36680. BABYLON.serialize()
  36681. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  36682. __decorate([
  36683. BABYLON.serializeAsColor4()
  36684. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  36685. __decorate([
  36686. BABYLON.serialize()
  36687. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  36688. __decorate([
  36689. BABYLON.serialize()
  36690. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  36691. __decorate([
  36692. BABYLON.serialize()
  36693. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  36694. __decorate([
  36695. BABYLON.serialize()
  36696. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  36697. __decorate([
  36698. BABYLON.serialize()
  36699. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  36700. return ImageProcessingConfiguration;
  36701. }());
  36702. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  36703. })(BABYLON || (BABYLON = {}));
  36704. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  36705. var BABYLON;
  36706. (function (BABYLON) {
  36707. /**
  36708. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  36709. * It can help converting any input color in a desired output one. This can then be used to create effects
  36710. * from sepia, black and white to sixties or futuristic rendering...
  36711. *
  36712. * The only supported format is currently 3dl.
  36713. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  36714. */
  36715. var ColorGradingTexture = /** @class */ (function (_super) {
  36716. __extends(ColorGradingTexture, _super);
  36717. /**
  36718. * Instantiates a ColorGradingTexture from the following parameters.
  36719. *
  36720. * @param url The location of the color gradind data (currently only supporting 3dl)
  36721. * @param scene The scene the texture will be used in
  36722. */
  36723. function ColorGradingTexture(url, scene) {
  36724. var _this = _super.call(this, scene) || this;
  36725. if (!url) {
  36726. return _this;
  36727. }
  36728. _this._engine = scene.getEngine();
  36729. _this._textureMatrix = BABYLON.Matrix.Identity();
  36730. _this.name = url;
  36731. _this.url = url;
  36732. _this.hasAlpha = false;
  36733. _this.isCube = false;
  36734. _this.is3D = _this._engine.webGLVersion > 1;
  36735. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  36736. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  36737. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  36738. _this.anisotropicFilteringLevel = 1;
  36739. _this._texture = _this._getFromCache(url, true);
  36740. if (!_this._texture) {
  36741. if (!scene.useDelayedTextureLoading) {
  36742. _this.loadTexture();
  36743. }
  36744. else {
  36745. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  36746. }
  36747. }
  36748. return _this;
  36749. }
  36750. /**
  36751. * Returns the texture matrix used in most of the material.
  36752. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  36753. */
  36754. ColorGradingTexture.prototype.getTextureMatrix = function () {
  36755. return this._textureMatrix;
  36756. };
  36757. /**
  36758. * Occurs when the file being loaded is a .3dl LUT file.
  36759. */
  36760. ColorGradingTexture.prototype.load3dlTexture = function () {
  36761. var engine = this._engine;
  36762. var texture;
  36763. if (engine.webGLVersion === 1) {
  36764. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  36765. }
  36766. else {
  36767. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  36768. }
  36769. this._texture = texture;
  36770. var callback = function (text) {
  36771. if (typeof text !== "string") {
  36772. return;
  36773. }
  36774. var data = null;
  36775. var tempData = null;
  36776. var line;
  36777. var lines = text.split('\n');
  36778. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  36779. var maxColor = 0;
  36780. for (var i = 0; i < lines.length; i++) {
  36781. line = lines[i];
  36782. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  36783. continue;
  36784. if (line.indexOf('#') === 0)
  36785. continue;
  36786. var words = line.split(" ");
  36787. if (size === 0) {
  36788. // Number of space + one
  36789. size = words.length;
  36790. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  36791. tempData = new Float32Array(size * size * size * 4);
  36792. continue;
  36793. }
  36794. if (size != 0) {
  36795. var r = Math.max(parseInt(words[0]), 0);
  36796. var g = Math.max(parseInt(words[1]), 0);
  36797. var b = Math.max(parseInt(words[2]), 0);
  36798. maxColor = Math.max(r, maxColor);
  36799. maxColor = Math.max(g, maxColor);
  36800. maxColor = Math.max(b, maxColor);
  36801. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  36802. if (tempData) {
  36803. tempData[pixelStorageIndex + 0] = r;
  36804. tempData[pixelStorageIndex + 1] = g;
  36805. tempData[pixelStorageIndex + 2] = b;
  36806. }
  36807. pixelIndexSlice++;
  36808. if (pixelIndexSlice % size == 0) {
  36809. pixelIndexH++;
  36810. pixelIndexSlice = 0;
  36811. if (pixelIndexH % size == 0) {
  36812. pixelIndexW++;
  36813. pixelIndexH = 0;
  36814. }
  36815. }
  36816. }
  36817. }
  36818. if (tempData && data) {
  36819. for (var i = 0; i < tempData.length; i++) {
  36820. if (i > 0 && (i + 1) % 4 === 0) {
  36821. data[i] = 255;
  36822. }
  36823. else {
  36824. var value = tempData[i];
  36825. data[i] = (value / maxColor * 255);
  36826. }
  36827. }
  36828. }
  36829. if (texture.is3D) {
  36830. texture.updateSize(size, size, size);
  36831. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  36832. }
  36833. else {
  36834. texture.updateSize(size * size, size);
  36835. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  36836. }
  36837. };
  36838. var scene = this.getScene();
  36839. if (scene) {
  36840. scene._loadFile(this.url, callback);
  36841. }
  36842. else {
  36843. this._engine._loadFile(this.url, callback);
  36844. }
  36845. return this._texture;
  36846. };
  36847. /**
  36848. * Starts the loading process of the texture.
  36849. */
  36850. ColorGradingTexture.prototype.loadTexture = function () {
  36851. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  36852. this.load3dlTexture();
  36853. }
  36854. };
  36855. /**
  36856. * Clones the color gradind texture.
  36857. */
  36858. ColorGradingTexture.prototype.clone = function () {
  36859. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  36860. // Base texture
  36861. newTexture.level = this.level;
  36862. return newTexture;
  36863. };
  36864. /**
  36865. * Called during delayed load for textures.
  36866. */
  36867. ColorGradingTexture.prototype.delayLoad = function () {
  36868. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  36869. return;
  36870. }
  36871. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  36872. this._texture = this._getFromCache(this.url, true);
  36873. if (!this._texture) {
  36874. this.loadTexture();
  36875. }
  36876. };
  36877. /**
  36878. * Parses a color grading texture serialized by Babylon.
  36879. * @param parsedTexture The texture information being parsedTexture
  36880. * @param scene The scene to load the texture in
  36881. * @param rootUrl The root url of the data assets to load
  36882. * @return A color gradind texture
  36883. */
  36884. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  36885. var texture = null;
  36886. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  36887. texture = new ColorGradingTexture(parsedTexture.name, scene);
  36888. texture.name = parsedTexture.name;
  36889. texture.level = parsedTexture.level;
  36890. }
  36891. return texture;
  36892. };
  36893. /**
  36894. * Serializes the LUT texture to json format.
  36895. */
  36896. ColorGradingTexture.prototype.serialize = function () {
  36897. if (!this.name) {
  36898. return null;
  36899. }
  36900. var serializationObject = {};
  36901. serializationObject.name = this.name;
  36902. serializationObject.level = this.level;
  36903. serializationObject.customType = "BABYLON.ColorGradingTexture";
  36904. return serializationObject;
  36905. };
  36906. /**
  36907. * Empty line regex stored for GC.
  36908. */
  36909. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  36910. return ColorGradingTexture;
  36911. }(BABYLON.BaseTexture));
  36912. BABYLON.ColorGradingTexture = ColorGradingTexture;
  36913. })(BABYLON || (BABYLON = {}));
  36914. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  36915. var BABYLON;
  36916. (function (BABYLON) {
  36917. /**
  36918. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  36919. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  36920. * 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;
  36921. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  36922. */
  36923. var ColorCurves = /** @class */ (function () {
  36924. function ColorCurves() {
  36925. this._dirty = true;
  36926. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  36927. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  36928. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  36929. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  36930. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  36931. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  36932. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  36933. this._globalHue = 30;
  36934. this._globalDensity = 0;
  36935. this._globalSaturation = 0;
  36936. this._globalExposure = 0;
  36937. this._highlightsHue = 30;
  36938. this._highlightsDensity = 0;
  36939. this._highlightsSaturation = 0;
  36940. this._highlightsExposure = 0;
  36941. this._midtonesHue = 30;
  36942. this._midtonesDensity = 0;
  36943. this._midtonesSaturation = 0;
  36944. this._midtonesExposure = 0;
  36945. this._shadowsHue = 30;
  36946. this._shadowsDensity = 0;
  36947. this._shadowsSaturation = 0;
  36948. this._shadowsExposure = 0;
  36949. }
  36950. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  36951. /**
  36952. * Gets the global Hue value.
  36953. * 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).
  36954. */
  36955. get: function () {
  36956. return this._globalHue;
  36957. },
  36958. /**
  36959. * Sets the global Hue value.
  36960. * 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).
  36961. */
  36962. set: function (value) {
  36963. this._globalHue = value;
  36964. this._dirty = true;
  36965. },
  36966. enumerable: true,
  36967. configurable: true
  36968. });
  36969. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  36970. /**
  36971. * Gets the global Density value.
  36972. * 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.
  36973. * Values less than zero provide a filter of opposite hue.
  36974. */
  36975. get: function () {
  36976. return this._globalDensity;
  36977. },
  36978. /**
  36979. * Sets the global Density value.
  36980. * 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.
  36981. * Values less than zero provide a filter of opposite hue.
  36982. */
  36983. set: function (value) {
  36984. this._globalDensity = value;
  36985. this._dirty = true;
  36986. },
  36987. enumerable: true,
  36988. configurable: true
  36989. });
  36990. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  36991. /**
  36992. * Gets the global Saturation value.
  36993. * 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.
  36994. */
  36995. get: function () {
  36996. return this._globalSaturation;
  36997. },
  36998. /**
  36999. * Sets the global Saturation value.
  37000. * 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.
  37001. */
  37002. set: function (value) {
  37003. this._globalSaturation = value;
  37004. this._dirty = true;
  37005. },
  37006. enumerable: true,
  37007. configurable: true
  37008. });
  37009. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  37010. /**
  37011. * Gets the highlights Hue value.
  37012. * 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).
  37013. */
  37014. get: function () {
  37015. return this._highlightsHue;
  37016. },
  37017. /**
  37018. * Sets the highlights Hue value.
  37019. * 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).
  37020. */
  37021. set: function (value) {
  37022. this._highlightsHue = value;
  37023. this._dirty = true;
  37024. },
  37025. enumerable: true,
  37026. configurable: true
  37027. });
  37028. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  37029. /**
  37030. * Gets the highlights Density value.
  37031. * 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.
  37032. * Values less than zero provide a filter of opposite hue.
  37033. */
  37034. get: function () {
  37035. return this._highlightsDensity;
  37036. },
  37037. /**
  37038. * Sets the highlights Density value.
  37039. * 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.
  37040. * Values less than zero provide a filter of opposite hue.
  37041. */
  37042. set: function (value) {
  37043. this._highlightsDensity = value;
  37044. this._dirty = true;
  37045. },
  37046. enumerable: true,
  37047. configurable: true
  37048. });
  37049. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  37050. /**
  37051. * Gets the highlights Saturation value.
  37052. * 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.
  37053. */
  37054. get: function () {
  37055. return this._highlightsSaturation;
  37056. },
  37057. /**
  37058. * Sets the highlights Saturation value.
  37059. * 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.
  37060. */
  37061. set: function (value) {
  37062. this._highlightsSaturation = value;
  37063. this._dirty = true;
  37064. },
  37065. enumerable: true,
  37066. configurable: true
  37067. });
  37068. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  37069. /**
  37070. * Gets the highlights Exposure value.
  37071. * 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.
  37072. */
  37073. get: function () {
  37074. return this._highlightsExposure;
  37075. },
  37076. /**
  37077. * Sets the highlights Exposure value.
  37078. * 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.
  37079. */
  37080. set: function (value) {
  37081. this._highlightsExposure = value;
  37082. this._dirty = true;
  37083. },
  37084. enumerable: true,
  37085. configurable: true
  37086. });
  37087. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  37088. /**
  37089. * Gets the midtones Hue value.
  37090. * 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).
  37091. */
  37092. get: function () {
  37093. return this._midtonesHue;
  37094. },
  37095. /**
  37096. * Sets the midtones Hue value.
  37097. * 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).
  37098. */
  37099. set: function (value) {
  37100. this._midtonesHue = value;
  37101. this._dirty = true;
  37102. },
  37103. enumerable: true,
  37104. configurable: true
  37105. });
  37106. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  37107. /**
  37108. * Gets the midtones Density value.
  37109. * 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.
  37110. * Values less than zero provide a filter of opposite hue.
  37111. */
  37112. get: function () {
  37113. return this._midtonesDensity;
  37114. },
  37115. /**
  37116. * Sets the midtones Density value.
  37117. * 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.
  37118. * Values less than zero provide a filter of opposite hue.
  37119. */
  37120. set: function (value) {
  37121. this._midtonesDensity = value;
  37122. this._dirty = true;
  37123. },
  37124. enumerable: true,
  37125. configurable: true
  37126. });
  37127. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  37128. /**
  37129. * Gets the midtones Saturation value.
  37130. * 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.
  37131. */
  37132. get: function () {
  37133. return this._midtonesSaturation;
  37134. },
  37135. /**
  37136. * Sets the midtones Saturation value.
  37137. * 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.
  37138. */
  37139. set: function (value) {
  37140. this._midtonesSaturation = value;
  37141. this._dirty = true;
  37142. },
  37143. enumerable: true,
  37144. configurable: true
  37145. });
  37146. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  37147. /**
  37148. * Gets the midtones Exposure value.
  37149. * 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.
  37150. */
  37151. get: function () {
  37152. return this._midtonesExposure;
  37153. },
  37154. /**
  37155. * Sets the midtones Exposure value.
  37156. * 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.
  37157. */
  37158. set: function (value) {
  37159. this._midtonesExposure = value;
  37160. this._dirty = true;
  37161. },
  37162. enumerable: true,
  37163. configurable: true
  37164. });
  37165. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  37166. /**
  37167. * Gets the shadows Hue value.
  37168. * 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).
  37169. */
  37170. get: function () {
  37171. return this._shadowsHue;
  37172. },
  37173. /**
  37174. * Sets the shadows Hue value.
  37175. * 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).
  37176. */
  37177. set: function (value) {
  37178. this._shadowsHue = value;
  37179. this._dirty = true;
  37180. },
  37181. enumerable: true,
  37182. configurable: true
  37183. });
  37184. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  37185. /**
  37186. * Gets the shadows Density value.
  37187. * 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.
  37188. * Values less than zero provide a filter of opposite hue.
  37189. */
  37190. get: function () {
  37191. return this._shadowsDensity;
  37192. },
  37193. /**
  37194. * Sets the shadows Density value.
  37195. * 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.
  37196. * Values less than zero provide a filter of opposite hue.
  37197. */
  37198. set: function (value) {
  37199. this._shadowsDensity = value;
  37200. this._dirty = true;
  37201. },
  37202. enumerable: true,
  37203. configurable: true
  37204. });
  37205. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  37206. /**
  37207. * Gets the shadows Saturation value.
  37208. * 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.
  37209. */
  37210. get: function () {
  37211. return this._shadowsSaturation;
  37212. },
  37213. /**
  37214. * Sets the shadows Saturation value.
  37215. * 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.
  37216. */
  37217. set: function (value) {
  37218. this._shadowsSaturation = value;
  37219. this._dirty = true;
  37220. },
  37221. enumerable: true,
  37222. configurable: true
  37223. });
  37224. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  37225. /**
  37226. * Gets the shadows Exposure value.
  37227. * 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.
  37228. */
  37229. get: function () {
  37230. return this._shadowsExposure;
  37231. },
  37232. /**
  37233. * Sets the shadows Exposure value.
  37234. * 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.
  37235. */
  37236. set: function (value) {
  37237. this._shadowsExposure = value;
  37238. this._dirty = true;
  37239. },
  37240. enumerable: true,
  37241. configurable: true
  37242. });
  37243. ColorCurves.prototype.getClassName = function () {
  37244. return "ColorCurves";
  37245. };
  37246. /**
  37247. * Binds the color curves to the shader.
  37248. * @param colorCurves The color curve to bind
  37249. * @param effect The effect to bind to
  37250. */
  37251. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  37252. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  37253. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  37254. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  37255. if (colorCurves._dirty) {
  37256. colorCurves._dirty = false;
  37257. // Fill in global info.
  37258. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  37259. // Compute highlights info.
  37260. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  37261. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  37262. // Compute midtones info.
  37263. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  37264. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  37265. // Compute shadows info.
  37266. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  37267. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  37268. // Compute deltas (neutral is midtones).
  37269. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  37270. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  37271. }
  37272. if (effect) {
  37273. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  37274. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  37275. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  37276. }
  37277. };
  37278. /**
  37279. * Prepare the list of uniforms associated with the ColorCurves effects.
  37280. * @param uniformsList The list of uniforms used in the effect
  37281. */
  37282. ColorCurves.PrepareUniforms = function (uniformsList) {
  37283. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  37284. };
  37285. /**
  37286. * Returns color grading data based on a hue, density, saturation and exposure value.
  37287. * @param filterHue The hue of the color filter.
  37288. * @param filterDensity The density of the color filter.
  37289. * @param saturation The saturation.
  37290. * @param exposure The exposure.
  37291. * @param result The result data container.
  37292. */
  37293. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  37294. if (hue == null) {
  37295. return;
  37296. }
  37297. hue = ColorCurves.clamp(hue, 0, 360);
  37298. density = ColorCurves.clamp(density, -100, 100);
  37299. saturation = ColorCurves.clamp(saturation, -100, 100);
  37300. exposure = ColorCurves.clamp(exposure, -100, 100);
  37301. // Remap the slider/config filter density with non-linear mapping and also scale by half
  37302. // so that the maximum filter density is only 50% control. This provides fine control
  37303. // for small values and reasonable range.
  37304. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  37305. density *= 0.5;
  37306. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  37307. if (density < 0) {
  37308. density *= -1;
  37309. hue = (hue + 180) % 360;
  37310. }
  37311. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  37312. result.scaleToRef(2, result);
  37313. result.a = 1 + 0.01 * saturation;
  37314. };
  37315. /**
  37316. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  37317. * @param value The input slider value in range [-100,100].
  37318. * @returns Adjusted value.
  37319. */
  37320. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  37321. value /= 100;
  37322. var x = Math.abs(value);
  37323. x = Math.pow(x, 2);
  37324. if (value < 0) {
  37325. x *= -1;
  37326. }
  37327. x *= 100;
  37328. return x;
  37329. };
  37330. /**
  37331. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  37332. * @param hue The hue (H) input.
  37333. * @param saturation The saturation (S) input.
  37334. * @param brightness The brightness (B) input.
  37335. * @result An RGBA color represented as Vector4.
  37336. */
  37337. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  37338. var h = ColorCurves.clamp(hue, 0, 360);
  37339. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  37340. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  37341. if (s === 0) {
  37342. result.r = v;
  37343. result.g = v;
  37344. result.b = v;
  37345. }
  37346. else {
  37347. // sector 0 to 5
  37348. h /= 60;
  37349. var i = Math.floor(h);
  37350. // fractional part of h
  37351. var f = h - i;
  37352. var p = v * (1 - s);
  37353. var q = v * (1 - s * f);
  37354. var t = v * (1 - s * (1 - f));
  37355. switch (i) {
  37356. case 0:
  37357. result.r = v;
  37358. result.g = t;
  37359. result.b = p;
  37360. break;
  37361. case 1:
  37362. result.r = q;
  37363. result.g = v;
  37364. result.b = p;
  37365. break;
  37366. case 2:
  37367. result.r = p;
  37368. result.g = v;
  37369. result.b = t;
  37370. break;
  37371. case 3:
  37372. result.r = p;
  37373. result.g = q;
  37374. result.b = v;
  37375. break;
  37376. case 4:
  37377. result.r = t;
  37378. result.g = p;
  37379. result.b = v;
  37380. break;
  37381. default:// case 5:
  37382. result.r = v;
  37383. result.g = p;
  37384. result.b = q;
  37385. break;
  37386. }
  37387. }
  37388. result.a = 1;
  37389. };
  37390. /**
  37391. * Returns a value clamped between min and max
  37392. * @param value The value to clamp
  37393. * @param min The minimum of value
  37394. * @param max The maximum of value
  37395. * @returns The clamped value.
  37396. */
  37397. ColorCurves.clamp = function (value, min, max) {
  37398. return Math.min(Math.max(value, min), max);
  37399. };
  37400. /**
  37401. * Clones the current color curve instance.
  37402. * @return The cloned curves
  37403. */
  37404. ColorCurves.prototype.clone = function () {
  37405. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  37406. };
  37407. /**
  37408. * Serializes the current color curve instance to a json representation.
  37409. * @return a JSON representation
  37410. */
  37411. ColorCurves.prototype.serialize = function () {
  37412. return BABYLON.SerializationHelper.Serialize(this);
  37413. };
  37414. /**
  37415. * Parses the color curve from a json representation.
  37416. * @param source the JSON source to parse
  37417. * @return The parsed curves
  37418. */
  37419. ColorCurves.Parse = function (source) {
  37420. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  37421. };
  37422. __decorate([
  37423. BABYLON.serialize()
  37424. ], ColorCurves.prototype, "_globalHue", void 0);
  37425. __decorate([
  37426. BABYLON.serialize()
  37427. ], ColorCurves.prototype, "_globalDensity", void 0);
  37428. __decorate([
  37429. BABYLON.serialize()
  37430. ], ColorCurves.prototype, "_globalSaturation", void 0);
  37431. __decorate([
  37432. BABYLON.serialize()
  37433. ], ColorCurves.prototype, "_globalExposure", void 0);
  37434. __decorate([
  37435. BABYLON.serialize()
  37436. ], ColorCurves.prototype, "_highlightsHue", void 0);
  37437. __decorate([
  37438. BABYLON.serialize()
  37439. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  37440. __decorate([
  37441. BABYLON.serialize()
  37442. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  37443. __decorate([
  37444. BABYLON.serialize()
  37445. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  37446. __decorate([
  37447. BABYLON.serialize()
  37448. ], ColorCurves.prototype, "_midtonesHue", void 0);
  37449. __decorate([
  37450. BABYLON.serialize()
  37451. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  37452. __decorate([
  37453. BABYLON.serialize()
  37454. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  37455. __decorate([
  37456. BABYLON.serialize()
  37457. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  37458. return ColorCurves;
  37459. }());
  37460. BABYLON.ColorCurves = ColorCurves;
  37461. })(BABYLON || (BABYLON = {}));
  37462. //# sourceMappingURL=babylon.colorCurves.js.map
  37463. //# sourceMappingURL=babylon.behavior.js.map
  37464. var BABYLON;
  37465. (function (BABYLON) {
  37466. /**
  37467. * "Static Class" containing the most commonly used helper while dealing with material for
  37468. * rendering purpose.
  37469. *
  37470. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  37471. *
  37472. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  37473. */
  37474. var MaterialHelper = /** @class */ (function () {
  37475. function MaterialHelper() {
  37476. }
  37477. /**
  37478. * Bind the current view position to an effect.
  37479. * @param effect The effect to be bound
  37480. * @param scene The scene the eyes position is used from
  37481. */
  37482. MaterialHelper.BindEyePosition = function (effect, scene) {
  37483. if (scene._forcedViewPosition) {
  37484. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  37485. return;
  37486. }
  37487. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  37488. };
  37489. /**
  37490. * Helps preparing the defines values about the UVs in used in the effect.
  37491. * UVs are shared as much as we can accross chanels in the shaders.
  37492. * @param texture The texture we are preparing the UVs for
  37493. * @param defines The defines to update
  37494. * @param key The chanel key "diffuse", "specular"... used in the shader
  37495. */
  37496. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  37497. defines._needUVs = true;
  37498. defines[key] = true;
  37499. if (texture.getTextureMatrix().isIdentity(true)) {
  37500. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  37501. if (texture.coordinatesIndex === 0) {
  37502. defines["MAINUV1"] = true;
  37503. }
  37504. else {
  37505. defines["MAINUV2"] = true;
  37506. }
  37507. }
  37508. else {
  37509. defines[key + "DIRECTUV"] = 0;
  37510. }
  37511. };
  37512. /**
  37513. * Binds a texture matrix value to its corrsponding uniform
  37514. * @param texture The texture to bind the matrix for
  37515. * @param uniformBuffer The uniform buffer receivin the data
  37516. * @param key The chanel key "diffuse", "specular"... used in the shader
  37517. */
  37518. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  37519. var matrix = texture.getTextureMatrix();
  37520. if (!matrix.isIdentity(true)) {
  37521. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  37522. }
  37523. };
  37524. /**
  37525. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  37526. * @param mesh defines the current mesh
  37527. * @param scene defines the current scene
  37528. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  37529. * @param pointsCloud defines if point cloud rendering has to be turned on
  37530. * @param fogEnabled defines if fog has to be turned on
  37531. * @param alphaTest defines if alpha testing has to be turned on
  37532. * @param defines defines the current list of defines
  37533. */
  37534. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  37535. if (defines._areMiscDirty) {
  37536. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  37537. defines["POINTSIZE"] = (pointsCloud || scene.forcePointsCloud);
  37538. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  37539. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  37540. defines["ALPHATEST"] = alphaTest;
  37541. }
  37542. };
  37543. /**
  37544. * Helper used to prepare the list of defines associated with frame values for shader compilation
  37545. * @param scene defines the current scene
  37546. * @param engine defines the current engine
  37547. * @param defines specifies the list of active defines
  37548. * @param useInstances defines if instances have to be turned on
  37549. * @param useClipPlane defines if clip plane have to be turned on
  37550. */
  37551. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  37552. if (useClipPlane === void 0) { useClipPlane = null; }
  37553. var changed = false;
  37554. if (useClipPlane == null) {
  37555. useClipPlane = (scene.clipPlane !== undefined && scene.clipPlane !== null);
  37556. }
  37557. if (defines["CLIPPLANE"] !== useClipPlane) {
  37558. defines["CLIPPLANE"] = useClipPlane;
  37559. changed = true;
  37560. }
  37561. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  37562. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  37563. changed = true;
  37564. }
  37565. if (defines["INSTANCES"] !== useInstances) {
  37566. defines["INSTANCES"] = useInstances;
  37567. changed = true;
  37568. }
  37569. if (changed) {
  37570. defines.markAsUnprocessed();
  37571. }
  37572. };
  37573. /**
  37574. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  37575. * @param mesh The mesh containing the geometry data we will draw
  37576. * @param defines The defines to update
  37577. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  37578. * @param useBones Precise whether bones should be used or not (override mesh info)
  37579. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  37580. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  37581. * @returns false if defines are considered not dirty and have not been checked
  37582. */
  37583. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  37584. if (useMorphTargets === void 0) { useMorphTargets = false; }
  37585. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  37586. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  37587. return false;
  37588. }
  37589. defines._normals = defines._needNormals;
  37590. defines._uvs = defines._needUVs;
  37591. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  37592. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  37593. defines["TANGENT"] = true;
  37594. }
  37595. if (defines._needUVs) {
  37596. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  37597. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  37598. }
  37599. else {
  37600. defines["UV1"] = false;
  37601. defines["UV2"] = false;
  37602. }
  37603. if (useVertexColor) {
  37604. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  37605. defines["VERTEXCOLOR"] = hasVertexColors;
  37606. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  37607. }
  37608. if (useBones) {
  37609. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  37610. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  37611. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  37612. }
  37613. else {
  37614. defines["NUM_BONE_INFLUENCERS"] = 0;
  37615. defines["BonesPerMesh"] = 0;
  37616. }
  37617. }
  37618. if (useMorphTargets) {
  37619. var manager = mesh.morphTargetManager;
  37620. if (manager) {
  37621. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  37622. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  37623. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  37624. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  37625. }
  37626. else {
  37627. defines["MORPHTARGETS_TANGENT"] = false;
  37628. defines["MORPHTARGETS_NORMAL"] = false;
  37629. defines["MORPHTARGETS"] = false;
  37630. defines["NUM_MORPH_INFLUENCERS"] = 0;
  37631. }
  37632. }
  37633. return true;
  37634. };
  37635. /**
  37636. * Prepares the defines related to the light information passed in parameter
  37637. * @param scene The scene we are intending to draw
  37638. * @param mesh The mesh the effect is compiling for
  37639. * @param defines The defines to update
  37640. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  37641. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  37642. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  37643. * @returns true if normals will be required for the rest of the effect
  37644. */
  37645. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  37646. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  37647. if (disableLighting === void 0) { disableLighting = false; }
  37648. if (!defines._areLightsDirty) {
  37649. return defines._needNormals;
  37650. }
  37651. var lightIndex = 0;
  37652. var needNormals = false;
  37653. var needRebuild = false;
  37654. var lightmapMode = false;
  37655. var shadowEnabled = false;
  37656. var specularEnabled = false;
  37657. if (scene.lightsEnabled && !disableLighting) {
  37658. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  37659. var light = _a[_i];
  37660. needNormals = true;
  37661. if (defines["LIGHT" + lightIndex] === undefined) {
  37662. needRebuild = true;
  37663. }
  37664. defines["LIGHT" + lightIndex] = true;
  37665. defines["SPOTLIGHT" + lightIndex] = false;
  37666. defines["HEMILIGHT" + lightIndex] = false;
  37667. defines["POINTLIGHT" + lightIndex] = false;
  37668. defines["DIRLIGHT" + lightIndex] = false;
  37669. var type;
  37670. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  37671. type = "SPOTLIGHT" + lightIndex;
  37672. var spotLight = light;
  37673. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = spotLight.projectionTexture ? spotLight.projectionTexture.isReady() : false;
  37674. }
  37675. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  37676. type = "HEMILIGHT" + lightIndex;
  37677. }
  37678. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  37679. type = "POINTLIGHT" + lightIndex;
  37680. }
  37681. else {
  37682. type = "DIRLIGHT" + lightIndex;
  37683. }
  37684. defines[type] = true;
  37685. // Specular
  37686. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  37687. specularEnabled = true;
  37688. }
  37689. // Shadows
  37690. defines["SHADOW" + lightIndex] = false;
  37691. defines["SHADOWPCF" + lightIndex] = false;
  37692. defines["SHADOWESM" + lightIndex] = false;
  37693. defines["SHADOWCUBE" + lightIndex] = false;
  37694. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  37695. var shadowGenerator = light.getShadowGenerator();
  37696. if (shadowGenerator) {
  37697. shadowEnabled = true;
  37698. shadowGenerator.prepareDefines(defines, lightIndex);
  37699. }
  37700. }
  37701. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  37702. lightmapMode = true;
  37703. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  37704. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  37705. }
  37706. else {
  37707. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  37708. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  37709. }
  37710. lightIndex++;
  37711. if (lightIndex === maxSimultaneousLights)
  37712. break;
  37713. }
  37714. }
  37715. defines["SPECULARTERM"] = specularEnabled;
  37716. defines["SHADOWS"] = shadowEnabled;
  37717. // Resetting all other lights if any
  37718. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  37719. if (defines["LIGHT" + index] !== undefined) {
  37720. defines["LIGHT" + index] = false;
  37721. defines["HEMILIGHT" + lightIndex] = false;
  37722. defines["POINTLIGHT" + lightIndex] = false;
  37723. defines["DIRLIGHT" + lightIndex] = false;
  37724. defines["SPOTLIGHT" + lightIndex] = false;
  37725. defines["SHADOW" + lightIndex] = false;
  37726. }
  37727. }
  37728. var caps = scene.getEngine().getCaps();
  37729. if (defines["SHADOWFLOAT"] === undefined) {
  37730. needRebuild = true;
  37731. }
  37732. defines["SHADOWFLOAT"] = shadowEnabled &&
  37733. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  37734. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  37735. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  37736. if (needRebuild) {
  37737. defines.rebuild();
  37738. }
  37739. return needNormals;
  37740. };
  37741. /**
  37742. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  37743. * that won t be acctive due to defines being turned off.
  37744. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  37745. * @param samplersList The samplers list
  37746. * @param defines The defines helping in the list generation
  37747. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  37748. */
  37749. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  37750. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  37751. var uniformsList;
  37752. var uniformBuffersList = null;
  37753. if (uniformsListOrOptions.uniformsNames) {
  37754. var options = uniformsListOrOptions;
  37755. uniformsList = options.uniformsNames;
  37756. uniformBuffersList = options.uniformBuffersNames;
  37757. samplersList = options.samplers;
  37758. defines = options.defines;
  37759. maxSimultaneousLights = options.maxSimultaneousLights;
  37760. }
  37761. else {
  37762. uniformsList = uniformsListOrOptions;
  37763. if (!samplersList) {
  37764. samplersList = [];
  37765. }
  37766. }
  37767. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  37768. if (!defines["LIGHT" + lightIndex]) {
  37769. break;
  37770. }
  37771. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  37772. if (uniformBuffersList) {
  37773. uniformBuffersList.push("Light" + lightIndex);
  37774. }
  37775. samplersList.push("shadowSampler" + lightIndex);
  37776. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  37777. samplersList.push("projectionLightSampler" + lightIndex);
  37778. uniformsList.push("textureProjectionMatrix" + lightIndex);
  37779. }
  37780. }
  37781. if (defines["NUM_MORPH_INFLUENCERS"]) {
  37782. uniformsList.push("morphTargetInfluences");
  37783. }
  37784. };
  37785. /**
  37786. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  37787. * @param defines The defines to update while falling back
  37788. * @param fallbacks The authorized effect fallbacks
  37789. * @param maxSimultaneousLights The maximum number of lights allowed
  37790. * @param rank the current rank of the Effect
  37791. * @returns The newly affected rank
  37792. */
  37793. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  37794. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  37795. if (rank === void 0) { rank = 0; }
  37796. var lightFallbackRank = 0;
  37797. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  37798. if (!defines["LIGHT" + lightIndex]) {
  37799. break;
  37800. }
  37801. if (lightIndex > 0) {
  37802. lightFallbackRank = rank + lightIndex;
  37803. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  37804. }
  37805. if (!defines["SHADOWS"]) {
  37806. if (defines["SHADOW" + lightIndex]) {
  37807. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  37808. }
  37809. if (defines["SHADOWPCF" + lightIndex]) {
  37810. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  37811. }
  37812. if (defines["SHADOWESM" + lightIndex]) {
  37813. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  37814. }
  37815. }
  37816. }
  37817. return lightFallbackRank++;
  37818. };
  37819. /**
  37820. * Prepares the list of attributes required for morph targets according to the effect defines.
  37821. * @param attribs The current list of supported attribs
  37822. * @param mesh The mesh to prepare the morph targets attributes for
  37823. * @param defines The current Defines of the effect
  37824. */
  37825. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  37826. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  37827. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  37828. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  37829. var manager = mesh.morphTargetManager;
  37830. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  37831. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  37832. for (var index = 0; index < influencers; index++) {
  37833. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  37834. if (normal) {
  37835. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  37836. }
  37837. if (tangent) {
  37838. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  37839. }
  37840. if (attribs.length > maxAttributesCount) {
  37841. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  37842. }
  37843. }
  37844. }
  37845. };
  37846. /**
  37847. * Prepares the list of attributes required for bones according to the effect defines.
  37848. * @param attribs The current list of supported attribs
  37849. * @param mesh The mesh to prepare the bones attributes for
  37850. * @param defines The current Defines of the effect
  37851. * @param fallbacks The current efffect fallback strategy
  37852. */
  37853. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  37854. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  37855. fallbacks.addCPUSkinningFallback(0, mesh);
  37856. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  37857. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  37858. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  37859. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  37860. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  37861. }
  37862. }
  37863. };
  37864. /**
  37865. * Prepares the list of attributes required for instances according to the effect defines.
  37866. * @param attribs The current list of supported attribs
  37867. * @param defines The current Defines of the effect
  37868. */
  37869. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  37870. if (defines["INSTANCES"]) {
  37871. attribs.push("world0");
  37872. attribs.push("world1");
  37873. attribs.push("world2");
  37874. attribs.push("world3");
  37875. }
  37876. };
  37877. /**
  37878. * Binds the light shadow information to the effect for the given mesh.
  37879. * @param light The light containing the generator
  37880. * @param scene The scene the lights belongs to
  37881. * @param mesh The mesh we are binding the information to render
  37882. * @param lightIndex The light index in the effect used to render the mesh
  37883. * @param effect The effect we are binding the data to
  37884. */
  37885. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  37886. if (light.shadowEnabled && mesh.receiveShadows) {
  37887. var shadowGenerator = light.getShadowGenerator();
  37888. if (shadowGenerator) {
  37889. shadowGenerator.bindShadowLight(lightIndex, effect);
  37890. }
  37891. }
  37892. };
  37893. /**
  37894. * Binds the light information to the effect.
  37895. * @param light The light containing the generator
  37896. * @param effect The effect we are binding the data to
  37897. * @param lightIndex The light index in the effect used to render
  37898. */
  37899. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  37900. light.transferToEffect(effect, lightIndex + "");
  37901. };
  37902. /**
  37903. * Binds the lights information from the scene to the effect for the given mesh.
  37904. * @param scene The scene the lights belongs to
  37905. * @param mesh The mesh we are binding the information to render
  37906. * @param effect The effect we are binding the data to
  37907. * @param defines The generated defines for the effect
  37908. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  37909. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  37910. */
  37911. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  37912. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  37913. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  37914. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  37915. for (var i = 0; i < len; i++) {
  37916. var light = mesh._lightSources[i];
  37917. var iAsString = i.toString();
  37918. var scaledIntensity = light.getScaledIntensity();
  37919. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  37920. MaterialHelper.BindLightProperties(light, effect, i);
  37921. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  37922. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  37923. if (defines["SPECULARTERM"]) {
  37924. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  37925. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  37926. }
  37927. // Shadows
  37928. if (scene.shadowsEnabled) {
  37929. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  37930. }
  37931. light._uniformBuffer.update();
  37932. }
  37933. };
  37934. /**
  37935. * Binds the fog information from the scene to the effect for the given mesh.
  37936. * @param scene The scene the lights belongs to
  37937. * @param mesh The mesh we are binding the information to render
  37938. * @param effect The effect we are binding the data to
  37939. */
  37940. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  37941. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  37942. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  37943. effect.setColor3("vFogColor", scene.fogColor);
  37944. }
  37945. };
  37946. /**
  37947. * Binds the bones information from the mesh to the effect.
  37948. * @param mesh The mesh we are binding the information to render
  37949. * @param effect The effect we are binding the data to
  37950. */
  37951. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  37952. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  37953. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  37954. if (matrices && effect) {
  37955. effect.setMatrices("mBones", matrices);
  37956. }
  37957. }
  37958. };
  37959. /**
  37960. * Binds the morph targets information from the mesh to the effect.
  37961. * @param abstractMesh The mesh we are binding the information to render
  37962. * @param effect The effect we are binding the data to
  37963. */
  37964. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  37965. var manager = abstractMesh.morphTargetManager;
  37966. if (!abstractMesh || !manager) {
  37967. return;
  37968. }
  37969. effect.setFloatArray("morphTargetInfluences", manager.influences);
  37970. };
  37971. /**
  37972. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  37973. * @param defines The generated defines used in the effect
  37974. * @param effect The effect we are binding the data to
  37975. * @param scene The scene we are willing to render with logarithmic scale for
  37976. */
  37977. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  37978. if (defines["LOGARITHMICDEPTH"]) {
  37979. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  37980. }
  37981. };
  37982. /**
  37983. * Binds the clip plane information from the scene to the effect.
  37984. * @param scene The scene the clip plane information are extracted from
  37985. * @param effect The effect we are binding the data to
  37986. */
  37987. MaterialHelper.BindClipPlane = function (effect, scene) {
  37988. if (scene.clipPlane) {
  37989. var clipPlane = scene.clipPlane;
  37990. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  37991. }
  37992. };
  37993. return MaterialHelper;
  37994. }());
  37995. BABYLON.MaterialHelper = MaterialHelper;
  37996. })(BABYLON || (BABYLON = {}));
  37997. //# sourceMappingURL=babylon.materialHelper.js.map
  37998. var BABYLON;
  37999. (function (BABYLON) {
  38000. var PushMaterial = /** @class */ (function (_super) {
  38001. __extends(PushMaterial, _super);
  38002. function PushMaterial(name, scene) {
  38003. var _this = _super.call(this, name, scene) || this;
  38004. _this.storeEffectOnSubMeshes = true;
  38005. return _this;
  38006. }
  38007. PushMaterial.prototype.getEffect = function () {
  38008. return this._activeEffect;
  38009. };
  38010. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  38011. if (!mesh) {
  38012. return false;
  38013. }
  38014. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  38015. return true;
  38016. }
  38017. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  38018. };
  38019. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  38020. this._activeEffect.setMatrix("world", world);
  38021. };
  38022. PushMaterial.prototype.bind = function (world, mesh) {
  38023. if (!mesh) {
  38024. return;
  38025. }
  38026. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  38027. };
  38028. PushMaterial.prototype._afterBind = function (mesh, effect) {
  38029. if (effect === void 0) { effect = null; }
  38030. _super.prototype._afterBind.call(this, mesh);
  38031. this.getScene()._cachedEffect = effect;
  38032. };
  38033. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  38034. if (visibility === void 0) { visibility = 1; }
  38035. return scene.isCachedMaterialInvalid(this, effect, visibility);
  38036. };
  38037. return PushMaterial;
  38038. }(BABYLON.Material));
  38039. BABYLON.PushMaterial = PushMaterial;
  38040. })(BABYLON || (BABYLON = {}));
  38041. //# sourceMappingURL=babylon.pushMaterial.js.map
  38042. var BABYLON;
  38043. (function (BABYLON) {
  38044. /** @ignore */
  38045. var StandardMaterialDefines = /** @class */ (function (_super) {
  38046. __extends(StandardMaterialDefines, _super);
  38047. function StandardMaterialDefines() {
  38048. var _this = _super.call(this) || this;
  38049. _this.MAINUV1 = false;
  38050. _this.MAINUV2 = false;
  38051. _this.DIFFUSE = false;
  38052. _this.DIFFUSEDIRECTUV = 0;
  38053. _this.AMBIENT = false;
  38054. _this.AMBIENTDIRECTUV = 0;
  38055. _this.OPACITY = false;
  38056. _this.OPACITYDIRECTUV = 0;
  38057. _this.OPACITYRGB = false;
  38058. _this.REFLECTION = false;
  38059. _this.EMISSIVE = false;
  38060. _this.EMISSIVEDIRECTUV = 0;
  38061. _this.SPECULAR = false;
  38062. _this.SPECULARDIRECTUV = 0;
  38063. _this.BUMP = false;
  38064. _this.BUMPDIRECTUV = 0;
  38065. _this.PARALLAX = false;
  38066. _this.PARALLAXOCCLUSION = false;
  38067. _this.SPECULAROVERALPHA = false;
  38068. _this.CLIPPLANE = false;
  38069. _this.ALPHATEST = false;
  38070. _this.DEPTHPREPASS = false;
  38071. _this.ALPHAFROMDIFFUSE = false;
  38072. _this.POINTSIZE = false;
  38073. _this.FOG = false;
  38074. _this.SPECULARTERM = false;
  38075. _this.DIFFUSEFRESNEL = false;
  38076. _this.OPACITYFRESNEL = false;
  38077. _this.REFLECTIONFRESNEL = false;
  38078. _this.REFRACTIONFRESNEL = false;
  38079. _this.EMISSIVEFRESNEL = false;
  38080. _this.FRESNEL = false;
  38081. _this.NORMAL = false;
  38082. _this.UV1 = false;
  38083. _this.UV2 = false;
  38084. _this.VERTEXCOLOR = false;
  38085. _this.VERTEXALPHA = false;
  38086. _this.NUM_BONE_INFLUENCERS = 0;
  38087. _this.BonesPerMesh = 0;
  38088. _this.INSTANCES = false;
  38089. _this.GLOSSINESS = false;
  38090. _this.ROUGHNESS = false;
  38091. _this.EMISSIVEASILLUMINATION = false;
  38092. _this.LINKEMISSIVEWITHDIFFUSE = false;
  38093. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  38094. _this.LIGHTMAP = false;
  38095. _this.LIGHTMAPDIRECTUV = 0;
  38096. _this.USELIGHTMAPASSHADOWMAP = false;
  38097. _this.REFLECTIONMAP_3D = false;
  38098. _this.REFLECTIONMAP_SPHERICAL = false;
  38099. _this.REFLECTIONMAP_PLANAR = false;
  38100. _this.REFLECTIONMAP_CUBIC = false;
  38101. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  38102. _this.REFLECTIONMAP_PROJECTION = false;
  38103. _this.REFLECTIONMAP_SKYBOX = false;
  38104. _this.REFLECTIONMAP_EXPLICIT = false;
  38105. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  38106. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  38107. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  38108. _this.INVERTCUBICMAP = false;
  38109. _this.LOGARITHMICDEPTH = false;
  38110. _this.REFRACTION = false;
  38111. _this.REFRACTIONMAP_3D = false;
  38112. _this.REFLECTIONOVERALPHA = false;
  38113. _this.TWOSIDEDLIGHTING = false;
  38114. _this.SHADOWFLOAT = false;
  38115. _this.MORPHTARGETS = false;
  38116. _this.MORPHTARGETS_NORMAL = false;
  38117. _this.MORPHTARGETS_TANGENT = false;
  38118. _this.NUM_MORPH_INFLUENCERS = 0;
  38119. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  38120. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  38121. _this.IMAGEPROCESSING = false;
  38122. _this.VIGNETTE = false;
  38123. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  38124. _this.VIGNETTEBLENDMODEOPAQUE = false;
  38125. _this.TONEMAPPING = false;
  38126. _this.CONTRAST = false;
  38127. _this.COLORCURVES = false;
  38128. _this.COLORGRADING = false;
  38129. _this.COLORGRADING3D = false;
  38130. _this.SAMPLER3DGREENDEPTH = false;
  38131. _this.SAMPLER3DBGRMAP = false;
  38132. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  38133. _this.EXPOSURE = false;
  38134. _this.rebuild();
  38135. return _this;
  38136. }
  38137. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  38138. var modes = [
  38139. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  38140. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  38141. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  38142. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  38143. ];
  38144. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  38145. var mode = modes_1[_i];
  38146. this[mode] = (mode === modeToEnable);
  38147. }
  38148. };
  38149. return StandardMaterialDefines;
  38150. }(BABYLON.MaterialDefines));
  38151. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  38152. var StandardMaterial = /** @class */ (function (_super) {
  38153. __extends(StandardMaterial, _super);
  38154. function StandardMaterial(name, scene) {
  38155. var _this = _super.call(this, name, scene) || this;
  38156. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  38157. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  38158. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  38159. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  38160. _this.specularPower = 64;
  38161. _this._useAlphaFromDiffuseTexture = false;
  38162. _this._useEmissiveAsIllumination = false;
  38163. _this._linkEmissiveWithDiffuse = false;
  38164. _this._useSpecularOverAlpha = false;
  38165. _this._useReflectionOverAlpha = false;
  38166. _this._disableLighting = false;
  38167. _this._useParallax = false;
  38168. _this._useParallaxOcclusion = false;
  38169. _this.parallaxScaleBias = 0.05;
  38170. _this._roughness = 0;
  38171. _this.indexOfRefraction = 0.98;
  38172. _this.invertRefractionY = true;
  38173. _this._useLightmapAsShadowmap = false;
  38174. _this._useReflectionFresnelFromSpecular = false;
  38175. _this._useGlossinessFromSpecularMapAlpha = false;
  38176. _this._maxSimultaneousLights = 4;
  38177. /**
  38178. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  38179. */
  38180. _this._invertNormalMapX = false;
  38181. /**
  38182. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  38183. */
  38184. _this._invertNormalMapY = false;
  38185. /**
  38186. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  38187. */
  38188. _this._twoSidedLighting = false;
  38189. _this._renderTargets = new BABYLON.SmartArray(16);
  38190. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  38191. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  38192. // Setup the default processing configuration to the scene.
  38193. _this._attachImageProcessingConfiguration(null);
  38194. _this.getRenderTargetTextures = function () {
  38195. _this._renderTargets.reset();
  38196. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  38197. _this._renderTargets.push(_this._reflectionTexture);
  38198. }
  38199. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  38200. _this._renderTargets.push(_this._refractionTexture);
  38201. }
  38202. return _this._renderTargets;
  38203. };
  38204. return _this;
  38205. }
  38206. ;
  38207. ;
  38208. ;
  38209. ;
  38210. ;
  38211. ;
  38212. ;
  38213. ;
  38214. ;
  38215. ;
  38216. ;
  38217. ;
  38218. ;
  38219. ;
  38220. ;
  38221. ;
  38222. ;
  38223. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  38224. /**
  38225. * Gets the image processing configuration used either in this material.
  38226. */
  38227. get: function () {
  38228. return this._imageProcessingConfiguration;
  38229. },
  38230. /**
  38231. * Sets the Default image processing configuration used either in the this material.
  38232. *
  38233. * If sets to null, the scene one is in use.
  38234. */
  38235. set: function (value) {
  38236. this._attachImageProcessingConfiguration(value);
  38237. // Ensure the effect will be rebuilt.
  38238. this._markAllSubMeshesAsTexturesDirty();
  38239. },
  38240. enumerable: true,
  38241. configurable: true
  38242. });
  38243. /**
  38244. * Attaches a new image processing configuration to the Standard Material.
  38245. * @param configuration
  38246. */
  38247. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  38248. var _this = this;
  38249. if (configuration === this._imageProcessingConfiguration) {
  38250. return;
  38251. }
  38252. // Detaches observer.
  38253. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  38254. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  38255. }
  38256. // Pick the scene configuration if needed.
  38257. if (!configuration) {
  38258. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  38259. }
  38260. else {
  38261. this._imageProcessingConfiguration = configuration;
  38262. }
  38263. // Attaches observer.
  38264. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  38265. _this._markAllSubMeshesAsImageProcessingDirty();
  38266. });
  38267. };
  38268. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  38269. /**
  38270. * Gets wether the color curves effect is enabled.
  38271. */
  38272. get: function () {
  38273. return this.imageProcessingConfiguration.colorCurvesEnabled;
  38274. },
  38275. /**
  38276. * Sets wether the color curves effect is enabled.
  38277. */
  38278. set: function (value) {
  38279. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  38280. },
  38281. enumerable: true,
  38282. configurable: true
  38283. });
  38284. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  38285. /**
  38286. * Gets wether the color grading effect is enabled.
  38287. */
  38288. get: function () {
  38289. return this.imageProcessingConfiguration.colorGradingEnabled;
  38290. },
  38291. /**
  38292. * Gets wether the color grading effect is enabled.
  38293. */
  38294. set: function (value) {
  38295. this.imageProcessingConfiguration.colorGradingEnabled = value;
  38296. },
  38297. enumerable: true,
  38298. configurable: true
  38299. });
  38300. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  38301. /**
  38302. * Gets wether tonemapping is enabled or not.
  38303. */
  38304. get: function () {
  38305. return this._imageProcessingConfiguration.toneMappingEnabled;
  38306. },
  38307. /**
  38308. * Sets wether tonemapping is enabled or not
  38309. */
  38310. set: function (value) {
  38311. this._imageProcessingConfiguration.toneMappingEnabled = value;
  38312. },
  38313. enumerable: true,
  38314. configurable: true
  38315. });
  38316. ;
  38317. ;
  38318. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  38319. /**
  38320. * The camera exposure used on this material.
  38321. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  38322. * This corresponds to a photographic exposure.
  38323. */
  38324. get: function () {
  38325. return this._imageProcessingConfiguration.exposure;
  38326. },
  38327. /**
  38328. * The camera exposure used on this material.
  38329. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  38330. * This corresponds to a photographic exposure.
  38331. */
  38332. set: function (value) {
  38333. this._imageProcessingConfiguration.exposure = value;
  38334. },
  38335. enumerable: true,
  38336. configurable: true
  38337. });
  38338. ;
  38339. ;
  38340. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  38341. /**
  38342. * Gets The camera contrast used on this material.
  38343. */
  38344. get: function () {
  38345. return this._imageProcessingConfiguration.contrast;
  38346. },
  38347. /**
  38348. * Sets The camera contrast used on this material.
  38349. */
  38350. set: function (value) {
  38351. this._imageProcessingConfiguration.contrast = value;
  38352. },
  38353. enumerable: true,
  38354. configurable: true
  38355. });
  38356. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  38357. /**
  38358. * Gets the Color Grading 2D Lookup Texture.
  38359. */
  38360. get: function () {
  38361. return this._imageProcessingConfiguration.colorGradingTexture;
  38362. },
  38363. /**
  38364. * Sets the Color Grading 2D Lookup Texture.
  38365. */
  38366. set: function (value) {
  38367. this._imageProcessingConfiguration.colorGradingTexture = value;
  38368. },
  38369. enumerable: true,
  38370. configurable: true
  38371. });
  38372. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  38373. /**
  38374. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  38375. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  38376. * 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;
  38377. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  38378. */
  38379. get: function () {
  38380. return this._imageProcessingConfiguration.colorCurves;
  38381. },
  38382. /**
  38383. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  38384. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  38385. * 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;
  38386. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  38387. */
  38388. set: function (value) {
  38389. this._imageProcessingConfiguration.colorCurves = value;
  38390. },
  38391. enumerable: true,
  38392. configurable: true
  38393. });
  38394. StandardMaterial.prototype.getClassName = function () {
  38395. return "StandardMaterial";
  38396. };
  38397. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  38398. get: function () {
  38399. return this._useLogarithmicDepth;
  38400. },
  38401. set: function (value) {
  38402. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  38403. this._markAllSubMeshesAsMiscDirty();
  38404. },
  38405. enumerable: true,
  38406. configurable: true
  38407. });
  38408. StandardMaterial.prototype.needAlphaBlending = function () {
  38409. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  38410. };
  38411. StandardMaterial.prototype.needAlphaTesting = function () {
  38412. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  38413. };
  38414. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  38415. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  38416. };
  38417. StandardMaterial.prototype.getAlphaTestTexture = function () {
  38418. return this._diffuseTexture;
  38419. };
  38420. /**
  38421. * Child classes can use it to update shaders
  38422. */
  38423. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  38424. if (useInstances === void 0) { useInstances = false; }
  38425. if (subMesh.effect && this.isFrozen) {
  38426. if (this._wasPreviouslyReady && subMesh.effect) {
  38427. return true;
  38428. }
  38429. }
  38430. if (!subMesh._materialDefines) {
  38431. subMesh._materialDefines = new StandardMaterialDefines();
  38432. }
  38433. var scene = this.getScene();
  38434. var defines = subMesh._materialDefines;
  38435. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  38436. if (defines._renderId === scene.getRenderId()) {
  38437. return true;
  38438. }
  38439. }
  38440. var engine = scene.getEngine();
  38441. // Lights
  38442. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  38443. // Textures
  38444. if (defines._areTexturesDirty) {
  38445. defines._needUVs = false;
  38446. defines.MAINUV1 = false;
  38447. defines.MAINUV2 = false;
  38448. if (scene.texturesEnabled) {
  38449. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  38450. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  38451. return false;
  38452. }
  38453. else {
  38454. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  38455. }
  38456. }
  38457. else {
  38458. defines.DIFFUSE = false;
  38459. }
  38460. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  38461. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  38462. return false;
  38463. }
  38464. else {
  38465. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  38466. }
  38467. }
  38468. else {
  38469. defines.AMBIENT = false;
  38470. }
  38471. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  38472. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  38473. return false;
  38474. }
  38475. else {
  38476. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  38477. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  38478. }
  38479. }
  38480. else {
  38481. defines.OPACITY = false;
  38482. }
  38483. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  38484. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  38485. return false;
  38486. }
  38487. else {
  38488. defines._needNormals = true;
  38489. defines.REFLECTION = true;
  38490. defines.ROUGHNESS = (this._roughness > 0);
  38491. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  38492. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  38493. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  38494. switch (this._reflectionTexture.coordinatesMode) {
  38495. case BABYLON.Texture.CUBIC_MODE:
  38496. case BABYLON.Texture.INVCUBIC_MODE:
  38497. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  38498. break;
  38499. case BABYLON.Texture.EXPLICIT_MODE:
  38500. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  38501. break;
  38502. case BABYLON.Texture.PLANAR_MODE:
  38503. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  38504. break;
  38505. case BABYLON.Texture.PROJECTION_MODE:
  38506. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  38507. break;
  38508. case BABYLON.Texture.SKYBOX_MODE:
  38509. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  38510. break;
  38511. case BABYLON.Texture.SPHERICAL_MODE:
  38512. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  38513. break;
  38514. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  38515. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  38516. break;
  38517. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  38518. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  38519. break;
  38520. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  38521. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  38522. break;
  38523. }
  38524. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  38525. }
  38526. }
  38527. else {
  38528. defines.REFLECTION = false;
  38529. }
  38530. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  38531. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  38532. return false;
  38533. }
  38534. else {
  38535. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  38536. }
  38537. }
  38538. else {
  38539. defines.EMISSIVE = false;
  38540. }
  38541. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  38542. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  38543. return false;
  38544. }
  38545. else {
  38546. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  38547. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  38548. }
  38549. }
  38550. else {
  38551. defines.LIGHTMAP = false;
  38552. }
  38553. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  38554. if (!this._specularTexture.isReadyOrNotBlocking()) {
  38555. return false;
  38556. }
  38557. else {
  38558. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  38559. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  38560. }
  38561. }
  38562. else {
  38563. defines.SPECULAR = false;
  38564. }
  38565. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  38566. // Bump texure can not be not blocking.
  38567. if (!this._bumpTexture.isReady()) {
  38568. return false;
  38569. }
  38570. else {
  38571. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  38572. defines.PARALLAX = this._useParallax;
  38573. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  38574. }
  38575. }
  38576. else {
  38577. defines.BUMP = false;
  38578. }
  38579. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  38580. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  38581. return false;
  38582. }
  38583. else {
  38584. defines._needUVs = true;
  38585. defines.REFRACTION = true;
  38586. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  38587. }
  38588. }
  38589. else {
  38590. defines.REFRACTION = false;
  38591. }
  38592. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  38593. }
  38594. else {
  38595. defines.DIFFUSE = false;
  38596. defines.AMBIENT = false;
  38597. defines.OPACITY = false;
  38598. defines.REFLECTION = false;
  38599. defines.EMISSIVE = false;
  38600. defines.LIGHTMAP = false;
  38601. defines.BUMP = false;
  38602. defines.REFRACTION = false;
  38603. }
  38604. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  38605. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  38606. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  38607. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  38608. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  38609. }
  38610. if (defines._areImageProcessingDirty) {
  38611. if (!this._imageProcessingConfiguration.isReady()) {
  38612. return false;
  38613. }
  38614. this._imageProcessingConfiguration.prepareDefines(defines);
  38615. }
  38616. if (defines._areFresnelDirty) {
  38617. if (StandardMaterial.FresnelEnabled) {
  38618. // Fresnel
  38619. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  38620. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  38621. this._reflectionFresnelParameters) {
  38622. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  38623. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  38624. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  38625. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  38626. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  38627. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  38628. defines._needNormals = true;
  38629. defines.FRESNEL = true;
  38630. }
  38631. }
  38632. else {
  38633. defines.FRESNEL = false;
  38634. }
  38635. }
  38636. // Misc.
  38637. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  38638. // Attribs
  38639. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  38640. // Values that need to be evaluated on every frame
  38641. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  38642. // Get correct effect
  38643. if (defines.isDirty) {
  38644. defines.markAsProcessed();
  38645. scene.resetCachedMaterial();
  38646. // Fallbacks
  38647. var fallbacks = new BABYLON.EffectFallbacks();
  38648. if (defines.REFLECTION) {
  38649. fallbacks.addFallback(0, "REFLECTION");
  38650. }
  38651. if (defines.SPECULAR) {
  38652. fallbacks.addFallback(0, "SPECULAR");
  38653. }
  38654. if (defines.BUMP) {
  38655. fallbacks.addFallback(0, "BUMP");
  38656. }
  38657. if (defines.PARALLAX) {
  38658. fallbacks.addFallback(1, "PARALLAX");
  38659. }
  38660. if (defines.PARALLAXOCCLUSION) {
  38661. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  38662. }
  38663. if (defines.SPECULAROVERALPHA) {
  38664. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  38665. }
  38666. if (defines.FOG) {
  38667. fallbacks.addFallback(1, "FOG");
  38668. }
  38669. if (defines.POINTSIZE) {
  38670. fallbacks.addFallback(0, "POINTSIZE");
  38671. }
  38672. if (defines.LOGARITHMICDEPTH) {
  38673. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  38674. }
  38675. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  38676. if (defines.SPECULARTERM) {
  38677. fallbacks.addFallback(0, "SPECULARTERM");
  38678. }
  38679. if (defines.DIFFUSEFRESNEL) {
  38680. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  38681. }
  38682. if (defines.OPACITYFRESNEL) {
  38683. fallbacks.addFallback(2, "OPACITYFRESNEL");
  38684. }
  38685. if (defines.REFLECTIONFRESNEL) {
  38686. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  38687. }
  38688. if (defines.EMISSIVEFRESNEL) {
  38689. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  38690. }
  38691. if (defines.FRESNEL) {
  38692. fallbacks.addFallback(4, "FRESNEL");
  38693. }
  38694. //Attributes
  38695. var attribs = [BABYLON.VertexBuffer.PositionKind];
  38696. if (defines.NORMAL) {
  38697. attribs.push(BABYLON.VertexBuffer.NormalKind);
  38698. }
  38699. if (defines.UV1) {
  38700. attribs.push(BABYLON.VertexBuffer.UVKind);
  38701. }
  38702. if (defines.UV2) {
  38703. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  38704. }
  38705. if (defines.VERTEXCOLOR) {
  38706. attribs.push(BABYLON.VertexBuffer.ColorKind);
  38707. }
  38708. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  38709. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  38710. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  38711. var shaderName = "default";
  38712. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  38713. "vFogInfos", "vFogColor", "pointSize",
  38714. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  38715. "mBones",
  38716. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  38717. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  38718. "vReflectionPosition", "vReflectionSize",
  38719. "logarithmicDepthConstant", "vTangentSpaceParams"
  38720. ];
  38721. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  38722. var uniformBuffers = ["Material", "Scene"];
  38723. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  38724. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  38725. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  38726. uniformsNames: uniforms,
  38727. uniformBuffersNames: uniformBuffers,
  38728. samplers: samplers,
  38729. defines: defines,
  38730. maxSimultaneousLights: this._maxSimultaneousLights
  38731. });
  38732. if (this.customShaderNameResolve) {
  38733. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  38734. }
  38735. var join = defines.toString();
  38736. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  38737. attributes: attribs,
  38738. uniformsNames: uniforms,
  38739. uniformBuffersNames: uniformBuffers,
  38740. samplers: samplers,
  38741. defines: join,
  38742. fallbacks: fallbacks,
  38743. onCompiled: this.onCompiled,
  38744. onError: this.onError,
  38745. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  38746. }, engine), defines);
  38747. this.buildUniformLayout();
  38748. }
  38749. if (!subMesh.effect || !subMesh.effect.isReady()) {
  38750. return false;
  38751. }
  38752. defines._renderId = scene.getRenderId();
  38753. this._wasPreviouslyReady = true;
  38754. return true;
  38755. };
  38756. StandardMaterial.prototype.buildUniformLayout = function () {
  38757. // Order is important !
  38758. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  38759. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  38760. this._uniformBuffer.addUniform("opacityParts", 4);
  38761. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  38762. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  38763. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  38764. this._uniformBuffer.addUniform("refractionRightColor", 4);
  38765. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  38766. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  38767. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  38768. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  38769. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  38770. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  38771. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  38772. this._uniformBuffer.addUniform("vReflectionSize", 3);
  38773. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  38774. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  38775. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  38776. this._uniformBuffer.addUniform("vBumpInfos", 3);
  38777. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  38778. this._uniformBuffer.addUniform("ambientMatrix", 16);
  38779. this._uniformBuffer.addUniform("opacityMatrix", 16);
  38780. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  38781. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  38782. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  38783. this._uniformBuffer.addUniform("specularMatrix", 16);
  38784. this._uniformBuffer.addUniform("bumpMatrix", 16);
  38785. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  38786. this._uniformBuffer.addUniform("refractionMatrix", 16);
  38787. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  38788. this._uniformBuffer.addUniform("vSpecularColor", 4);
  38789. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  38790. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  38791. this._uniformBuffer.addUniform("pointSize", 1);
  38792. this._uniformBuffer.create();
  38793. };
  38794. StandardMaterial.prototype.unbind = function () {
  38795. if (this._activeEffect) {
  38796. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  38797. this._activeEffect.setTexture("reflection2DSampler", null);
  38798. }
  38799. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  38800. this._activeEffect.setTexture("refraction2DSampler", null);
  38801. }
  38802. }
  38803. _super.prototype.unbind.call(this);
  38804. };
  38805. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  38806. var scene = this.getScene();
  38807. var defines = subMesh._materialDefines;
  38808. if (!defines) {
  38809. return;
  38810. }
  38811. var effect = subMesh.effect;
  38812. if (!effect) {
  38813. return;
  38814. }
  38815. this._activeEffect = effect;
  38816. // Matrices
  38817. this.bindOnlyWorldMatrix(world);
  38818. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  38819. // Bones
  38820. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  38821. if (mustRebind) {
  38822. this._uniformBuffer.bindToEffect(effect, "Material");
  38823. this.bindViewProjection(effect);
  38824. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  38825. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  38826. // Fresnel
  38827. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  38828. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  38829. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  38830. }
  38831. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  38832. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  38833. }
  38834. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  38835. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  38836. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  38837. }
  38838. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  38839. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  38840. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  38841. }
  38842. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  38843. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  38844. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  38845. }
  38846. }
  38847. // Textures
  38848. if (scene.texturesEnabled) {
  38849. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  38850. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  38851. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  38852. }
  38853. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  38854. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  38855. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  38856. }
  38857. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  38858. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  38859. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  38860. }
  38861. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  38862. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  38863. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  38864. if (this._reflectionTexture.boundingBoxSize) {
  38865. var cubeTexture = this._reflectionTexture;
  38866. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  38867. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  38868. }
  38869. }
  38870. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  38871. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  38872. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  38873. }
  38874. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  38875. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  38876. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  38877. }
  38878. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  38879. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  38880. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  38881. }
  38882. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  38883. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  38884. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  38885. if (scene._mirroredCameraPosition) {
  38886. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  38887. }
  38888. else {
  38889. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  38890. }
  38891. }
  38892. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  38893. var depth = 1.0;
  38894. if (!this._refractionTexture.isCube) {
  38895. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  38896. if (this._refractionTexture.depth) {
  38897. depth = this._refractionTexture.depth;
  38898. }
  38899. }
  38900. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  38901. }
  38902. }
  38903. // Point size
  38904. if (this.pointsCloud) {
  38905. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  38906. }
  38907. if (defines.SPECULARTERM) {
  38908. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  38909. }
  38910. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  38911. // Diffuse
  38912. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  38913. }
  38914. // Textures
  38915. if (scene.texturesEnabled) {
  38916. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  38917. effect.setTexture("diffuseSampler", this._diffuseTexture);
  38918. }
  38919. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  38920. effect.setTexture("ambientSampler", this._ambientTexture);
  38921. }
  38922. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  38923. effect.setTexture("opacitySampler", this._opacityTexture);
  38924. }
  38925. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  38926. if (this._reflectionTexture.isCube) {
  38927. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  38928. }
  38929. else {
  38930. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  38931. }
  38932. }
  38933. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  38934. effect.setTexture("emissiveSampler", this._emissiveTexture);
  38935. }
  38936. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  38937. effect.setTexture("lightmapSampler", this._lightmapTexture);
  38938. }
  38939. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  38940. effect.setTexture("specularSampler", this._specularTexture);
  38941. }
  38942. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  38943. effect.setTexture("bumpSampler", this._bumpTexture);
  38944. }
  38945. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  38946. var depth = 1.0;
  38947. if (this._refractionTexture.isCube) {
  38948. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  38949. }
  38950. else {
  38951. effect.setTexture("refraction2DSampler", this._refractionTexture);
  38952. }
  38953. }
  38954. }
  38955. // Clip plane
  38956. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  38957. // Colors
  38958. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  38959. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  38960. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  38961. }
  38962. if (mustRebind || !this.isFrozen) {
  38963. // Lights
  38964. if (scene.lightsEnabled && !this._disableLighting) {
  38965. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  38966. }
  38967. // View
  38968. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  38969. this.bindView(effect);
  38970. }
  38971. // Fog
  38972. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  38973. // Morph targets
  38974. if (defines.NUM_MORPH_INFLUENCERS) {
  38975. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  38976. }
  38977. // Log. depth
  38978. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  38979. // image processing
  38980. if (!this._imageProcessingConfiguration.applyByPostProcess) {
  38981. this._imageProcessingConfiguration.bind(this._activeEffect);
  38982. }
  38983. }
  38984. this._uniformBuffer.update();
  38985. this._afterBind(mesh, this._activeEffect);
  38986. };
  38987. StandardMaterial.prototype.getAnimatables = function () {
  38988. var results = [];
  38989. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  38990. results.push(this._diffuseTexture);
  38991. }
  38992. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  38993. results.push(this._ambientTexture);
  38994. }
  38995. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  38996. results.push(this._opacityTexture);
  38997. }
  38998. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  38999. results.push(this._reflectionTexture);
  39000. }
  39001. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  39002. results.push(this._emissiveTexture);
  39003. }
  39004. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  39005. results.push(this._specularTexture);
  39006. }
  39007. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  39008. results.push(this._bumpTexture);
  39009. }
  39010. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  39011. results.push(this._lightmapTexture);
  39012. }
  39013. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  39014. results.push(this._refractionTexture);
  39015. }
  39016. return results;
  39017. };
  39018. StandardMaterial.prototype.getActiveTextures = function () {
  39019. var activeTextures = _super.prototype.getActiveTextures.call(this);
  39020. if (this._diffuseTexture) {
  39021. activeTextures.push(this._diffuseTexture);
  39022. }
  39023. if (this._ambientTexture) {
  39024. activeTextures.push(this._ambientTexture);
  39025. }
  39026. if (this._opacityTexture) {
  39027. activeTextures.push(this._opacityTexture);
  39028. }
  39029. if (this._reflectionTexture) {
  39030. activeTextures.push(this._reflectionTexture);
  39031. }
  39032. if (this._emissiveTexture) {
  39033. activeTextures.push(this._emissiveTexture);
  39034. }
  39035. if (this._specularTexture) {
  39036. activeTextures.push(this._specularTexture);
  39037. }
  39038. if (this._bumpTexture) {
  39039. activeTextures.push(this._bumpTexture);
  39040. }
  39041. if (this._lightmapTexture) {
  39042. activeTextures.push(this._lightmapTexture);
  39043. }
  39044. if (this._refractionTexture) {
  39045. activeTextures.push(this._refractionTexture);
  39046. }
  39047. return activeTextures;
  39048. };
  39049. StandardMaterial.prototype.hasTexture = function (texture) {
  39050. if (_super.prototype.hasTexture.call(this, texture)) {
  39051. return true;
  39052. }
  39053. if (this._diffuseTexture === texture) {
  39054. return true;
  39055. }
  39056. if (this._ambientTexture === texture) {
  39057. return true;
  39058. }
  39059. if (this._opacityTexture === texture) {
  39060. return true;
  39061. }
  39062. if (this._reflectionTexture === texture) {
  39063. return true;
  39064. }
  39065. if (this._emissiveTexture === texture) {
  39066. return true;
  39067. }
  39068. if (this._specularTexture === texture) {
  39069. return true;
  39070. }
  39071. if (this._bumpTexture === texture) {
  39072. return true;
  39073. }
  39074. if (this._lightmapTexture === texture) {
  39075. return true;
  39076. }
  39077. if (this._refractionTexture === texture) {
  39078. return true;
  39079. }
  39080. return false;
  39081. };
  39082. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  39083. if (forceDisposeTextures) {
  39084. if (this._diffuseTexture) {
  39085. this._diffuseTexture.dispose();
  39086. }
  39087. if (this._ambientTexture) {
  39088. this._ambientTexture.dispose();
  39089. }
  39090. if (this._opacityTexture) {
  39091. this._opacityTexture.dispose();
  39092. }
  39093. if (this._reflectionTexture) {
  39094. this._reflectionTexture.dispose();
  39095. }
  39096. if (this._emissiveTexture) {
  39097. this._emissiveTexture.dispose();
  39098. }
  39099. if (this._specularTexture) {
  39100. this._specularTexture.dispose();
  39101. }
  39102. if (this._bumpTexture) {
  39103. this._bumpTexture.dispose();
  39104. }
  39105. if (this._lightmapTexture) {
  39106. this._lightmapTexture.dispose();
  39107. }
  39108. if (this._refractionTexture) {
  39109. this._refractionTexture.dispose();
  39110. }
  39111. }
  39112. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  39113. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  39114. }
  39115. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  39116. };
  39117. StandardMaterial.prototype.clone = function (name) {
  39118. var _this = this;
  39119. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  39120. result.name = name;
  39121. result.id = name;
  39122. return result;
  39123. };
  39124. StandardMaterial.prototype.serialize = function () {
  39125. return BABYLON.SerializationHelper.Serialize(this);
  39126. };
  39127. // Statics
  39128. StandardMaterial.Parse = function (source, scene, rootUrl) {
  39129. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  39130. };
  39131. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  39132. get: function () {
  39133. return StandardMaterial._DiffuseTextureEnabled;
  39134. },
  39135. set: function (value) {
  39136. if (StandardMaterial._DiffuseTextureEnabled === value) {
  39137. return;
  39138. }
  39139. StandardMaterial._DiffuseTextureEnabled = value;
  39140. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39141. },
  39142. enumerable: true,
  39143. configurable: true
  39144. });
  39145. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  39146. get: function () {
  39147. return StandardMaterial._AmbientTextureEnabled;
  39148. },
  39149. set: function (value) {
  39150. if (StandardMaterial._AmbientTextureEnabled === value) {
  39151. return;
  39152. }
  39153. StandardMaterial._AmbientTextureEnabled = value;
  39154. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39155. },
  39156. enumerable: true,
  39157. configurable: true
  39158. });
  39159. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  39160. get: function () {
  39161. return StandardMaterial._OpacityTextureEnabled;
  39162. },
  39163. set: function (value) {
  39164. if (StandardMaterial._OpacityTextureEnabled === value) {
  39165. return;
  39166. }
  39167. StandardMaterial._OpacityTextureEnabled = value;
  39168. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39169. },
  39170. enumerable: true,
  39171. configurable: true
  39172. });
  39173. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  39174. get: function () {
  39175. return StandardMaterial._ReflectionTextureEnabled;
  39176. },
  39177. set: function (value) {
  39178. if (StandardMaterial._ReflectionTextureEnabled === value) {
  39179. return;
  39180. }
  39181. StandardMaterial._ReflectionTextureEnabled = value;
  39182. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39183. },
  39184. enumerable: true,
  39185. configurable: true
  39186. });
  39187. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  39188. get: function () {
  39189. return StandardMaterial._EmissiveTextureEnabled;
  39190. },
  39191. set: function (value) {
  39192. if (StandardMaterial._EmissiveTextureEnabled === value) {
  39193. return;
  39194. }
  39195. StandardMaterial._EmissiveTextureEnabled = value;
  39196. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39197. },
  39198. enumerable: true,
  39199. configurable: true
  39200. });
  39201. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  39202. get: function () {
  39203. return StandardMaterial._SpecularTextureEnabled;
  39204. },
  39205. set: function (value) {
  39206. if (StandardMaterial._SpecularTextureEnabled === value) {
  39207. return;
  39208. }
  39209. StandardMaterial._SpecularTextureEnabled = value;
  39210. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39211. },
  39212. enumerable: true,
  39213. configurable: true
  39214. });
  39215. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  39216. get: function () {
  39217. return StandardMaterial._BumpTextureEnabled;
  39218. },
  39219. set: function (value) {
  39220. if (StandardMaterial._BumpTextureEnabled === value) {
  39221. return;
  39222. }
  39223. StandardMaterial._BumpTextureEnabled = value;
  39224. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39225. },
  39226. enumerable: true,
  39227. configurable: true
  39228. });
  39229. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  39230. get: function () {
  39231. return StandardMaterial._LightmapTextureEnabled;
  39232. },
  39233. set: function (value) {
  39234. if (StandardMaterial._LightmapTextureEnabled === value) {
  39235. return;
  39236. }
  39237. StandardMaterial._LightmapTextureEnabled = value;
  39238. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39239. },
  39240. enumerable: true,
  39241. configurable: true
  39242. });
  39243. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  39244. get: function () {
  39245. return StandardMaterial._RefractionTextureEnabled;
  39246. },
  39247. set: function (value) {
  39248. if (StandardMaterial._RefractionTextureEnabled === value) {
  39249. return;
  39250. }
  39251. StandardMaterial._RefractionTextureEnabled = value;
  39252. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39253. },
  39254. enumerable: true,
  39255. configurable: true
  39256. });
  39257. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  39258. get: function () {
  39259. return StandardMaterial._ColorGradingTextureEnabled;
  39260. },
  39261. set: function (value) {
  39262. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  39263. return;
  39264. }
  39265. StandardMaterial._ColorGradingTextureEnabled = value;
  39266. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39267. },
  39268. enumerable: true,
  39269. configurable: true
  39270. });
  39271. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  39272. get: function () {
  39273. return StandardMaterial._FresnelEnabled;
  39274. },
  39275. set: function (value) {
  39276. if (StandardMaterial._FresnelEnabled === value) {
  39277. return;
  39278. }
  39279. StandardMaterial._FresnelEnabled = value;
  39280. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  39281. },
  39282. enumerable: true,
  39283. configurable: true
  39284. });
  39285. // Flags used to enable or disable a type of texture for all Standard Materials
  39286. StandardMaterial._DiffuseTextureEnabled = true;
  39287. StandardMaterial._AmbientTextureEnabled = true;
  39288. StandardMaterial._OpacityTextureEnabled = true;
  39289. StandardMaterial._ReflectionTextureEnabled = true;
  39290. StandardMaterial._EmissiveTextureEnabled = true;
  39291. StandardMaterial._SpecularTextureEnabled = true;
  39292. StandardMaterial._BumpTextureEnabled = true;
  39293. StandardMaterial._LightmapTextureEnabled = true;
  39294. StandardMaterial._RefractionTextureEnabled = true;
  39295. StandardMaterial._ColorGradingTextureEnabled = true;
  39296. StandardMaterial._FresnelEnabled = true;
  39297. __decorate([
  39298. BABYLON.serializeAsTexture("diffuseTexture")
  39299. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  39300. __decorate([
  39301. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  39302. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  39303. __decorate([
  39304. BABYLON.serializeAsTexture("ambientTexture")
  39305. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  39306. __decorate([
  39307. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39308. ], StandardMaterial.prototype, "ambientTexture", void 0);
  39309. __decorate([
  39310. BABYLON.serializeAsTexture("opacityTexture")
  39311. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  39312. __decorate([
  39313. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  39314. ], StandardMaterial.prototype, "opacityTexture", void 0);
  39315. __decorate([
  39316. BABYLON.serializeAsTexture("reflectionTexture")
  39317. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  39318. __decorate([
  39319. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39320. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  39321. __decorate([
  39322. BABYLON.serializeAsTexture("emissiveTexture")
  39323. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  39324. __decorate([
  39325. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39326. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  39327. __decorate([
  39328. BABYLON.serializeAsTexture("specularTexture")
  39329. ], StandardMaterial.prototype, "_specularTexture", void 0);
  39330. __decorate([
  39331. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39332. ], StandardMaterial.prototype, "specularTexture", void 0);
  39333. __decorate([
  39334. BABYLON.serializeAsTexture("bumpTexture")
  39335. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  39336. __decorate([
  39337. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39338. ], StandardMaterial.prototype, "bumpTexture", void 0);
  39339. __decorate([
  39340. BABYLON.serializeAsTexture("lightmapTexture")
  39341. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  39342. __decorate([
  39343. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39344. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  39345. __decorate([
  39346. BABYLON.serializeAsTexture("refractionTexture")
  39347. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  39348. __decorate([
  39349. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39350. ], StandardMaterial.prototype, "refractionTexture", void 0);
  39351. __decorate([
  39352. BABYLON.serializeAsColor3("ambient")
  39353. ], StandardMaterial.prototype, "ambientColor", void 0);
  39354. __decorate([
  39355. BABYLON.serializeAsColor3("diffuse")
  39356. ], StandardMaterial.prototype, "diffuseColor", void 0);
  39357. __decorate([
  39358. BABYLON.serializeAsColor3("specular")
  39359. ], StandardMaterial.prototype, "specularColor", void 0);
  39360. __decorate([
  39361. BABYLON.serializeAsColor3("emissive")
  39362. ], StandardMaterial.prototype, "emissiveColor", void 0);
  39363. __decorate([
  39364. BABYLON.serialize()
  39365. ], StandardMaterial.prototype, "specularPower", void 0);
  39366. __decorate([
  39367. BABYLON.serialize("useAlphaFromDiffuseTexture")
  39368. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  39369. __decorate([
  39370. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39371. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  39372. __decorate([
  39373. BABYLON.serialize("useEmissiveAsIllumination")
  39374. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  39375. __decorate([
  39376. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39377. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  39378. __decorate([
  39379. BABYLON.serialize("linkEmissiveWithDiffuse")
  39380. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  39381. __decorate([
  39382. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39383. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  39384. __decorate([
  39385. BABYLON.serialize("useSpecularOverAlpha")
  39386. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  39387. __decorate([
  39388. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39389. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  39390. __decorate([
  39391. BABYLON.serialize("useReflectionOverAlpha")
  39392. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  39393. __decorate([
  39394. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39395. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  39396. __decorate([
  39397. BABYLON.serialize("disableLighting")
  39398. ], StandardMaterial.prototype, "_disableLighting", void 0);
  39399. __decorate([
  39400. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  39401. ], StandardMaterial.prototype, "disableLighting", void 0);
  39402. __decorate([
  39403. BABYLON.serialize("useParallax")
  39404. ], StandardMaterial.prototype, "_useParallax", void 0);
  39405. __decorate([
  39406. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39407. ], StandardMaterial.prototype, "useParallax", void 0);
  39408. __decorate([
  39409. BABYLON.serialize("useParallaxOcclusion")
  39410. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  39411. __decorate([
  39412. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39413. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  39414. __decorate([
  39415. BABYLON.serialize()
  39416. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  39417. __decorate([
  39418. BABYLON.serialize("roughness")
  39419. ], StandardMaterial.prototype, "_roughness", void 0);
  39420. __decorate([
  39421. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39422. ], StandardMaterial.prototype, "roughness", void 0);
  39423. __decorate([
  39424. BABYLON.serialize()
  39425. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  39426. __decorate([
  39427. BABYLON.serialize()
  39428. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  39429. __decorate([
  39430. BABYLON.serialize("useLightmapAsShadowmap")
  39431. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  39432. __decorate([
  39433. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39434. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  39435. __decorate([
  39436. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  39437. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  39438. __decorate([
  39439. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  39440. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  39441. __decorate([
  39442. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  39443. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  39444. __decorate([
  39445. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  39446. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  39447. __decorate([
  39448. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  39449. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  39450. __decorate([
  39451. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  39452. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  39453. __decorate([
  39454. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  39455. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  39456. __decorate([
  39457. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  39458. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  39459. __decorate([
  39460. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  39461. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  39462. __decorate([
  39463. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  39464. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  39465. __decorate([
  39466. BABYLON.serialize("useReflectionFresnelFromSpecular")
  39467. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  39468. __decorate([
  39469. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  39470. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  39471. __decorate([
  39472. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  39473. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  39474. __decorate([
  39475. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39476. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  39477. __decorate([
  39478. BABYLON.serialize("maxSimultaneousLights")
  39479. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  39480. __decorate([
  39481. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  39482. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  39483. __decorate([
  39484. BABYLON.serialize("invertNormalMapX")
  39485. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  39486. __decorate([
  39487. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39488. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  39489. __decorate([
  39490. BABYLON.serialize("invertNormalMapY")
  39491. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  39492. __decorate([
  39493. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39494. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  39495. __decorate([
  39496. BABYLON.serialize("twoSidedLighting")
  39497. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  39498. __decorate([
  39499. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39500. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  39501. __decorate([
  39502. BABYLON.serialize()
  39503. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  39504. return StandardMaterial;
  39505. }(BABYLON.PushMaterial));
  39506. BABYLON.StandardMaterial = StandardMaterial;
  39507. })(BABYLON || (BABYLON = {}));
  39508. //# sourceMappingURL=babylon.standardMaterial.js.map
  39509. var BABYLON;
  39510. (function (BABYLON) {
  39511. /**
  39512. * Manages the defines for the PBR Material.
  39513. */
  39514. var PBRMaterialDefines = /** @class */ (function (_super) {
  39515. __extends(PBRMaterialDefines, _super);
  39516. /**
  39517. * Initializes the PBR Material defines.
  39518. */
  39519. function PBRMaterialDefines() {
  39520. var _this = _super.call(this) || this;
  39521. _this.PBR = true;
  39522. _this.MAINUV1 = false;
  39523. _this.MAINUV2 = false;
  39524. _this.UV1 = false;
  39525. _this.UV2 = false;
  39526. _this.ALBEDO = false;
  39527. _this.ALBEDODIRECTUV = 0;
  39528. _this.VERTEXCOLOR = false;
  39529. _this.AMBIENT = false;
  39530. _this.AMBIENTDIRECTUV = 0;
  39531. _this.AMBIENTINGRAYSCALE = false;
  39532. _this.OPACITY = false;
  39533. _this.VERTEXALPHA = false;
  39534. _this.OPACITYDIRECTUV = 0;
  39535. _this.OPACITYRGB = false;
  39536. _this.ALPHATEST = false;
  39537. _this.DEPTHPREPASS = false;
  39538. _this.ALPHABLEND = false;
  39539. _this.ALPHAFROMALBEDO = false;
  39540. _this.ALPHATESTVALUE = 0.5;
  39541. _this.SPECULAROVERALPHA = false;
  39542. _this.RADIANCEOVERALPHA = false;
  39543. _this.ALPHAFRESNEL = false;
  39544. _this.LINEARALPHAFRESNEL = false;
  39545. _this.PREMULTIPLYALPHA = false;
  39546. _this.EMISSIVE = false;
  39547. _this.EMISSIVEDIRECTUV = 0;
  39548. _this.REFLECTIVITY = false;
  39549. _this.REFLECTIVITYDIRECTUV = 0;
  39550. _this.SPECULARTERM = false;
  39551. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  39552. _this.MICROSURFACEAUTOMATIC = false;
  39553. _this.LODBASEDMICROSFURACE = false;
  39554. _this.MICROSURFACEMAP = false;
  39555. _this.MICROSURFACEMAPDIRECTUV = 0;
  39556. _this.METALLICWORKFLOW = false;
  39557. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  39558. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  39559. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  39560. _this.AOSTOREINMETALMAPRED = false;
  39561. _this.ENVIRONMENTBRDF = false;
  39562. _this.NORMAL = false;
  39563. _this.TANGENT = false;
  39564. _this.BUMP = false;
  39565. _this.BUMPDIRECTUV = 0;
  39566. _this.PARALLAX = false;
  39567. _this.PARALLAXOCCLUSION = false;
  39568. _this.NORMALXYSCALE = true;
  39569. _this.LIGHTMAP = false;
  39570. _this.LIGHTMAPDIRECTUV = 0;
  39571. _this.USELIGHTMAPASSHADOWMAP = false;
  39572. _this.REFLECTION = false;
  39573. _this.REFLECTIONMAP_3D = false;
  39574. _this.REFLECTIONMAP_SPHERICAL = false;
  39575. _this.REFLECTIONMAP_PLANAR = false;
  39576. _this.REFLECTIONMAP_CUBIC = false;
  39577. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  39578. _this.REFLECTIONMAP_PROJECTION = false;
  39579. _this.REFLECTIONMAP_SKYBOX = false;
  39580. _this.REFLECTIONMAP_EXPLICIT = false;
  39581. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  39582. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  39583. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  39584. _this.INVERTCUBICMAP = false;
  39585. _this.USESPHERICALFROMREFLECTIONMAP = false;
  39586. _this.USESPHERICALINVERTEX = false;
  39587. _this.REFLECTIONMAP_OPPOSITEZ = false;
  39588. _this.LODINREFLECTIONALPHA = false;
  39589. _this.GAMMAREFLECTION = false;
  39590. _this.RADIANCEOCCLUSION = false;
  39591. _this.HORIZONOCCLUSION = false;
  39592. _this.REFRACTION = false;
  39593. _this.REFRACTIONMAP_3D = false;
  39594. _this.REFRACTIONMAP_OPPOSITEZ = false;
  39595. _this.LODINREFRACTIONALPHA = false;
  39596. _this.GAMMAREFRACTION = false;
  39597. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  39598. _this.INSTANCES = false;
  39599. _this.NUM_BONE_INFLUENCERS = 0;
  39600. _this.BonesPerMesh = 0;
  39601. _this.NONUNIFORMSCALING = false;
  39602. _this.MORPHTARGETS = false;
  39603. _this.MORPHTARGETS_NORMAL = false;
  39604. _this.MORPHTARGETS_TANGENT = false;
  39605. _this.NUM_MORPH_INFLUENCERS = 0;
  39606. _this.IMAGEPROCESSING = false;
  39607. _this.VIGNETTE = false;
  39608. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  39609. _this.VIGNETTEBLENDMODEOPAQUE = false;
  39610. _this.TONEMAPPING = false;
  39611. _this.CONTRAST = false;
  39612. _this.COLORCURVES = false;
  39613. _this.COLORGRADING = false;
  39614. _this.COLORGRADING3D = false;
  39615. _this.SAMPLER3DGREENDEPTH = false;
  39616. _this.SAMPLER3DBGRMAP = false;
  39617. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  39618. _this.EXPOSURE = false;
  39619. _this.USEPHYSICALLIGHTFALLOFF = false;
  39620. _this.TWOSIDEDLIGHTING = false;
  39621. _this.SHADOWFLOAT = false;
  39622. _this.CLIPPLANE = false;
  39623. _this.POINTSIZE = false;
  39624. _this.FOG = false;
  39625. _this.LOGARITHMICDEPTH = false;
  39626. _this.FORCENORMALFORWARD = false;
  39627. _this.rebuild();
  39628. return _this;
  39629. }
  39630. /**
  39631. * Resets the PBR Material defines.
  39632. */
  39633. PBRMaterialDefines.prototype.reset = function () {
  39634. _super.prototype.reset.call(this);
  39635. this.ALPHATESTVALUE = 0.5;
  39636. this.PBR = true;
  39637. };
  39638. return PBRMaterialDefines;
  39639. }(BABYLON.MaterialDefines));
  39640. /**
  39641. * The Physically based material base class of BJS.
  39642. *
  39643. * This offers the main features of a standard PBR material.
  39644. * For more information, please refer to the documentation :
  39645. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  39646. */
  39647. var PBRBaseMaterial = /** @class */ (function (_super) {
  39648. __extends(PBRBaseMaterial, _super);
  39649. /**
  39650. * Instantiates a new PBRMaterial instance.
  39651. *
  39652. * @param name The material name
  39653. * @param scene The scene the material will be use in.
  39654. */
  39655. function PBRBaseMaterial(name, scene) {
  39656. var _this = _super.call(this, name, scene) || this;
  39657. /**
  39658. * Intensity of the direct lights e.g. the four lights available in your scene.
  39659. * This impacts both the direct diffuse and specular highlights.
  39660. */
  39661. _this._directIntensity = 1.0;
  39662. /**
  39663. * Intensity of the emissive part of the material.
  39664. * This helps controlling the emissive effect without modifying the emissive color.
  39665. */
  39666. _this._emissiveIntensity = 1.0;
  39667. /**
  39668. * Intensity of the environment e.g. how much the environment will light the object
  39669. * either through harmonics for rough material or through the refelction for shiny ones.
  39670. */
  39671. _this._environmentIntensity = 1.0;
  39672. /**
  39673. * This is a special control allowing the reduction of the specular highlights coming from the
  39674. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  39675. */
  39676. _this._specularIntensity = 1.0;
  39677. /**
  39678. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  39679. */
  39680. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  39681. /**
  39682. * Debug Control allowing disabling the bump map on this material.
  39683. */
  39684. _this._disableBumpMap = false;
  39685. /**
  39686. * AKA Occlusion Texture Intensity in other nomenclature.
  39687. */
  39688. _this._ambientTextureStrength = 1.0;
  39689. /**
  39690. * The color of a material in ambient lighting.
  39691. */
  39692. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  39693. /**
  39694. * AKA Diffuse Color in other nomenclature.
  39695. */
  39696. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  39697. /**
  39698. * AKA Specular Color in other nomenclature.
  39699. */
  39700. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  39701. /**
  39702. * The color applied when light is reflected from a material.
  39703. */
  39704. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  39705. /**
  39706. * The color applied when light is emitted from a material.
  39707. */
  39708. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  39709. /**
  39710. * AKA Glossiness in other nomenclature.
  39711. */
  39712. _this._microSurface = 0.9;
  39713. /**
  39714. * source material index of refraction (IOR)' / 'destination material IOR.
  39715. */
  39716. _this._indexOfRefraction = 0.66;
  39717. /**
  39718. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  39719. */
  39720. _this._invertRefractionY = false;
  39721. /**
  39722. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  39723. * Materials half opaque for instance using refraction could benefit from this control.
  39724. */
  39725. _this._linkRefractionWithTransparency = false;
  39726. /**
  39727. * Specifies that the material will use the light map as a show map.
  39728. */
  39729. _this._useLightmapAsShadowmap = false;
  39730. /**
  39731. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  39732. * makes the reflect vector face the model (under horizon).
  39733. */
  39734. _this._useHorizonOcclusion = true;
  39735. /**
  39736. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  39737. * too much the area relying on ambient texture to define their ambient occlusion.
  39738. */
  39739. _this._useRadianceOcclusion = true;
  39740. /**
  39741. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  39742. */
  39743. _this._useAlphaFromAlbedoTexture = false;
  39744. /**
  39745. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  39746. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  39747. */
  39748. _this._useSpecularOverAlpha = true;
  39749. /**
  39750. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  39751. */
  39752. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  39753. /**
  39754. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  39755. */
  39756. _this._useRoughnessFromMetallicTextureAlpha = true;
  39757. /**
  39758. * Specifies if the metallic texture contains the roughness information in its green channel.
  39759. */
  39760. _this._useRoughnessFromMetallicTextureGreen = false;
  39761. /**
  39762. * Specifies if the metallic texture contains the metallness information in its blue channel.
  39763. */
  39764. _this._useMetallnessFromMetallicTextureBlue = false;
  39765. /**
  39766. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  39767. */
  39768. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  39769. /**
  39770. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  39771. */
  39772. _this._useAmbientInGrayScale = false;
  39773. /**
  39774. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  39775. * The material will try to infer what glossiness each pixel should be.
  39776. */
  39777. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  39778. /**
  39779. * BJS is using an harcoded light falloff based on a manually sets up range.
  39780. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  39781. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  39782. */
  39783. _this._usePhysicalLightFalloff = true;
  39784. /**
  39785. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  39786. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  39787. */
  39788. _this._useRadianceOverAlpha = true;
  39789. /**
  39790. * Allows using the bump map in parallax mode.
  39791. */
  39792. _this._useParallax = false;
  39793. /**
  39794. * Allows using the bump map in parallax occlusion mode.
  39795. */
  39796. _this._useParallaxOcclusion = false;
  39797. /**
  39798. * Controls the scale bias of the parallax mode.
  39799. */
  39800. _this._parallaxScaleBias = 0.05;
  39801. /**
  39802. * If sets to true, disables all the lights affecting the material.
  39803. */
  39804. _this._disableLighting = false;
  39805. /**
  39806. * Number of Simultaneous lights allowed on the material.
  39807. */
  39808. _this._maxSimultaneousLights = 4;
  39809. /**
  39810. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  39811. */
  39812. _this._invertNormalMapX = false;
  39813. /**
  39814. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  39815. */
  39816. _this._invertNormalMapY = false;
  39817. /**
  39818. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  39819. */
  39820. _this._twoSidedLighting = false;
  39821. /**
  39822. * Defines the alpha limits in alpha test mode.
  39823. */
  39824. _this._alphaCutOff = 0.4;
  39825. /**
  39826. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  39827. */
  39828. _this._forceAlphaTest = false;
  39829. /**
  39830. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  39831. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  39832. */
  39833. _this._useAlphaFresnel = false;
  39834. /**
  39835. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  39836. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  39837. */
  39838. _this._useLinearAlphaFresnel = false;
  39839. /**
  39840. * The transparency mode of the material.
  39841. */
  39842. _this._transparencyMode = null;
  39843. /**
  39844. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  39845. * from cos thetav and roughness:
  39846. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  39847. */
  39848. _this._environmentBRDFTexture = null;
  39849. /**
  39850. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  39851. */
  39852. _this._forceIrradianceInFragment = false;
  39853. /**
  39854. * Force normal to face away from face.
  39855. */
  39856. _this._forceNormalForward = false;
  39857. /**
  39858. * Force metallic workflow.
  39859. */
  39860. _this._forceMetallicWorkflow = false;
  39861. /**
  39862. * Stores the available render targets.
  39863. */
  39864. _this._renderTargets = new BABYLON.SmartArray(16);
  39865. /**
  39866. * Sets the global ambient color for the material used in lighting calculations.
  39867. */
  39868. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  39869. // Setup the default processing configuration to the scene.
  39870. _this._attachImageProcessingConfiguration(null);
  39871. _this.getRenderTargetTextures = function () {
  39872. _this._renderTargets.reset();
  39873. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  39874. _this._renderTargets.push(_this._reflectionTexture);
  39875. }
  39876. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  39877. _this._renderTargets.push(_this._refractionTexture);
  39878. }
  39879. return _this._renderTargets;
  39880. };
  39881. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  39882. return _this;
  39883. }
  39884. /**
  39885. * Attaches a new image processing configuration to the PBR Material.
  39886. * @param configuration
  39887. */
  39888. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  39889. var _this = this;
  39890. if (configuration === this._imageProcessingConfiguration) {
  39891. return;
  39892. }
  39893. // Detaches observer.
  39894. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  39895. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  39896. }
  39897. // Pick the scene configuration if needed.
  39898. if (!configuration) {
  39899. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  39900. }
  39901. else {
  39902. this._imageProcessingConfiguration = configuration;
  39903. }
  39904. // Attaches observer.
  39905. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  39906. _this._markAllSubMeshesAsImageProcessingDirty();
  39907. });
  39908. };
  39909. /**
  39910. * Gets the name of the material class.
  39911. */
  39912. PBRBaseMaterial.prototype.getClassName = function () {
  39913. return "PBRBaseMaterial";
  39914. };
  39915. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  39916. /**
  39917. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  39918. */
  39919. get: function () {
  39920. return this._useLogarithmicDepth;
  39921. },
  39922. /**
  39923. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  39924. */
  39925. set: function (value) {
  39926. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  39927. },
  39928. enumerable: true,
  39929. configurable: true
  39930. });
  39931. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  39932. /**
  39933. * Gets the current transparency mode.
  39934. */
  39935. get: function () {
  39936. return this._transparencyMode;
  39937. },
  39938. /**
  39939. * Sets the transparency mode of the material.
  39940. */
  39941. set: function (value) {
  39942. if (this._transparencyMode === value) {
  39943. return;
  39944. }
  39945. this._transparencyMode = value;
  39946. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  39947. this._markAllSubMeshesAsTexturesAndMiscDirty();
  39948. },
  39949. enumerable: true,
  39950. configurable: true
  39951. });
  39952. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  39953. /**
  39954. * Returns true if alpha blending should be disabled.
  39955. */
  39956. get: function () {
  39957. return (this._linkRefractionWithTransparency ||
  39958. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  39959. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  39960. },
  39961. enumerable: true,
  39962. configurable: true
  39963. });
  39964. /**
  39965. * Specifies whether or not this material should be rendered in alpha blend mode.
  39966. */
  39967. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  39968. if (this._disableAlphaBlending) {
  39969. return false;
  39970. }
  39971. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  39972. };
  39973. /**
  39974. * Specifies if the mesh will require alpha blending.
  39975. * @param mesh - BJS mesh.
  39976. */
  39977. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  39978. if (this._disableAlphaBlending) {
  39979. return false;
  39980. }
  39981. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  39982. };
  39983. /**
  39984. * Specifies whether or not this material should be rendered in alpha test mode.
  39985. */
  39986. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  39987. if (this._forceAlphaTest) {
  39988. return true;
  39989. }
  39990. if (this._linkRefractionWithTransparency) {
  39991. return false;
  39992. }
  39993. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  39994. };
  39995. /**
  39996. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  39997. */
  39998. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  39999. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  40000. };
  40001. /**
  40002. * Gets the texture used for the alpha test.
  40003. */
  40004. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  40005. return this._albedoTexture;
  40006. };
  40007. /**
  40008. * Specifies that the submesh is ready to be used.
  40009. * @param mesh - BJS mesh.
  40010. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  40011. * @param useInstances - Specifies that instances should be used.
  40012. * @returns - boolean indicating that the submesh is ready or not.
  40013. */
  40014. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  40015. if (subMesh.effect && this.isFrozen) {
  40016. if (this._wasPreviouslyReady) {
  40017. return true;
  40018. }
  40019. }
  40020. if (!subMesh._materialDefines) {
  40021. subMesh._materialDefines = new PBRMaterialDefines();
  40022. }
  40023. var defines = subMesh._materialDefines;
  40024. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  40025. if (defines._renderId === this.getScene().getRenderId()) {
  40026. return true;
  40027. }
  40028. }
  40029. var scene = this.getScene();
  40030. var engine = scene.getEngine();
  40031. if (defines._areTexturesDirty) {
  40032. if (scene.texturesEnabled) {
  40033. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  40034. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  40035. return false;
  40036. }
  40037. }
  40038. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  40039. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  40040. return false;
  40041. }
  40042. }
  40043. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  40044. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  40045. return false;
  40046. }
  40047. }
  40048. var reflectionTexture = this._getReflectionTexture();
  40049. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  40050. if (!reflectionTexture.isReadyOrNotBlocking()) {
  40051. return false;
  40052. }
  40053. }
  40054. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  40055. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  40056. return false;
  40057. }
  40058. }
  40059. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  40060. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  40061. return false;
  40062. }
  40063. }
  40064. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  40065. if (this._metallicTexture) {
  40066. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  40067. return false;
  40068. }
  40069. }
  40070. else if (this._reflectivityTexture) {
  40071. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  40072. return false;
  40073. }
  40074. }
  40075. if (this._microSurfaceTexture) {
  40076. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  40077. return false;
  40078. }
  40079. }
  40080. }
  40081. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  40082. // Bump texture cannot be not blocking.
  40083. if (!this._bumpTexture.isReady()) {
  40084. return false;
  40085. }
  40086. }
  40087. var refractionTexture = this._getRefractionTexture();
  40088. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  40089. if (!refractionTexture.isReadyOrNotBlocking()) {
  40090. return false;
  40091. }
  40092. }
  40093. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  40094. // This is blocking.
  40095. if (!this._environmentBRDFTexture.isReady()) {
  40096. return false;
  40097. }
  40098. }
  40099. }
  40100. }
  40101. if (defines._areImageProcessingDirty) {
  40102. if (!this._imageProcessingConfiguration.isReady()) {
  40103. return false;
  40104. }
  40105. }
  40106. if (!engine.getCaps().standardDerivatives) {
  40107. var bufferMesh = null;
  40108. if (mesh.getClassName() === "InstancedMesh") {
  40109. bufferMesh = mesh.sourceMesh;
  40110. }
  40111. else if (mesh.getClassName() === "Mesh") {
  40112. bufferMesh = mesh;
  40113. }
  40114. if (bufferMesh && bufferMesh.geometry && bufferMesh.geometry.isReady() && !bufferMesh.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  40115. bufferMesh.createNormals(true);
  40116. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + bufferMesh.name);
  40117. }
  40118. }
  40119. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  40120. if (effect) {
  40121. scene.resetCachedMaterial();
  40122. subMesh.setEffect(effect, defines);
  40123. this.buildUniformLayout();
  40124. }
  40125. if (!subMesh.effect || !subMesh.effect.isReady()) {
  40126. return false;
  40127. }
  40128. defines._renderId = scene.getRenderId();
  40129. this._wasPreviouslyReady = true;
  40130. return true;
  40131. };
  40132. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  40133. if (onCompiled === void 0) { onCompiled = null; }
  40134. if (onError === void 0) { onError = null; }
  40135. if (useInstances === void 0) { useInstances = null; }
  40136. if (useClipPlane === void 0) { useClipPlane = null; }
  40137. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  40138. if (!defines.isDirty) {
  40139. return null;
  40140. }
  40141. defines.markAsProcessed();
  40142. var scene = this.getScene();
  40143. var engine = scene.getEngine();
  40144. // Fallbacks
  40145. var fallbacks = new BABYLON.EffectFallbacks();
  40146. var fallbackRank = 0;
  40147. if (defines.USESPHERICALINVERTEX) {
  40148. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  40149. }
  40150. if (defines.FOG) {
  40151. fallbacks.addFallback(fallbackRank, "FOG");
  40152. }
  40153. if (defines.POINTSIZE) {
  40154. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  40155. }
  40156. if (defines.LOGARITHMICDEPTH) {
  40157. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  40158. }
  40159. if (defines.PARALLAX) {
  40160. fallbacks.addFallback(fallbackRank, "PARALLAX");
  40161. }
  40162. if (defines.PARALLAXOCCLUSION) {
  40163. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  40164. }
  40165. if (defines.ENVIRONMENTBRDF) {
  40166. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  40167. }
  40168. if (defines.TANGENT) {
  40169. fallbacks.addFallback(fallbackRank++, "TANGENT");
  40170. }
  40171. if (defines.BUMP) {
  40172. fallbacks.addFallback(fallbackRank++, "BUMP");
  40173. }
  40174. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  40175. if (defines.SPECULARTERM) {
  40176. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  40177. }
  40178. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  40179. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  40180. }
  40181. if (defines.LIGHTMAP) {
  40182. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  40183. }
  40184. if (defines.NORMAL) {
  40185. fallbacks.addFallback(fallbackRank++, "NORMAL");
  40186. }
  40187. if (defines.AMBIENT) {
  40188. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  40189. }
  40190. if (defines.EMISSIVE) {
  40191. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  40192. }
  40193. if (defines.VERTEXCOLOR) {
  40194. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  40195. }
  40196. if (defines.NUM_BONE_INFLUENCERS > 0) {
  40197. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  40198. }
  40199. if (defines.MORPHTARGETS) {
  40200. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  40201. }
  40202. //Attributes
  40203. var attribs = [BABYLON.VertexBuffer.PositionKind];
  40204. if (defines.NORMAL) {
  40205. attribs.push(BABYLON.VertexBuffer.NormalKind);
  40206. }
  40207. if (defines.TANGENT) {
  40208. attribs.push(BABYLON.VertexBuffer.TangentKind);
  40209. }
  40210. if (defines.UV1) {
  40211. attribs.push(BABYLON.VertexBuffer.UVKind);
  40212. }
  40213. if (defines.UV2) {
  40214. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  40215. }
  40216. if (defines.VERTEXCOLOR) {
  40217. attribs.push(BABYLON.VertexBuffer.ColorKind);
  40218. }
  40219. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  40220. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  40221. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  40222. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  40223. "vFogInfos", "vFogColor", "pointSize",
  40224. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  40225. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  40226. "mBones",
  40227. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  40228. "vLightingIntensity",
  40229. "logarithmicDepthConstant",
  40230. "vSphericalX", "vSphericalY", "vSphericalZ",
  40231. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  40232. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  40233. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  40234. "vTangentSpaceParams"
  40235. ];
  40236. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  40237. "bumpSampler", "lightmapSampler", "opacitySampler",
  40238. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  40239. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  40240. "microSurfaceSampler", "environmentBrdfSampler"];
  40241. var uniformBuffers = ["Material", "Scene"];
  40242. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  40243. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  40244. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  40245. uniformsNames: uniforms,
  40246. uniformBuffersNames: uniformBuffers,
  40247. samplers: samplers,
  40248. defines: defines,
  40249. maxSimultaneousLights: this._maxSimultaneousLights
  40250. });
  40251. var join = defines.toString();
  40252. return engine.createEffect("pbr", {
  40253. attributes: attribs,
  40254. uniformsNames: uniforms,
  40255. uniformBuffersNames: uniformBuffers,
  40256. samplers: samplers,
  40257. defines: join,
  40258. fallbacks: fallbacks,
  40259. onCompiled: onCompiled,
  40260. onError: onError,
  40261. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  40262. }, engine);
  40263. };
  40264. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  40265. if (useInstances === void 0) { useInstances = null; }
  40266. if (useClipPlane === void 0) { useClipPlane = null; }
  40267. var scene = this.getScene();
  40268. var engine = scene.getEngine();
  40269. // Lights
  40270. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  40271. defines._needNormals = true;
  40272. // Textures
  40273. if (defines._areTexturesDirty) {
  40274. defines._needUVs = false;
  40275. if (scene.texturesEnabled) {
  40276. if (scene.getEngine().getCaps().textureLOD) {
  40277. defines.LODBASEDMICROSFURACE = true;
  40278. }
  40279. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  40280. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  40281. }
  40282. else {
  40283. defines.ALBEDO = false;
  40284. }
  40285. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  40286. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  40287. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  40288. }
  40289. else {
  40290. defines.AMBIENT = false;
  40291. }
  40292. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  40293. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  40294. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  40295. }
  40296. else {
  40297. defines.OPACITY = false;
  40298. }
  40299. var reflectionTexture = this._getReflectionTexture();
  40300. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  40301. defines.REFLECTION = true;
  40302. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  40303. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  40304. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  40305. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  40306. defines.INVERTCUBICMAP = true;
  40307. }
  40308. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  40309. switch (reflectionTexture.coordinatesMode) {
  40310. case BABYLON.Texture.CUBIC_MODE:
  40311. case BABYLON.Texture.INVCUBIC_MODE:
  40312. defines.REFLECTIONMAP_CUBIC = true;
  40313. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  40314. break;
  40315. case BABYLON.Texture.EXPLICIT_MODE:
  40316. defines.REFLECTIONMAP_EXPLICIT = true;
  40317. break;
  40318. case BABYLON.Texture.PLANAR_MODE:
  40319. defines.REFLECTIONMAP_PLANAR = true;
  40320. break;
  40321. case BABYLON.Texture.PROJECTION_MODE:
  40322. defines.REFLECTIONMAP_PROJECTION = true;
  40323. break;
  40324. case BABYLON.Texture.SKYBOX_MODE:
  40325. defines.REFLECTIONMAP_SKYBOX = true;
  40326. break;
  40327. case BABYLON.Texture.SPHERICAL_MODE:
  40328. defines.REFLECTIONMAP_SPHERICAL = true;
  40329. break;
  40330. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  40331. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  40332. break;
  40333. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  40334. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  40335. break;
  40336. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  40337. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  40338. break;
  40339. }
  40340. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  40341. if (reflectionTexture.sphericalPolynomial) {
  40342. defines.USESPHERICALFROMREFLECTIONMAP = true;
  40343. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  40344. defines.USESPHERICALINVERTEX = false;
  40345. }
  40346. else {
  40347. defines.USESPHERICALINVERTEX = true;
  40348. }
  40349. }
  40350. }
  40351. }
  40352. else {
  40353. defines.REFLECTION = false;
  40354. defines.REFLECTIONMAP_3D = false;
  40355. defines.REFLECTIONMAP_SPHERICAL = false;
  40356. defines.REFLECTIONMAP_PLANAR = false;
  40357. defines.REFLECTIONMAP_CUBIC = false;
  40358. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  40359. defines.REFLECTIONMAP_PROJECTION = false;
  40360. defines.REFLECTIONMAP_SKYBOX = false;
  40361. defines.REFLECTIONMAP_EXPLICIT = false;
  40362. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  40363. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  40364. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  40365. defines.INVERTCUBICMAP = false;
  40366. defines.USESPHERICALFROMREFLECTIONMAP = false;
  40367. defines.USESPHERICALINVERTEX = false;
  40368. defines.REFLECTIONMAP_OPPOSITEZ = false;
  40369. defines.LODINREFLECTIONALPHA = false;
  40370. defines.GAMMAREFLECTION = false;
  40371. }
  40372. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  40373. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  40374. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  40375. }
  40376. else {
  40377. defines.LIGHTMAP = false;
  40378. }
  40379. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  40380. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  40381. }
  40382. else {
  40383. defines.EMISSIVE = false;
  40384. }
  40385. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  40386. if (this._metallicTexture) {
  40387. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  40388. defines.METALLICWORKFLOW = true;
  40389. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  40390. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  40391. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  40392. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  40393. }
  40394. else if (this._reflectivityTexture) {
  40395. defines.METALLICWORKFLOW = false;
  40396. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  40397. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  40398. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  40399. }
  40400. else {
  40401. defines.METALLICWORKFLOW = false;
  40402. defines.REFLECTIVITY = false;
  40403. }
  40404. if (this._microSurfaceTexture) {
  40405. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  40406. }
  40407. else {
  40408. defines.MICROSURFACEMAP = false;
  40409. }
  40410. }
  40411. else {
  40412. defines.REFLECTIVITY = false;
  40413. defines.MICROSURFACEMAP = false;
  40414. }
  40415. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  40416. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  40417. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  40418. defines.PARALLAX = true;
  40419. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  40420. }
  40421. else {
  40422. defines.PARALLAX = false;
  40423. }
  40424. }
  40425. else {
  40426. defines.BUMP = false;
  40427. }
  40428. var refractionTexture = this._getRefractionTexture();
  40429. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  40430. defines.REFRACTION = true;
  40431. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  40432. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  40433. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  40434. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  40435. if (this._linkRefractionWithTransparency) {
  40436. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  40437. }
  40438. }
  40439. else {
  40440. defines.REFRACTION = false;
  40441. }
  40442. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  40443. defines.ENVIRONMENTBRDF = true;
  40444. }
  40445. else {
  40446. defines.ENVIRONMENTBRDF = false;
  40447. }
  40448. if (this._shouldUseAlphaFromAlbedoTexture()) {
  40449. defines.ALPHAFROMALBEDO = true;
  40450. }
  40451. else {
  40452. defines.ALPHAFROMALBEDO = false;
  40453. }
  40454. }
  40455. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  40456. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  40457. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  40458. if (this._forceMetallicWorkflow || (this._metallic !== undefined && this._metallic !== null) || (this._roughness !== undefined && this._roughness !== null)) {
  40459. defines.METALLICWORKFLOW = true;
  40460. }
  40461. else {
  40462. defines.METALLICWORKFLOW = false;
  40463. }
  40464. if (!this.backFaceCulling && this._twoSidedLighting) {
  40465. defines.TWOSIDEDLIGHTING = true;
  40466. }
  40467. else {
  40468. defines.TWOSIDEDLIGHTING = false;
  40469. }
  40470. defines.ALPHATESTVALUE = this._alphaCutOff;
  40471. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  40472. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  40473. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  40474. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  40475. }
  40476. if (defines._areImageProcessingDirty) {
  40477. this._imageProcessingConfiguration.prepareDefines(defines);
  40478. }
  40479. defines.FORCENORMALFORWARD = this._forceNormalForward;
  40480. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  40481. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  40482. // Misc.
  40483. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  40484. // Values that need to be evaluated on every frame
  40485. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  40486. // Attribs
  40487. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  40488. };
  40489. /**
  40490. * Force shader compilation
  40491. */
  40492. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  40493. var _this = this;
  40494. var localOptions = __assign({ clipPlane: false }, options);
  40495. var defines = new PBRMaterialDefines();
  40496. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  40497. if (effect.isReady()) {
  40498. if (onCompiled) {
  40499. onCompiled(this);
  40500. }
  40501. }
  40502. else {
  40503. effect.onCompileObservable.add(function () {
  40504. if (onCompiled) {
  40505. onCompiled(_this);
  40506. }
  40507. });
  40508. }
  40509. };
  40510. /**
  40511. * Initializes the uniform buffer layout for the shader.
  40512. */
  40513. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  40514. // Order is important !
  40515. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  40516. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  40517. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  40518. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  40519. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  40520. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  40521. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  40522. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  40523. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  40524. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  40525. this._uniformBuffer.addUniform("vReflectionSize", 3);
  40526. this._uniformBuffer.addUniform("vBumpInfos", 3);
  40527. this._uniformBuffer.addUniform("albedoMatrix", 16);
  40528. this._uniformBuffer.addUniform("ambientMatrix", 16);
  40529. this._uniformBuffer.addUniform("opacityMatrix", 16);
  40530. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  40531. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  40532. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  40533. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  40534. this._uniformBuffer.addUniform("bumpMatrix", 16);
  40535. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  40536. this._uniformBuffer.addUniform("refractionMatrix", 16);
  40537. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  40538. this._uniformBuffer.addUniform("vReflectionColor", 3);
  40539. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  40540. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  40541. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  40542. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  40543. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  40544. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  40545. this._uniformBuffer.addUniform("pointSize", 1);
  40546. this._uniformBuffer.create();
  40547. };
  40548. /**
  40549. * Unbinds the textures.
  40550. */
  40551. PBRBaseMaterial.prototype.unbind = function () {
  40552. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  40553. this._uniformBuffer.setTexture("reflectionSampler", null);
  40554. }
  40555. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  40556. this._uniformBuffer.setTexture("refractionSampler", null);
  40557. }
  40558. _super.prototype.unbind.call(this);
  40559. };
  40560. /**
  40561. * Binds to the world matrix.
  40562. * @param world - The world matrix.
  40563. */
  40564. PBRBaseMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  40565. this._activeEffect.setMatrix("world", world);
  40566. };
  40567. /**
  40568. * Binds the submesh data.
  40569. * @param world - The world matrix.
  40570. * @param mesh - The BJS mesh.
  40571. * @param subMesh - A submesh of the BJS mesh.
  40572. */
  40573. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  40574. var scene = this.getScene();
  40575. var defines = subMesh._materialDefines;
  40576. if (!defines) {
  40577. return;
  40578. }
  40579. var effect = subMesh.effect;
  40580. if (!effect) {
  40581. return;
  40582. }
  40583. this._activeEffect = effect;
  40584. // Matrices
  40585. this.bindOnlyWorldMatrix(world);
  40586. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  40587. // Bones
  40588. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  40589. var reflectionTexture = null;
  40590. if (mustRebind) {
  40591. this._uniformBuffer.bindToEffect(effect, "Material");
  40592. this.bindViewProjection(effect);
  40593. reflectionTexture = this._getReflectionTexture();
  40594. var refractionTexture = this._getRefractionTexture();
  40595. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  40596. // Texture uniforms
  40597. if (scene.texturesEnabled) {
  40598. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  40599. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  40600. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  40601. }
  40602. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  40603. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  40604. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  40605. }
  40606. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  40607. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  40608. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  40609. }
  40610. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  40611. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  40612. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  40613. if (reflectionTexture.boundingBoxSize) {
  40614. var cubeTexture = reflectionTexture;
  40615. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  40616. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  40617. }
  40618. var polynomials = reflectionTexture.sphericalPolynomial;
  40619. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  40620. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  40621. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  40622. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  40623. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  40624. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  40625. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  40626. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  40627. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  40628. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  40629. }
  40630. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  40631. }
  40632. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  40633. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  40634. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  40635. }
  40636. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  40637. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  40638. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  40639. }
  40640. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  40641. if (this._metallicTexture) {
  40642. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  40643. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  40644. }
  40645. else if (this._reflectivityTexture) {
  40646. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  40647. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  40648. }
  40649. if (this._microSurfaceTexture) {
  40650. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  40651. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  40652. }
  40653. }
  40654. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  40655. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  40656. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  40657. if (scene._mirroredCameraPosition) {
  40658. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  40659. }
  40660. else {
  40661. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  40662. }
  40663. }
  40664. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  40665. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  40666. var depth = 1.0;
  40667. if (!refractionTexture.isCube) {
  40668. if (refractionTexture.depth) {
  40669. depth = refractionTexture.depth;
  40670. }
  40671. }
  40672. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  40673. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  40674. }
  40675. }
  40676. // Point size
  40677. if (this.pointsCloud) {
  40678. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  40679. }
  40680. // Colors
  40681. if (defines.METALLICWORKFLOW) {
  40682. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  40683. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  40684. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  40685. }
  40686. else {
  40687. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  40688. }
  40689. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  40690. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  40691. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  40692. // Misc
  40693. this._lightingInfos.x = this._directIntensity;
  40694. this._lightingInfos.y = this._emissiveIntensity;
  40695. this._lightingInfos.z = this._environmentIntensity;
  40696. this._lightingInfos.w = this._specularIntensity;
  40697. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  40698. }
  40699. // Textures
  40700. if (scene.texturesEnabled) {
  40701. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  40702. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  40703. }
  40704. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  40705. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  40706. }
  40707. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  40708. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  40709. }
  40710. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  40711. if (defines.LODBASEDMICROSFURACE) {
  40712. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  40713. }
  40714. else {
  40715. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  40716. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  40717. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  40718. }
  40719. }
  40720. if (defines.ENVIRONMENTBRDF) {
  40721. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  40722. }
  40723. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  40724. if (defines.LODBASEDMICROSFURACE) {
  40725. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  40726. }
  40727. else {
  40728. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  40729. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  40730. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  40731. }
  40732. }
  40733. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  40734. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  40735. }
  40736. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  40737. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  40738. }
  40739. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  40740. if (this._metallicTexture) {
  40741. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  40742. }
  40743. else if (this._reflectivityTexture) {
  40744. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  40745. }
  40746. if (this._microSurfaceTexture) {
  40747. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  40748. }
  40749. }
  40750. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  40751. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  40752. }
  40753. }
  40754. // Clip plane
  40755. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  40756. // Colors
  40757. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  40758. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  40759. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  40760. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  40761. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  40762. }
  40763. if (mustRebind || !this.isFrozen) {
  40764. // Lights
  40765. if (scene.lightsEnabled && !this._disableLighting) {
  40766. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  40767. }
  40768. // View
  40769. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  40770. this.bindView(effect);
  40771. }
  40772. // Fog
  40773. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  40774. // Morph targets
  40775. if (defines.NUM_MORPH_INFLUENCERS) {
  40776. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  40777. }
  40778. // image processing
  40779. this._imageProcessingConfiguration.bind(this._activeEffect);
  40780. // Log. depth
  40781. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  40782. }
  40783. this._uniformBuffer.update();
  40784. this._afterBind(mesh);
  40785. };
  40786. /**
  40787. * Returns the animatable textures.
  40788. * @returns - Array of animatable textures.
  40789. */
  40790. PBRBaseMaterial.prototype.getAnimatables = function () {
  40791. var results = [];
  40792. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  40793. results.push(this._albedoTexture);
  40794. }
  40795. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  40796. results.push(this._ambientTexture);
  40797. }
  40798. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  40799. results.push(this._opacityTexture);
  40800. }
  40801. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  40802. results.push(this._reflectionTexture);
  40803. }
  40804. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  40805. results.push(this._emissiveTexture);
  40806. }
  40807. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  40808. results.push(this._metallicTexture);
  40809. }
  40810. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  40811. results.push(this._reflectivityTexture);
  40812. }
  40813. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  40814. results.push(this._bumpTexture);
  40815. }
  40816. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  40817. results.push(this._lightmapTexture);
  40818. }
  40819. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  40820. results.push(this._refractionTexture);
  40821. }
  40822. return results;
  40823. };
  40824. /**
  40825. * Returns the texture used for reflections.
  40826. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  40827. */
  40828. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  40829. if (this._reflectionTexture) {
  40830. return this._reflectionTexture;
  40831. }
  40832. return this.getScene().environmentTexture;
  40833. };
  40834. /**
  40835. * Returns the texture used for refraction or null if none is used.
  40836. * @returns - Refection texture if present. If no refraction texture and refraction
  40837. * is linked with transparency, returns environment texture. Otherwise, returns null.
  40838. */
  40839. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  40840. if (this._refractionTexture) {
  40841. return this._refractionTexture;
  40842. }
  40843. if (this._linkRefractionWithTransparency) {
  40844. return this.getScene().environmentTexture;
  40845. }
  40846. return null;
  40847. };
  40848. /**
  40849. * Disposes the resources of the material.
  40850. * @param forceDisposeEffect - Forces the disposal of effects.
  40851. * @param forceDisposeTextures - Forces the disposal of all textures.
  40852. */
  40853. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  40854. if (forceDisposeTextures) {
  40855. if (this._albedoTexture) {
  40856. this._albedoTexture.dispose();
  40857. }
  40858. if (this._ambientTexture) {
  40859. this._ambientTexture.dispose();
  40860. }
  40861. if (this._opacityTexture) {
  40862. this._opacityTexture.dispose();
  40863. }
  40864. if (this._reflectionTexture) {
  40865. this._reflectionTexture.dispose();
  40866. }
  40867. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  40868. this._environmentBRDFTexture.dispose();
  40869. }
  40870. if (this._emissiveTexture) {
  40871. this._emissiveTexture.dispose();
  40872. }
  40873. if (this._metallicTexture) {
  40874. this._metallicTexture.dispose();
  40875. }
  40876. if (this._reflectivityTexture) {
  40877. this._reflectivityTexture.dispose();
  40878. }
  40879. if (this._bumpTexture) {
  40880. this._bumpTexture.dispose();
  40881. }
  40882. if (this._lightmapTexture) {
  40883. this._lightmapTexture.dispose();
  40884. }
  40885. if (this._refractionTexture) {
  40886. this._refractionTexture.dispose();
  40887. }
  40888. }
  40889. this._renderTargets.dispose();
  40890. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  40891. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  40892. }
  40893. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  40894. };
  40895. /**
  40896. * Stores the reflectivity values based on metallic roughness workflow.
  40897. */
  40898. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  40899. __decorate([
  40900. BABYLON.serializeAsImageProcessingConfiguration()
  40901. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  40902. __decorate([
  40903. BABYLON.serialize()
  40904. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  40905. __decorate([
  40906. BABYLON.serialize()
  40907. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  40908. return PBRBaseMaterial;
  40909. }(BABYLON.PushMaterial));
  40910. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  40911. })(BABYLON || (BABYLON = {}));
  40912. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  40913. var BABYLON;
  40914. (function (BABYLON) {
  40915. /**
  40916. * The Physically based simple base material of BJS.
  40917. *
  40918. * This enables better naming and convention enforcements on top of the pbrMaterial.
  40919. * It is used as the base class for both the specGloss and metalRough conventions.
  40920. */
  40921. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  40922. __extends(PBRBaseSimpleMaterial, _super);
  40923. /**
  40924. * Instantiates a new PBRMaterial instance.
  40925. *
  40926. * @param name The material name
  40927. * @param scene The scene the material will be use in.
  40928. */
  40929. function PBRBaseSimpleMaterial(name, scene) {
  40930. var _this = _super.call(this, name, scene) || this;
  40931. /**
  40932. * Number of Simultaneous lights allowed on the material.
  40933. */
  40934. _this.maxSimultaneousLights = 4;
  40935. /**
  40936. * If sets to true, disables all the lights affecting the material.
  40937. */
  40938. _this.disableLighting = false;
  40939. /**
  40940. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  40941. */
  40942. _this.invertNormalMapX = false;
  40943. /**
  40944. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  40945. */
  40946. _this.invertNormalMapY = false;
  40947. /**
  40948. * Emissivie color used to self-illuminate the model.
  40949. */
  40950. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  40951. /**
  40952. * Occlusion Channel Strenght.
  40953. */
  40954. _this.occlusionStrength = 1.0;
  40955. _this.useLightmapAsShadowmap = false;
  40956. _this._useAlphaFromAlbedoTexture = true;
  40957. _this._useAmbientInGrayScale = true;
  40958. return _this;
  40959. }
  40960. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  40961. /**
  40962. * Gets the current double sided mode.
  40963. */
  40964. get: function () {
  40965. return this._twoSidedLighting;
  40966. },
  40967. /**
  40968. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  40969. */
  40970. set: function (value) {
  40971. if (this._twoSidedLighting === value) {
  40972. return;
  40973. }
  40974. this._twoSidedLighting = value;
  40975. this.backFaceCulling = !value;
  40976. this._markAllSubMeshesAsTexturesDirty();
  40977. },
  40978. enumerable: true,
  40979. configurable: true
  40980. });
  40981. /**
  40982. * Return the active textures of the material.
  40983. */
  40984. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  40985. var activeTextures = _super.prototype.getActiveTextures.call(this);
  40986. if (this.environmentTexture) {
  40987. activeTextures.push(this.environmentTexture);
  40988. }
  40989. if (this.normalTexture) {
  40990. activeTextures.push(this.normalTexture);
  40991. }
  40992. if (this.emissiveTexture) {
  40993. activeTextures.push(this.emissiveTexture);
  40994. }
  40995. if (this.occlusionTexture) {
  40996. activeTextures.push(this.occlusionTexture);
  40997. }
  40998. if (this.lightmapTexture) {
  40999. activeTextures.push(this.lightmapTexture);
  41000. }
  41001. return activeTextures;
  41002. };
  41003. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  41004. if (_super.prototype.hasTexture.call(this, texture)) {
  41005. return true;
  41006. }
  41007. if (this.lightmapTexture === texture) {
  41008. return true;
  41009. }
  41010. return false;
  41011. };
  41012. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  41013. return "PBRBaseSimpleMaterial";
  41014. };
  41015. __decorate([
  41016. BABYLON.serialize(),
  41017. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  41018. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  41019. __decorate([
  41020. BABYLON.serialize(),
  41021. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  41022. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  41023. __decorate([
  41024. BABYLON.serializeAsTexture(),
  41025. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  41026. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  41027. __decorate([
  41028. BABYLON.serialize(),
  41029. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41030. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  41031. __decorate([
  41032. BABYLON.serialize(),
  41033. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41034. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  41035. __decorate([
  41036. BABYLON.serializeAsTexture(),
  41037. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  41038. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  41039. __decorate([
  41040. BABYLON.serializeAsColor3("emissive"),
  41041. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41042. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  41043. __decorate([
  41044. BABYLON.serializeAsTexture(),
  41045. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41046. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  41047. __decorate([
  41048. BABYLON.serialize(),
  41049. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  41050. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  41051. __decorate([
  41052. BABYLON.serializeAsTexture(),
  41053. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  41054. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  41055. __decorate([
  41056. BABYLON.serialize(),
  41057. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  41058. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  41059. __decorate([
  41060. BABYLON.serialize()
  41061. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  41062. __decorate([
  41063. BABYLON.serializeAsTexture(),
  41064. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  41065. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  41066. __decorate([
  41067. BABYLON.serialize(),
  41068. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41069. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  41070. return PBRBaseSimpleMaterial;
  41071. }(BABYLON.PBRBaseMaterial));
  41072. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  41073. })(BABYLON || (BABYLON = {}));
  41074. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  41075. var BABYLON;
  41076. (function (BABYLON) {
  41077. /**
  41078. * The Physically based material of BJS.
  41079. *
  41080. * This offers the main features of a standard PBR material.
  41081. * For more information, please refer to the documentation :
  41082. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  41083. */
  41084. var PBRMaterial = /** @class */ (function (_super) {
  41085. __extends(PBRMaterial, _super);
  41086. /**
  41087. * Instantiates a new PBRMaterial instance.
  41088. *
  41089. * @param name The material name
  41090. * @param scene The scene the material will be use in.
  41091. */
  41092. function PBRMaterial(name, scene) {
  41093. var _this = _super.call(this, name, scene) || this;
  41094. /**
  41095. * Intensity of the direct lights e.g. the four lights available in your scene.
  41096. * This impacts both the direct diffuse and specular highlights.
  41097. */
  41098. _this.directIntensity = 1.0;
  41099. /**
  41100. * Intensity of the emissive part of the material.
  41101. * This helps controlling the emissive effect without modifying the emissive color.
  41102. */
  41103. _this.emissiveIntensity = 1.0;
  41104. /**
  41105. * Intensity of the environment e.g. how much the environment will light the object
  41106. * either through harmonics for rough material or through the refelction for shiny ones.
  41107. */
  41108. _this.environmentIntensity = 1.0;
  41109. /**
  41110. * This is a special control allowing the reduction of the specular highlights coming from the
  41111. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  41112. */
  41113. _this.specularIntensity = 1.0;
  41114. /**
  41115. * Debug Control allowing disabling the bump map on this material.
  41116. */
  41117. _this.disableBumpMap = false;
  41118. /**
  41119. * AKA Occlusion Texture Intensity in other nomenclature.
  41120. */
  41121. _this.ambientTextureStrength = 1.0;
  41122. /**
  41123. * The color of a material in ambient lighting.
  41124. */
  41125. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  41126. /**
  41127. * AKA Diffuse Color in other nomenclature.
  41128. */
  41129. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  41130. /**
  41131. * AKA Specular Color in other nomenclature.
  41132. */
  41133. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  41134. /**
  41135. * The color reflected from the material.
  41136. */
  41137. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  41138. /**
  41139. * The color emitted from the material.
  41140. */
  41141. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  41142. /**
  41143. * AKA Glossiness in other nomenclature.
  41144. */
  41145. _this.microSurface = 1.0;
  41146. /**
  41147. * source material index of refraction (IOR)' / 'destination material IOR.
  41148. */
  41149. _this.indexOfRefraction = 0.66;
  41150. /**
  41151. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  41152. */
  41153. _this.invertRefractionY = false;
  41154. /**
  41155. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  41156. * Materials half opaque for instance using refraction could benefit from this control.
  41157. */
  41158. _this.linkRefractionWithTransparency = false;
  41159. _this.useLightmapAsShadowmap = false;
  41160. /**
  41161. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  41162. */
  41163. _this.useAlphaFromAlbedoTexture = false;
  41164. /**
  41165. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  41166. */
  41167. _this.forceAlphaTest = false;
  41168. /**
  41169. * Defines the alpha limits in alpha test mode.
  41170. */
  41171. _this.alphaCutOff = 0.4;
  41172. /**
  41173. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  41174. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  41175. */
  41176. _this.useSpecularOverAlpha = true;
  41177. /**
  41178. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  41179. */
  41180. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  41181. /**
  41182. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  41183. */
  41184. _this.useRoughnessFromMetallicTextureAlpha = true;
  41185. /**
  41186. * Specifies if the metallic texture contains the roughness information in its green channel.
  41187. */
  41188. _this.useRoughnessFromMetallicTextureGreen = false;
  41189. /**
  41190. * Specifies if the metallic texture contains the metallness information in its blue channel.
  41191. */
  41192. _this.useMetallnessFromMetallicTextureBlue = false;
  41193. /**
  41194. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  41195. */
  41196. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  41197. /**
  41198. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  41199. */
  41200. _this.useAmbientInGrayScale = false;
  41201. /**
  41202. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  41203. * The material will try to infer what glossiness each pixel should be.
  41204. */
  41205. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  41206. /**
  41207. * BJS is using an harcoded light falloff based on a manually sets up range.
  41208. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  41209. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  41210. */
  41211. _this.usePhysicalLightFalloff = true;
  41212. /**
  41213. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  41214. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  41215. */
  41216. _this.useRadianceOverAlpha = true;
  41217. /**
  41218. * Allows using the bump map in parallax mode.
  41219. */
  41220. _this.useParallax = false;
  41221. /**
  41222. * Allows using the bump map in parallax occlusion mode.
  41223. */
  41224. _this.useParallaxOcclusion = false;
  41225. /**
  41226. * Controls the scale bias of the parallax mode.
  41227. */
  41228. _this.parallaxScaleBias = 0.05;
  41229. /**
  41230. * If sets to true, disables all the lights affecting the material.
  41231. */
  41232. _this.disableLighting = false;
  41233. /**
  41234. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  41235. */
  41236. _this.forceIrradianceInFragment = false;
  41237. /**
  41238. * Number of Simultaneous lights allowed on the material.
  41239. */
  41240. _this.maxSimultaneousLights = 4;
  41241. /**
  41242. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  41243. */
  41244. _this.invertNormalMapX = false;
  41245. /**
  41246. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  41247. */
  41248. _this.invertNormalMapY = false;
  41249. /**
  41250. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  41251. */
  41252. _this.twoSidedLighting = false;
  41253. /**
  41254. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  41255. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  41256. */
  41257. _this.useAlphaFresnel = false;
  41258. /**
  41259. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  41260. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  41261. */
  41262. _this.useLinearAlphaFresnel = false;
  41263. /**
  41264. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  41265. * And/Or occlude the blended part.
  41266. */
  41267. _this.environmentBRDFTexture = null;
  41268. /**
  41269. * Force normal to face away from face.
  41270. */
  41271. _this.forceNormalForward = false;
  41272. /**
  41273. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  41274. * makes the reflect vector face the model (under horizon).
  41275. */
  41276. _this.useHorizonOcclusion = true;
  41277. /**
  41278. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  41279. * too much the area relying on ambient texture to define their ambient occlusion.
  41280. */
  41281. _this.useRadianceOcclusion = true;
  41282. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  41283. return _this;
  41284. }
  41285. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  41286. /**
  41287. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  41288. */
  41289. get: function () {
  41290. return this._PBRMATERIAL_OPAQUE;
  41291. },
  41292. enumerable: true,
  41293. configurable: true
  41294. });
  41295. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  41296. /**
  41297. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  41298. */
  41299. get: function () {
  41300. return this._PBRMATERIAL_ALPHATEST;
  41301. },
  41302. enumerable: true,
  41303. configurable: true
  41304. });
  41305. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  41306. /**
  41307. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  41308. */
  41309. get: function () {
  41310. return this._PBRMATERIAL_ALPHABLEND;
  41311. },
  41312. enumerable: true,
  41313. configurable: true
  41314. });
  41315. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  41316. /**
  41317. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  41318. * They are also discarded below the alpha cutoff threshold to improve performances.
  41319. */
  41320. get: function () {
  41321. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  41322. },
  41323. enumerable: true,
  41324. configurable: true
  41325. });
  41326. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  41327. /**
  41328. * Gets the image processing configuration used either in this material.
  41329. */
  41330. get: function () {
  41331. return this._imageProcessingConfiguration;
  41332. },
  41333. /**
  41334. * Sets the Default image processing configuration used either in the this material.
  41335. *
  41336. * If sets to null, the scene one is in use.
  41337. */
  41338. set: function (value) {
  41339. this._attachImageProcessingConfiguration(value);
  41340. // Ensure the effect will be rebuilt.
  41341. this._markAllSubMeshesAsTexturesDirty();
  41342. },
  41343. enumerable: true,
  41344. configurable: true
  41345. });
  41346. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  41347. /**
  41348. * Gets wether the color curves effect is enabled.
  41349. */
  41350. get: function () {
  41351. return this.imageProcessingConfiguration.colorCurvesEnabled;
  41352. },
  41353. /**
  41354. * Sets wether the color curves effect is enabled.
  41355. */
  41356. set: function (value) {
  41357. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  41358. },
  41359. enumerable: true,
  41360. configurable: true
  41361. });
  41362. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  41363. /**
  41364. * Gets wether the color grading effect is enabled.
  41365. */
  41366. get: function () {
  41367. return this.imageProcessingConfiguration.colorGradingEnabled;
  41368. },
  41369. /**
  41370. * Gets wether the color grading effect is enabled.
  41371. */
  41372. set: function (value) {
  41373. this.imageProcessingConfiguration.colorGradingEnabled = value;
  41374. },
  41375. enumerable: true,
  41376. configurable: true
  41377. });
  41378. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  41379. /**
  41380. * Gets wether tonemapping is enabled or not.
  41381. */
  41382. get: function () {
  41383. return this._imageProcessingConfiguration.toneMappingEnabled;
  41384. },
  41385. /**
  41386. * Sets wether tonemapping is enabled or not
  41387. */
  41388. set: function (value) {
  41389. this._imageProcessingConfiguration.toneMappingEnabled = value;
  41390. },
  41391. enumerable: true,
  41392. configurable: true
  41393. });
  41394. ;
  41395. ;
  41396. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  41397. /**
  41398. * The camera exposure used on this material.
  41399. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  41400. * This corresponds to a photographic exposure.
  41401. */
  41402. get: function () {
  41403. return this._imageProcessingConfiguration.exposure;
  41404. },
  41405. /**
  41406. * The camera exposure used on this material.
  41407. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  41408. * This corresponds to a photographic exposure.
  41409. */
  41410. set: function (value) {
  41411. this._imageProcessingConfiguration.exposure = value;
  41412. },
  41413. enumerable: true,
  41414. configurable: true
  41415. });
  41416. ;
  41417. ;
  41418. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  41419. /**
  41420. * Gets The camera contrast used on this material.
  41421. */
  41422. get: function () {
  41423. return this._imageProcessingConfiguration.contrast;
  41424. },
  41425. /**
  41426. * Sets The camera contrast used on this material.
  41427. */
  41428. set: function (value) {
  41429. this._imageProcessingConfiguration.contrast = value;
  41430. },
  41431. enumerable: true,
  41432. configurable: true
  41433. });
  41434. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  41435. /**
  41436. * Gets the Color Grading 2D Lookup Texture.
  41437. */
  41438. get: function () {
  41439. return this._imageProcessingConfiguration.colorGradingTexture;
  41440. },
  41441. /**
  41442. * Sets the Color Grading 2D Lookup Texture.
  41443. */
  41444. set: function (value) {
  41445. this._imageProcessingConfiguration.colorGradingTexture = value;
  41446. },
  41447. enumerable: true,
  41448. configurable: true
  41449. });
  41450. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  41451. /**
  41452. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  41453. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  41454. * 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;
  41455. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  41456. */
  41457. get: function () {
  41458. return this._imageProcessingConfiguration.colorCurves;
  41459. },
  41460. /**
  41461. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  41462. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  41463. * 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;
  41464. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  41465. */
  41466. set: function (value) {
  41467. this._imageProcessingConfiguration.colorCurves = value;
  41468. },
  41469. enumerable: true,
  41470. configurable: true
  41471. });
  41472. /**
  41473. * Returns the name of this material class.
  41474. */
  41475. PBRMaterial.prototype.getClassName = function () {
  41476. return "PBRMaterial";
  41477. };
  41478. /**
  41479. * Returns an array of the actively used textures.
  41480. * @returns - Array of BaseTextures
  41481. */
  41482. PBRMaterial.prototype.getActiveTextures = function () {
  41483. var activeTextures = _super.prototype.getActiveTextures.call(this);
  41484. if (this._albedoTexture) {
  41485. activeTextures.push(this._albedoTexture);
  41486. }
  41487. if (this._ambientTexture) {
  41488. activeTextures.push(this._ambientTexture);
  41489. }
  41490. if (this._opacityTexture) {
  41491. activeTextures.push(this._opacityTexture);
  41492. }
  41493. if (this._reflectionTexture) {
  41494. activeTextures.push(this._reflectionTexture);
  41495. }
  41496. if (this._emissiveTexture) {
  41497. activeTextures.push(this._emissiveTexture);
  41498. }
  41499. if (this._reflectivityTexture) {
  41500. activeTextures.push(this._reflectivityTexture);
  41501. }
  41502. if (this._metallicTexture) {
  41503. activeTextures.push(this._metallicTexture);
  41504. }
  41505. if (this._microSurfaceTexture) {
  41506. activeTextures.push(this._microSurfaceTexture);
  41507. }
  41508. if (this._bumpTexture) {
  41509. activeTextures.push(this._bumpTexture);
  41510. }
  41511. if (this._lightmapTexture) {
  41512. activeTextures.push(this._lightmapTexture);
  41513. }
  41514. if (this._refractionTexture) {
  41515. activeTextures.push(this._refractionTexture);
  41516. }
  41517. return activeTextures;
  41518. };
  41519. /**
  41520. * Checks to see if a texture is used in the material.
  41521. * @param texture - Base texture to use.
  41522. * @returns - Boolean specifying if a texture is used in the material.
  41523. */
  41524. PBRMaterial.prototype.hasTexture = function (texture) {
  41525. if (_super.prototype.hasTexture.call(this, texture)) {
  41526. return true;
  41527. }
  41528. if (this._albedoTexture === texture) {
  41529. return true;
  41530. }
  41531. if (this._ambientTexture === texture) {
  41532. return true;
  41533. }
  41534. if (this._opacityTexture === texture) {
  41535. return true;
  41536. }
  41537. if (this._reflectionTexture === texture) {
  41538. return true;
  41539. }
  41540. if (this._reflectivityTexture === texture) {
  41541. return true;
  41542. }
  41543. if (this._metallicTexture === texture) {
  41544. return true;
  41545. }
  41546. if (this._microSurfaceTexture === texture) {
  41547. return true;
  41548. }
  41549. if (this._bumpTexture === texture) {
  41550. return true;
  41551. }
  41552. if (this._lightmapTexture === texture) {
  41553. return true;
  41554. }
  41555. if (this._refractionTexture === texture) {
  41556. return true;
  41557. }
  41558. return false;
  41559. };
  41560. /**
  41561. * Makes a duplicate of the current material.
  41562. * @param name - name to use for the new material.
  41563. */
  41564. PBRMaterial.prototype.clone = function (name) {
  41565. var _this = this;
  41566. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  41567. clone.id = name;
  41568. clone.name = name;
  41569. return clone;
  41570. };
  41571. /**
  41572. * Serializes this PBR Material.
  41573. * @returns - An object with the serialized material.
  41574. */
  41575. PBRMaterial.prototype.serialize = function () {
  41576. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  41577. serializationObject.customType = "BABYLON.PBRMaterial";
  41578. return serializationObject;
  41579. };
  41580. // Statics
  41581. /**
  41582. * Parses a PBR Material from a serialized object.
  41583. * @param source - Serialized object.
  41584. * @param scene - BJS scene instance.
  41585. * @param rootUrl - url for the scene object
  41586. * @returns - PBRMaterial
  41587. */
  41588. PBRMaterial.Parse = function (source, scene, rootUrl) {
  41589. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  41590. };
  41591. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  41592. /**
  41593. * Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  41594. */
  41595. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  41596. /**
  41597. * Represents the value for Alpha Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  41598. */
  41599. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  41600. /**
  41601. * 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.
  41602. * They are also discarded below the alpha cutoff threshold to improve performances.
  41603. */
  41604. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  41605. __decorate([
  41606. BABYLON.serialize(),
  41607. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41608. ], PBRMaterial.prototype, "directIntensity", void 0);
  41609. __decorate([
  41610. BABYLON.serialize(),
  41611. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41612. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  41613. __decorate([
  41614. BABYLON.serialize(),
  41615. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41616. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  41617. __decorate([
  41618. BABYLON.serialize(),
  41619. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41620. ], PBRMaterial.prototype, "specularIntensity", void 0);
  41621. __decorate([
  41622. BABYLON.serialize(),
  41623. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41624. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  41625. __decorate([
  41626. BABYLON.serializeAsTexture(),
  41627. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41628. ], PBRMaterial.prototype, "albedoTexture", void 0);
  41629. __decorate([
  41630. BABYLON.serializeAsTexture(),
  41631. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41632. ], PBRMaterial.prototype, "ambientTexture", void 0);
  41633. __decorate([
  41634. BABYLON.serialize(),
  41635. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41636. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  41637. __decorate([
  41638. BABYLON.serializeAsTexture(),
  41639. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  41640. ], PBRMaterial.prototype, "opacityTexture", void 0);
  41641. __decorate([
  41642. BABYLON.serializeAsTexture(),
  41643. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41644. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  41645. __decorate([
  41646. BABYLON.serializeAsTexture(),
  41647. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41648. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  41649. __decorate([
  41650. BABYLON.serializeAsTexture(),
  41651. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41652. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  41653. __decorate([
  41654. BABYLON.serializeAsTexture(),
  41655. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41656. ], PBRMaterial.prototype, "metallicTexture", void 0);
  41657. __decorate([
  41658. BABYLON.serialize(),
  41659. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41660. ], PBRMaterial.prototype, "metallic", void 0);
  41661. __decorate([
  41662. BABYLON.serialize(),
  41663. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41664. ], PBRMaterial.prototype, "roughness", void 0);
  41665. __decorate([
  41666. BABYLON.serializeAsTexture(),
  41667. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41668. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  41669. __decorate([
  41670. BABYLON.serializeAsTexture(),
  41671. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41672. ], PBRMaterial.prototype, "bumpTexture", void 0);
  41673. __decorate([
  41674. BABYLON.serializeAsTexture(),
  41675. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  41676. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  41677. __decorate([
  41678. BABYLON.serializeAsTexture(),
  41679. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41680. ], PBRMaterial.prototype, "refractionTexture", void 0);
  41681. __decorate([
  41682. BABYLON.serializeAsColor3("ambient"),
  41683. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41684. ], PBRMaterial.prototype, "ambientColor", void 0);
  41685. __decorate([
  41686. BABYLON.serializeAsColor3("albedo"),
  41687. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41688. ], PBRMaterial.prototype, "albedoColor", void 0);
  41689. __decorate([
  41690. BABYLON.serializeAsColor3("reflectivity"),
  41691. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41692. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  41693. __decorate([
  41694. BABYLON.serializeAsColor3("reflection"),
  41695. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41696. ], PBRMaterial.prototype, "reflectionColor", void 0);
  41697. __decorate([
  41698. BABYLON.serializeAsColor3("emissive"),
  41699. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41700. ], PBRMaterial.prototype, "emissiveColor", void 0);
  41701. __decorate([
  41702. BABYLON.serialize(),
  41703. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41704. ], PBRMaterial.prototype, "microSurface", void 0);
  41705. __decorate([
  41706. BABYLON.serialize(),
  41707. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41708. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  41709. __decorate([
  41710. BABYLON.serialize(),
  41711. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41712. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  41713. __decorate([
  41714. BABYLON.serialize(),
  41715. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41716. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  41717. __decorate([
  41718. BABYLON.serialize(),
  41719. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41720. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  41721. __decorate([
  41722. BABYLON.serialize(),
  41723. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  41724. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  41725. __decorate([
  41726. BABYLON.serialize(),
  41727. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  41728. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  41729. __decorate([
  41730. BABYLON.serialize(),
  41731. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  41732. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  41733. __decorate([
  41734. BABYLON.serialize(),
  41735. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41736. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  41737. __decorate([
  41738. BABYLON.serialize(),
  41739. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41740. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  41741. __decorate([
  41742. BABYLON.serialize(),
  41743. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41744. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  41745. __decorate([
  41746. BABYLON.serialize(),
  41747. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41748. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  41749. __decorate([
  41750. BABYLON.serialize(),
  41751. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41752. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  41753. __decorate([
  41754. BABYLON.serialize(),
  41755. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41756. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  41757. __decorate([
  41758. BABYLON.serialize(),
  41759. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41760. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  41761. __decorate([
  41762. BABYLON.serialize(),
  41763. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41764. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  41765. __decorate([
  41766. BABYLON.serialize(),
  41767. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41768. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  41769. __decorate([
  41770. BABYLON.serialize(),
  41771. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41772. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  41773. __decorate([
  41774. BABYLON.serialize(),
  41775. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41776. ], PBRMaterial.prototype, "useParallax", void 0);
  41777. __decorate([
  41778. BABYLON.serialize(),
  41779. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41780. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  41781. __decorate([
  41782. BABYLON.serialize(),
  41783. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41784. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  41785. __decorate([
  41786. BABYLON.serialize(),
  41787. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  41788. ], PBRMaterial.prototype, "disableLighting", void 0);
  41789. __decorate([
  41790. BABYLON.serialize(),
  41791. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41792. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  41793. __decorate([
  41794. BABYLON.serialize(),
  41795. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  41796. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  41797. __decorate([
  41798. BABYLON.serialize(),
  41799. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41800. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  41801. __decorate([
  41802. BABYLON.serialize(),
  41803. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41804. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  41805. __decorate([
  41806. BABYLON.serialize(),
  41807. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41808. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  41809. __decorate([
  41810. BABYLON.serialize(),
  41811. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41812. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  41813. __decorate([
  41814. BABYLON.serialize(),
  41815. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41816. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  41817. __decorate([
  41818. BABYLON.serializeAsTexture(),
  41819. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41820. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  41821. __decorate([
  41822. BABYLON.serialize(),
  41823. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41824. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  41825. __decorate([
  41826. BABYLON.serialize(),
  41827. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41828. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  41829. __decorate([
  41830. BABYLON.serialize(),
  41831. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41832. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  41833. return PBRMaterial;
  41834. }(BABYLON.PBRBaseMaterial));
  41835. BABYLON.PBRMaterial = PBRMaterial;
  41836. })(BABYLON || (BABYLON = {}));
  41837. //# sourceMappingURL=babylon.pbrMaterial.js.map
  41838. var BABYLON;
  41839. (function (BABYLON) {
  41840. /**
  41841. * The PBR material of BJS following the metal roughness convention.
  41842. *
  41843. * This fits to the PBR convention in the GLTF definition:
  41844. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  41845. */
  41846. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  41847. __extends(PBRMetallicRoughnessMaterial, _super);
  41848. /**
  41849. * Instantiates a new PBRMetalRoughnessMaterial instance.
  41850. *
  41851. * @param name The material name
  41852. * @param scene The scene the material will be use in.
  41853. */
  41854. function PBRMetallicRoughnessMaterial(name, scene) {
  41855. var _this = _super.call(this, name, scene) || this;
  41856. _this._useRoughnessFromMetallicTextureAlpha = false;
  41857. _this._useRoughnessFromMetallicTextureGreen = true;
  41858. _this._useMetallnessFromMetallicTextureBlue = true;
  41859. _this._forceMetallicWorkflow = true;
  41860. return _this;
  41861. }
  41862. /**
  41863. * Return the currrent class name of the material.
  41864. */
  41865. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  41866. return "PBRMetallicRoughnessMaterial";
  41867. };
  41868. /**
  41869. * Return the active textures of the material.
  41870. */
  41871. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  41872. var activeTextures = _super.prototype.getActiveTextures.call(this);
  41873. if (this.baseTexture) {
  41874. activeTextures.push(this.baseTexture);
  41875. }
  41876. if (this.metallicRoughnessTexture) {
  41877. activeTextures.push(this.metallicRoughnessTexture);
  41878. }
  41879. return activeTextures;
  41880. };
  41881. /**
  41882. * Checks to see if a texture is used in the material.
  41883. * @param texture - Base texture to use.
  41884. * @returns - Boolean specifying if a texture is used in the material.
  41885. */
  41886. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  41887. if (_super.prototype.hasTexture.call(this, texture)) {
  41888. return true;
  41889. }
  41890. if (this.baseTexture === texture) {
  41891. return true;
  41892. }
  41893. if (this.metallicRoughnessTexture === texture) {
  41894. return true;
  41895. }
  41896. return false;
  41897. };
  41898. /**
  41899. * Makes a duplicate of the current material.
  41900. * @param name - name to use for the new material.
  41901. */
  41902. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  41903. var _this = this;
  41904. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  41905. clone.id = name;
  41906. clone.name = name;
  41907. return clone;
  41908. };
  41909. /**
  41910. * Serialize the material to a parsable JSON object.
  41911. */
  41912. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  41913. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  41914. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  41915. return serializationObject;
  41916. };
  41917. /**
  41918. * Parses a JSON object correponding to the serialize function.
  41919. */
  41920. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  41921. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  41922. };
  41923. __decorate([
  41924. BABYLON.serializeAsColor3(),
  41925. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  41926. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  41927. __decorate([
  41928. BABYLON.serializeAsTexture(),
  41929. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  41930. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  41931. __decorate([
  41932. BABYLON.serialize(),
  41933. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41934. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  41935. __decorate([
  41936. BABYLON.serialize(),
  41937. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41938. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  41939. __decorate([
  41940. BABYLON.serializeAsTexture(),
  41941. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  41942. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  41943. return PBRMetallicRoughnessMaterial;
  41944. }(BABYLON.PBRBaseSimpleMaterial));
  41945. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  41946. })(BABYLON || (BABYLON = {}));
  41947. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  41948. var BABYLON;
  41949. (function (BABYLON) {
  41950. /**
  41951. * The PBR material of BJS following the specular glossiness convention.
  41952. *
  41953. * This fits to the PBR convention in the GLTF definition:
  41954. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  41955. */
  41956. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  41957. __extends(PBRSpecularGlossinessMaterial, _super);
  41958. /**
  41959. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  41960. *
  41961. * @param name The material name
  41962. * @param scene The scene the material will be use in.
  41963. */
  41964. function PBRSpecularGlossinessMaterial(name, scene) {
  41965. var _this = _super.call(this, name, scene) || this;
  41966. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  41967. return _this;
  41968. }
  41969. /**
  41970. * Return the currrent class name of the material.
  41971. */
  41972. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  41973. return "PBRSpecularGlossinessMaterial";
  41974. };
  41975. /**
  41976. * Return the active textures of the material.
  41977. */
  41978. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  41979. var activeTextures = _super.prototype.getActiveTextures.call(this);
  41980. if (this.diffuseTexture) {
  41981. activeTextures.push(this.diffuseTexture);
  41982. }
  41983. if (this.specularGlossinessTexture) {
  41984. activeTextures.push(this.specularGlossinessTexture);
  41985. }
  41986. return activeTextures;
  41987. };
  41988. /**
  41989. * Checks to see if a texture is used in the material.
  41990. * @param texture - Base texture to use.
  41991. * @returns - Boolean specifying if a texture is used in the material.
  41992. */
  41993. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  41994. if (_super.prototype.hasTexture.call(this, texture)) {
  41995. return true;
  41996. }
  41997. if (this.diffuseTexture === texture) {
  41998. return true;
  41999. }
  42000. if (this.specularGlossinessTexture === texture) {
  42001. return true;
  42002. }
  42003. return false;
  42004. };
  42005. /**
  42006. * Makes a duplicate of the current material.
  42007. * @param name - name to use for the new material.
  42008. */
  42009. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  42010. var _this = this;
  42011. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  42012. clone.id = name;
  42013. clone.name = name;
  42014. return clone;
  42015. };
  42016. /**
  42017. * Serialize the material to a parsable JSON object.
  42018. */
  42019. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  42020. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  42021. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  42022. return serializationObject;
  42023. };
  42024. /**
  42025. * Parses a JSON object correponding to the serialize function.
  42026. */
  42027. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  42028. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  42029. };
  42030. __decorate([
  42031. BABYLON.serializeAsColor3("diffuse"),
  42032. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  42033. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  42034. __decorate([
  42035. BABYLON.serializeAsTexture(),
  42036. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  42037. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  42038. __decorate([
  42039. BABYLON.serializeAsColor3("specular"),
  42040. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  42041. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  42042. __decorate([
  42043. BABYLON.serialize(),
  42044. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  42045. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  42046. __decorate([
  42047. BABYLON.serializeAsTexture(),
  42048. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  42049. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  42050. return PBRSpecularGlossinessMaterial;
  42051. }(BABYLON.PBRBaseSimpleMaterial));
  42052. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  42053. })(BABYLON || (BABYLON = {}));
  42054. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  42055. var BABYLON;
  42056. (function (BABYLON) {
  42057. BABYLON.CameraInputTypes = {};
  42058. var CameraInputsManager = /** @class */ (function () {
  42059. function CameraInputsManager(camera) {
  42060. this.attached = {};
  42061. this.camera = camera;
  42062. this.checkInputs = function () { };
  42063. }
  42064. /**
  42065. * Add an input method to a camera.
  42066. * builtin inputs example: camera.inputs.addGamepad();
  42067. * custom inputs example: camera.inputs.add(new BABYLON.FreeCameraGamepadInput());
  42068. * @param input camera input method
  42069. */
  42070. CameraInputsManager.prototype.add = function (input) {
  42071. var type = input.getSimpleName();
  42072. if (this.attached[type]) {
  42073. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  42074. return;
  42075. }
  42076. this.attached[type] = input;
  42077. input.camera = this.camera;
  42078. //for checkInputs, we are dynamically creating a function
  42079. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  42080. if (input.checkInputs) {
  42081. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  42082. }
  42083. if (this.attachedElement) {
  42084. input.attachControl(this.attachedElement);
  42085. }
  42086. };
  42087. /**
  42088. * Remove a specific input method from a camera
  42089. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  42090. * @param inputToRemove camera input method
  42091. */
  42092. CameraInputsManager.prototype.remove = function (inputToRemove) {
  42093. for (var cam in this.attached) {
  42094. var input = this.attached[cam];
  42095. if (input === inputToRemove) {
  42096. input.detachControl(this.attachedElement);
  42097. input.camera = null;
  42098. delete this.attached[cam];
  42099. this.rebuildInputCheck();
  42100. }
  42101. }
  42102. };
  42103. CameraInputsManager.prototype.removeByType = function (inputType) {
  42104. for (var cam in this.attached) {
  42105. var input = this.attached[cam];
  42106. if (input.getClassName() === inputType) {
  42107. input.detachControl(this.attachedElement);
  42108. input.camera = null;
  42109. delete this.attached[cam];
  42110. this.rebuildInputCheck();
  42111. }
  42112. }
  42113. };
  42114. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  42115. var current = this.checkInputs;
  42116. return function () {
  42117. current();
  42118. fn();
  42119. };
  42120. };
  42121. CameraInputsManager.prototype.attachInput = function (input) {
  42122. if (this.attachedElement) {
  42123. input.attachControl(this.attachedElement, this.noPreventDefault);
  42124. }
  42125. };
  42126. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  42127. if (noPreventDefault === void 0) { noPreventDefault = false; }
  42128. if (this.attachedElement) {
  42129. return;
  42130. }
  42131. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  42132. this.attachedElement = element;
  42133. this.noPreventDefault = noPreventDefault;
  42134. for (var cam in this.attached) {
  42135. this.attached[cam].attachControl(element, noPreventDefault);
  42136. }
  42137. };
  42138. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  42139. if (disconnect === void 0) { disconnect = false; }
  42140. if (this.attachedElement !== element) {
  42141. return;
  42142. }
  42143. for (var cam in this.attached) {
  42144. this.attached[cam].detachControl(element);
  42145. if (disconnect) {
  42146. this.attached[cam].camera = null;
  42147. }
  42148. }
  42149. this.attachedElement = null;
  42150. };
  42151. CameraInputsManager.prototype.rebuildInputCheck = function () {
  42152. this.checkInputs = function () { };
  42153. for (var cam in this.attached) {
  42154. var input = this.attached[cam];
  42155. if (input.checkInputs) {
  42156. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  42157. }
  42158. }
  42159. };
  42160. /**
  42161. * Remove all attached input methods from a camera
  42162. */
  42163. CameraInputsManager.prototype.clear = function () {
  42164. if (this.attachedElement) {
  42165. this.detachElement(this.attachedElement, true);
  42166. }
  42167. this.attached = {};
  42168. this.attachedElement = null;
  42169. this.checkInputs = function () { };
  42170. };
  42171. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  42172. var inputs = {};
  42173. for (var cam in this.attached) {
  42174. var input = this.attached[cam];
  42175. var res = BABYLON.SerializationHelper.Serialize(input);
  42176. inputs[input.getClassName()] = res;
  42177. }
  42178. serializedCamera.inputsmgr = inputs;
  42179. };
  42180. CameraInputsManager.prototype.parse = function (parsedCamera) {
  42181. var parsedInputs = parsedCamera.inputsmgr;
  42182. if (parsedInputs) {
  42183. this.clear();
  42184. for (var n in parsedInputs) {
  42185. var construct = BABYLON.CameraInputTypes[n];
  42186. if (construct) {
  42187. var parsedinput = parsedInputs[n];
  42188. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  42189. this.add(input);
  42190. }
  42191. }
  42192. }
  42193. else {
  42194. //2016-03-08 this part is for managing backward compatibility
  42195. for (var n in this.attached) {
  42196. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  42197. if (construct) {
  42198. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  42199. this.remove(this.attached[n]);
  42200. this.add(input);
  42201. }
  42202. }
  42203. }
  42204. };
  42205. return CameraInputsManager;
  42206. }());
  42207. BABYLON.CameraInputsManager = CameraInputsManager;
  42208. })(BABYLON || (BABYLON = {}));
  42209. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  42210. var BABYLON;
  42211. (function (BABYLON) {
  42212. var TargetCamera = /** @class */ (function (_super) {
  42213. __extends(TargetCamera, _super);
  42214. function TargetCamera(name, position, scene) {
  42215. var _this = _super.call(this, name, position, scene) || this;
  42216. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  42217. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  42218. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  42219. _this.speed = 2.0;
  42220. _this.noRotationConstraint = false;
  42221. _this.lockedTarget = null;
  42222. _this._currentTarget = BABYLON.Vector3.Zero();
  42223. _this._viewMatrix = BABYLON.Matrix.Zero();
  42224. _this._camMatrix = BABYLON.Matrix.Zero();
  42225. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  42226. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  42227. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  42228. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  42229. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  42230. _this._lookAtTemp = BABYLON.Matrix.Zero();
  42231. _this._tempMatrix = BABYLON.Matrix.Zero();
  42232. return _this;
  42233. }
  42234. TargetCamera.prototype.getFrontPosition = function (distance) {
  42235. this.getWorldMatrix();
  42236. var direction = this.getTarget().subtract(this.position);
  42237. direction.normalize();
  42238. direction.scaleInPlace(distance);
  42239. return this.globalPosition.add(direction);
  42240. };
  42241. TargetCamera.prototype._getLockedTargetPosition = function () {
  42242. if (!this.lockedTarget) {
  42243. return null;
  42244. }
  42245. if (this.lockedTarget.absolutePosition) {
  42246. this.lockedTarget.computeWorldMatrix();
  42247. }
  42248. return this.lockedTarget.absolutePosition || this.lockedTarget;
  42249. };
  42250. TargetCamera.prototype.storeState = function () {
  42251. this._storedPosition = this.position.clone();
  42252. this._storedRotation = this.rotation.clone();
  42253. if (this.rotationQuaternion) {
  42254. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  42255. }
  42256. return _super.prototype.storeState.call(this);
  42257. };
  42258. /**
  42259. * Restored camera state. You must call storeState() first
  42260. */
  42261. TargetCamera.prototype._restoreStateValues = function () {
  42262. if (!_super.prototype._restoreStateValues.call(this)) {
  42263. return false;
  42264. }
  42265. this.position = this._storedPosition.clone();
  42266. this.rotation = this._storedRotation.clone();
  42267. if (this.rotationQuaternion) {
  42268. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  42269. }
  42270. this.cameraDirection.copyFromFloats(0, 0, 0);
  42271. this.cameraRotation.copyFromFloats(0, 0);
  42272. return true;
  42273. };
  42274. // Cache
  42275. TargetCamera.prototype._initCache = function () {
  42276. _super.prototype._initCache.call(this);
  42277. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  42278. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  42279. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  42280. };
  42281. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  42282. if (!ignoreParentClass) {
  42283. _super.prototype._updateCache.call(this);
  42284. }
  42285. var lockedTargetPosition = this._getLockedTargetPosition();
  42286. if (!lockedTargetPosition) {
  42287. this._cache.lockedTarget = null;
  42288. }
  42289. else {
  42290. if (!this._cache.lockedTarget) {
  42291. this._cache.lockedTarget = lockedTargetPosition.clone();
  42292. }
  42293. else {
  42294. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  42295. }
  42296. }
  42297. this._cache.rotation.copyFrom(this.rotation);
  42298. if (this.rotationQuaternion)
  42299. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  42300. };
  42301. // Synchronized
  42302. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  42303. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  42304. return false;
  42305. }
  42306. var lockedTargetPosition = this._getLockedTargetPosition();
  42307. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  42308. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  42309. };
  42310. // Methods
  42311. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  42312. var engine = this.getEngine();
  42313. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  42314. };
  42315. // Target
  42316. TargetCamera.prototype.setTarget = function (target) {
  42317. this.upVector.normalize();
  42318. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  42319. this._camMatrix.invert();
  42320. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  42321. var vDir = target.subtract(this.position);
  42322. if (vDir.x >= 0.0) {
  42323. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  42324. }
  42325. else {
  42326. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  42327. }
  42328. this.rotation.z = 0;
  42329. if (isNaN(this.rotation.x)) {
  42330. this.rotation.x = 0;
  42331. }
  42332. if (isNaN(this.rotation.y)) {
  42333. this.rotation.y = 0;
  42334. }
  42335. if (isNaN(this.rotation.z)) {
  42336. this.rotation.z = 0;
  42337. }
  42338. if (this.rotationQuaternion) {
  42339. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  42340. }
  42341. };
  42342. /**
  42343. * Return the current target position of the camera. This value is expressed in local space.
  42344. */
  42345. TargetCamera.prototype.getTarget = function () {
  42346. return this._currentTarget;
  42347. };
  42348. TargetCamera.prototype._decideIfNeedsToMove = function () {
  42349. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  42350. };
  42351. TargetCamera.prototype._updatePosition = function () {
  42352. if (this.parent) {
  42353. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  42354. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  42355. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  42356. return;
  42357. }
  42358. this.position.addInPlace(this.cameraDirection);
  42359. };
  42360. TargetCamera.prototype._checkInputs = function () {
  42361. var needToMove = this._decideIfNeedsToMove();
  42362. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  42363. // Move
  42364. if (needToMove) {
  42365. this._updatePosition();
  42366. }
  42367. // Rotate
  42368. if (needToRotate) {
  42369. this.rotation.x += this.cameraRotation.x;
  42370. this.rotation.y += this.cameraRotation.y;
  42371. //rotate, if quaternion is set and rotation was used
  42372. if (this.rotationQuaternion) {
  42373. var len = this.rotation.lengthSquared();
  42374. if (len) {
  42375. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  42376. }
  42377. }
  42378. if (!this.noRotationConstraint) {
  42379. var limit = (Math.PI / 2) * 0.95;
  42380. if (this.rotation.x > limit)
  42381. this.rotation.x = limit;
  42382. if (this.rotation.x < -limit)
  42383. this.rotation.x = -limit;
  42384. }
  42385. }
  42386. // Inertia
  42387. if (needToMove) {
  42388. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  42389. this.cameraDirection.x = 0;
  42390. }
  42391. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  42392. this.cameraDirection.y = 0;
  42393. }
  42394. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  42395. this.cameraDirection.z = 0;
  42396. }
  42397. this.cameraDirection.scaleInPlace(this.inertia);
  42398. }
  42399. if (needToRotate) {
  42400. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  42401. this.cameraRotation.x = 0;
  42402. }
  42403. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  42404. this.cameraRotation.y = 0;
  42405. }
  42406. this.cameraRotation.scaleInPlace(this.inertia);
  42407. }
  42408. _super.prototype._checkInputs.call(this);
  42409. };
  42410. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  42411. if (this.rotationQuaternion) {
  42412. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  42413. }
  42414. else {
  42415. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  42416. }
  42417. //update the up vector!
  42418. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  42419. };
  42420. TargetCamera.prototype._getViewMatrix = function () {
  42421. if (this.lockedTarget) {
  42422. this.setTarget(this._getLockedTargetPosition());
  42423. }
  42424. // Compute
  42425. this._updateCameraRotationMatrix();
  42426. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  42427. // Computing target and final matrix
  42428. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  42429. if (this.getScene().useRightHandedSystem) {
  42430. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  42431. }
  42432. else {
  42433. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  42434. }
  42435. return this._viewMatrix;
  42436. };
  42437. /**
  42438. * @override
  42439. * Override Camera.createRigCamera
  42440. */
  42441. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  42442. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  42443. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  42444. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  42445. if (!this.rotationQuaternion) {
  42446. this.rotationQuaternion = new BABYLON.Quaternion();
  42447. }
  42448. rigCamera._cameraRigParams = {};
  42449. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  42450. }
  42451. return rigCamera;
  42452. }
  42453. return null;
  42454. };
  42455. /**
  42456. * @override
  42457. * Override Camera._updateRigCameras
  42458. */
  42459. TargetCamera.prototype._updateRigCameras = function () {
  42460. var camLeft = this._rigCameras[0];
  42461. var camRight = this._rigCameras[1];
  42462. switch (this.cameraRigMode) {
  42463. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  42464. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  42465. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  42466. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  42467. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  42468. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  42469. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  42470. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  42471. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  42472. camLeft.setTarget(this.getTarget());
  42473. camRight.setTarget(this.getTarget());
  42474. break;
  42475. case BABYLON.Camera.RIG_MODE_VR:
  42476. if (camLeft.rotationQuaternion) {
  42477. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  42478. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  42479. }
  42480. else {
  42481. camLeft.rotation.copyFrom(this.rotation);
  42482. camRight.rotation.copyFrom(this.rotation);
  42483. }
  42484. camLeft.position.copyFrom(this.position);
  42485. camRight.position.copyFrom(this.position);
  42486. break;
  42487. }
  42488. _super.prototype._updateRigCameras.call(this);
  42489. };
  42490. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  42491. if (!this._rigCamTransformMatrix) {
  42492. this._rigCamTransformMatrix = new BABYLON.Matrix();
  42493. }
  42494. var target = this.getTarget();
  42495. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  42496. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  42497. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  42498. };
  42499. TargetCamera.prototype.getClassName = function () {
  42500. return "TargetCamera";
  42501. };
  42502. __decorate([
  42503. BABYLON.serializeAsVector3()
  42504. ], TargetCamera.prototype, "rotation", void 0);
  42505. __decorate([
  42506. BABYLON.serialize()
  42507. ], TargetCamera.prototype, "speed", void 0);
  42508. __decorate([
  42509. BABYLON.serializeAsMeshReference("lockedTargetId")
  42510. ], TargetCamera.prototype, "lockedTarget", void 0);
  42511. return TargetCamera;
  42512. }(BABYLON.Camera));
  42513. BABYLON.TargetCamera = TargetCamera;
  42514. })(BABYLON || (BABYLON = {}));
  42515. //# sourceMappingURL=babylon.targetCamera.js.map
  42516. var BABYLON;
  42517. (function (BABYLON) {
  42518. var FreeCameraMouseInput = /** @class */ (function () {
  42519. function FreeCameraMouseInput(touchEnabled) {
  42520. if (touchEnabled === void 0) { touchEnabled = true; }
  42521. this.touchEnabled = touchEnabled;
  42522. this.buttons = [0, 1, 2];
  42523. this.angularSensibility = 2000.0;
  42524. this.previousPosition = null;
  42525. }
  42526. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  42527. var _this = this;
  42528. var engine = this.camera.getEngine();
  42529. if (!this._pointerInput) {
  42530. this._pointerInput = function (p, s) {
  42531. var evt = p.event;
  42532. if (engine.isInVRExclusivePointerMode) {
  42533. return;
  42534. }
  42535. if (!_this.touchEnabled && evt.pointerType === "touch") {
  42536. return;
  42537. }
  42538. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  42539. return;
  42540. }
  42541. var srcElement = (evt.srcElement || evt.target);
  42542. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  42543. try {
  42544. srcElement.setPointerCapture(evt.pointerId);
  42545. }
  42546. catch (e) {
  42547. //Nothing to do with the error. Execution will continue.
  42548. }
  42549. _this.previousPosition = {
  42550. x: evt.clientX,
  42551. y: evt.clientY
  42552. };
  42553. if (!noPreventDefault) {
  42554. evt.preventDefault();
  42555. element.focus();
  42556. }
  42557. }
  42558. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  42559. try {
  42560. srcElement.releasePointerCapture(evt.pointerId);
  42561. }
  42562. catch (e) {
  42563. //Nothing to do with the error.
  42564. }
  42565. _this.previousPosition = null;
  42566. if (!noPreventDefault) {
  42567. evt.preventDefault();
  42568. }
  42569. }
  42570. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  42571. if (!_this.previousPosition || engine.isPointerLock) {
  42572. return;
  42573. }
  42574. var offsetX = evt.clientX - _this.previousPosition.x;
  42575. var offsetY = evt.clientY - _this.previousPosition.y;
  42576. if (_this.camera.getScene().useRightHandedSystem) {
  42577. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  42578. }
  42579. else {
  42580. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  42581. }
  42582. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  42583. _this.previousPosition = {
  42584. x: evt.clientX,
  42585. y: evt.clientY
  42586. };
  42587. if (!noPreventDefault) {
  42588. evt.preventDefault();
  42589. }
  42590. }
  42591. };
  42592. }
  42593. this._onMouseMove = function (evt) {
  42594. if (!engine.isPointerLock) {
  42595. return;
  42596. }
  42597. if (engine.isInVRExclusivePointerMode) {
  42598. return;
  42599. }
  42600. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  42601. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  42602. if (_this.camera.getScene().useRightHandedSystem) {
  42603. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  42604. }
  42605. else {
  42606. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  42607. }
  42608. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  42609. _this.previousPosition = null;
  42610. if (!noPreventDefault) {
  42611. evt.preventDefault();
  42612. }
  42613. };
  42614. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  42615. element.addEventListener("mousemove", this._onMouseMove, false);
  42616. };
  42617. FreeCameraMouseInput.prototype.detachControl = function (element) {
  42618. if (this._observer && element) {
  42619. this.camera.getScene().onPointerObservable.remove(this._observer);
  42620. if (this._onMouseMove) {
  42621. element.removeEventListener("mousemove", this._onMouseMove);
  42622. }
  42623. this._observer = null;
  42624. this._onMouseMove = null;
  42625. this.previousPosition = null;
  42626. }
  42627. };
  42628. FreeCameraMouseInput.prototype.getClassName = function () {
  42629. return "FreeCameraMouseInput";
  42630. };
  42631. FreeCameraMouseInput.prototype.getSimpleName = function () {
  42632. return "mouse";
  42633. };
  42634. __decorate([
  42635. BABYLON.serialize()
  42636. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  42637. __decorate([
  42638. BABYLON.serialize()
  42639. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  42640. return FreeCameraMouseInput;
  42641. }());
  42642. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  42643. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  42644. })(BABYLON || (BABYLON = {}));
  42645. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  42646. var BABYLON;
  42647. (function (BABYLON) {
  42648. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  42649. function FreeCameraKeyboardMoveInput() {
  42650. this._keys = new Array();
  42651. this.keysUp = [38];
  42652. this.keysDown = [40];
  42653. this.keysLeft = [37];
  42654. this.keysRight = [39];
  42655. }
  42656. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  42657. var _this = this;
  42658. if (this._onCanvasBlurObserver) {
  42659. return;
  42660. }
  42661. this._scene = this.camera.getScene();
  42662. this._engine = this._scene.getEngine();
  42663. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  42664. _this._keys = [];
  42665. });
  42666. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  42667. var evt = info.event;
  42668. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  42669. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  42670. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  42671. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  42672. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  42673. var index = _this._keys.indexOf(evt.keyCode);
  42674. if (index === -1) {
  42675. _this._keys.push(evt.keyCode);
  42676. }
  42677. if (!noPreventDefault) {
  42678. evt.preventDefault();
  42679. }
  42680. }
  42681. }
  42682. else {
  42683. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  42684. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  42685. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  42686. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  42687. var index = _this._keys.indexOf(evt.keyCode);
  42688. if (index >= 0) {
  42689. _this._keys.splice(index, 1);
  42690. }
  42691. if (!noPreventDefault) {
  42692. evt.preventDefault();
  42693. }
  42694. }
  42695. }
  42696. });
  42697. };
  42698. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  42699. if (this._scene) {
  42700. if (this._onKeyboardObserver) {
  42701. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  42702. }
  42703. if (this._onCanvasBlurObserver) {
  42704. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  42705. }
  42706. this._onKeyboardObserver = null;
  42707. this._onCanvasBlurObserver = null;
  42708. }
  42709. this._keys = [];
  42710. };
  42711. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  42712. if (this._onKeyboardObserver) {
  42713. var camera = this.camera;
  42714. // Keyboard
  42715. for (var index = 0; index < this._keys.length; index++) {
  42716. var keyCode = this._keys[index];
  42717. var speed = camera._computeLocalCameraSpeed();
  42718. if (this.keysLeft.indexOf(keyCode) !== -1) {
  42719. camera._localDirection.copyFromFloats(-speed, 0, 0);
  42720. }
  42721. else if (this.keysUp.indexOf(keyCode) !== -1) {
  42722. camera._localDirection.copyFromFloats(0, 0, speed);
  42723. }
  42724. else if (this.keysRight.indexOf(keyCode) !== -1) {
  42725. camera._localDirection.copyFromFloats(speed, 0, 0);
  42726. }
  42727. else if (this.keysDown.indexOf(keyCode) !== -1) {
  42728. camera._localDirection.copyFromFloats(0, 0, -speed);
  42729. }
  42730. if (camera.getScene().useRightHandedSystem) {
  42731. camera._localDirection.z *= -1;
  42732. }
  42733. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  42734. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  42735. camera.cameraDirection.addInPlace(camera._transformedDirection);
  42736. }
  42737. }
  42738. };
  42739. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  42740. return "FreeCameraKeyboardMoveInput";
  42741. };
  42742. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  42743. this._keys = [];
  42744. };
  42745. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  42746. return "keyboard";
  42747. };
  42748. __decorate([
  42749. BABYLON.serialize()
  42750. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  42751. __decorate([
  42752. BABYLON.serialize()
  42753. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  42754. __decorate([
  42755. BABYLON.serialize()
  42756. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  42757. __decorate([
  42758. BABYLON.serialize()
  42759. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  42760. return FreeCameraKeyboardMoveInput;
  42761. }());
  42762. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  42763. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  42764. })(BABYLON || (BABYLON = {}));
  42765. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  42766. var BABYLON;
  42767. (function (BABYLON) {
  42768. var FreeCameraInputsManager = /** @class */ (function (_super) {
  42769. __extends(FreeCameraInputsManager, _super);
  42770. function FreeCameraInputsManager(camera) {
  42771. return _super.call(this, camera) || this;
  42772. }
  42773. FreeCameraInputsManager.prototype.addKeyboard = function () {
  42774. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  42775. return this;
  42776. };
  42777. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  42778. if (touchEnabled === void 0) { touchEnabled = true; }
  42779. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  42780. return this;
  42781. };
  42782. FreeCameraInputsManager.prototype.addGamepad = function () {
  42783. this.add(new BABYLON.FreeCameraGamepadInput());
  42784. return this;
  42785. };
  42786. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  42787. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  42788. return this;
  42789. };
  42790. FreeCameraInputsManager.prototype.addTouch = function () {
  42791. this.add(new BABYLON.FreeCameraTouchInput());
  42792. return this;
  42793. };
  42794. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  42795. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  42796. return this;
  42797. };
  42798. return FreeCameraInputsManager;
  42799. }(BABYLON.CameraInputsManager));
  42800. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  42801. })(BABYLON || (BABYLON = {}));
  42802. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  42803. var BABYLON;
  42804. (function (BABYLON) {
  42805. var FreeCamera = /** @class */ (function (_super) {
  42806. __extends(FreeCamera, _super);
  42807. function FreeCamera(name, position, scene) {
  42808. var _this = _super.call(this, name, position, scene) || this;
  42809. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  42810. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  42811. _this.checkCollisions = false;
  42812. _this.applyGravity = false;
  42813. _this._needMoveForGravity = false;
  42814. _this._oldPosition = BABYLON.Vector3.Zero();
  42815. _this._diffPosition = BABYLON.Vector3.Zero();
  42816. _this._newPosition = BABYLON.Vector3.Zero();
  42817. // Collisions
  42818. _this._collisionMask = -1;
  42819. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  42820. if (collidedMesh === void 0) { collidedMesh = null; }
  42821. //TODO move this to the collision coordinator!
  42822. if (_this.getScene().workerCollisions)
  42823. newPosition.multiplyInPlace(_this._collider._radius);
  42824. var updatePosition = function (newPos) {
  42825. _this._newPosition.copyFrom(newPos);
  42826. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  42827. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  42828. _this.position.addInPlace(_this._diffPosition);
  42829. if (_this.onCollide && collidedMesh) {
  42830. _this.onCollide(collidedMesh);
  42831. }
  42832. }
  42833. };
  42834. updatePosition(newPosition);
  42835. };
  42836. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  42837. _this.inputs.addKeyboard().addMouse();
  42838. return _this;
  42839. }
  42840. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  42841. //-- begin properties for backward compatibility for inputs
  42842. /**
  42843. * Gets the input sensibility for a mouse input. (default is 2000.0)
  42844. * Higher values reduce sensitivity.
  42845. */
  42846. get: function () {
  42847. var mouse = this.inputs.attached["mouse"];
  42848. if (mouse)
  42849. return mouse.angularSensibility;
  42850. return 0;
  42851. },
  42852. /**
  42853. * Sets the input sensibility for a mouse input. (default is 2000.0)
  42854. * Higher values reduce sensitivity.
  42855. */
  42856. set: function (value) {
  42857. var mouse = this.inputs.attached["mouse"];
  42858. if (mouse)
  42859. mouse.angularSensibility = value;
  42860. },
  42861. enumerable: true,
  42862. configurable: true
  42863. });
  42864. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  42865. get: function () {
  42866. var keyboard = this.inputs.attached["keyboard"];
  42867. if (keyboard)
  42868. return keyboard.keysUp;
  42869. return [];
  42870. },
  42871. set: function (value) {
  42872. var keyboard = this.inputs.attached["keyboard"];
  42873. if (keyboard)
  42874. keyboard.keysUp = value;
  42875. },
  42876. enumerable: true,
  42877. configurable: true
  42878. });
  42879. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  42880. get: function () {
  42881. var keyboard = this.inputs.attached["keyboard"];
  42882. if (keyboard)
  42883. return keyboard.keysDown;
  42884. return [];
  42885. },
  42886. set: function (value) {
  42887. var keyboard = this.inputs.attached["keyboard"];
  42888. if (keyboard)
  42889. keyboard.keysDown = value;
  42890. },
  42891. enumerable: true,
  42892. configurable: true
  42893. });
  42894. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  42895. get: function () {
  42896. var keyboard = this.inputs.attached["keyboard"];
  42897. if (keyboard)
  42898. return keyboard.keysLeft;
  42899. return [];
  42900. },
  42901. set: function (value) {
  42902. var keyboard = this.inputs.attached["keyboard"];
  42903. if (keyboard)
  42904. keyboard.keysLeft = value;
  42905. },
  42906. enumerable: true,
  42907. configurable: true
  42908. });
  42909. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  42910. get: function () {
  42911. var keyboard = this.inputs.attached["keyboard"];
  42912. if (keyboard)
  42913. return keyboard.keysRight;
  42914. return [];
  42915. },
  42916. set: function (value) {
  42917. var keyboard = this.inputs.attached["keyboard"];
  42918. if (keyboard)
  42919. keyboard.keysRight = value;
  42920. },
  42921. enumerable: true,
  42922. configurable: true
  42923. });
  42924. // Controls
  42925. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  42926. this.inputs.attachElement(element, noPreventDefault);
  42927. };
  42928. FreeCamera.prototype.detachControl = function (element) {
  42929. this.inputs.detachElement(element);
  42930. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  42931. this.cameraRotation = new BABYLON.Vector2(0, 0);
  42932. };
  42933. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  42934. get: function () {
  42935. return this._collisionMask;
  42936. },
  42937. set: function (mask) {
  42938. this._collisionMask = !isNaN(mask) ? mask : -1;
  42939. },
  42940. enumerable: true,
  42941. configurable: true
  42942. });
  42943. FreeCamera.prototype._collideWithWorld = function (displacement) {
  42944. var globalPosition;
  42945. if (this.parent) {
  42946. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  42947. }
  42948. else {
  42949. globalPosition = this.position;
  42950. }
  42951. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  42952. this._oldPosition.addInPlace(this.ellipsoidOffset);
  42953. if (!this._collider) {
  42954. this._collider = new BABYLON.Collider();
  42955. }
  42956. this._collider._radius = this.ellipsoid;
  42957. this._collider.collisionMask = this._collisionMask;
  42958. //no need for clone, as long as gravity is not on.
  42959. var actualDisplacement = displacement;
  42960. //add gravity to the direction to prevent the dual-collision checking
  42961. if (this.applyGravity) {
  42962. //this prevents mending with cameraDirection, a global variable of the free camera class.
  42963. actualDisplacement = displacement.add(this.getScene().gravity);
  42964. }
  42965. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  42966. };
  42967. FreeCamera.prototype._checkInputs = function () {
  42968. if (!this._localDirection) {
  42969. this._localDirection = BABYLON.Vector3.Zero();
  42970. this._transformedDirection = BABYLON.Vector3.Zero();
  42971. }
  42972. this.inputs.checkInputs();
  42973. _super.prototype._checkInputs.call(this);
  42974. };
  42975. FreeCamera.prototype._decideIfNeedsToMove = function () {
  42976. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  42977. };
  42978. FreeCamera.prototype._updatePosition = function () {
  42979. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  42980. this._collideWithWorld(this.cameraDirection);
  42981. }
  42982. else {
  42983. _super.prototype._updatePosition.call(this);
  42984. }
  42985. };
  42986. FreeCamera.prototype.dispose = function () {
  42987. this.inputs.clear();
  42988. _super.prototype.dispose.call(this);
  42989. };
  42990. FreeCamera.prototype.getClassName = function () {
  42991. return "FreeCamera";
  42992. };
  42993. __decorate([
  42994. BABYLON.serializeAsVector3()
  42995. ], FreeCamera.prototype, "ellipsoid", void 0);
  42996. __decorate([
  42997. BABYLON.serializeAsVector3()
  42998. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  42999. __decorate([
  43000. BABYLON.serialize()
  43001. ], FreeCamera.prototype, "checkCollisions", void 0);
  43002. __decorate([
  43003. BABYLON.serialize()
  43004. ], FreeCamera.prototype, "applyGravity", void 0);
  43005. return FreeCamera;
  43006. }(BABYLON.TargetCamera));
  43007. BABYLON.FreeCamera = FreeCamera;
  43008. })(BABYLON || (BABYLON = {}));
  43009. //# sourceMappingURL=babylon.freeCamera.js.map
  43010. var BABYLON;
  43011. (function (BABYLON) {
  43012. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  43013. function ArcRotateCameraKeyboardMoveInput() {
  43014. this._keys = new Array();
  43015. this.keysUp = [38];
  43016. this.keysDown = [40];
  43017. this.keysLeft = [37];
  43018. this.keysRight = [39];
  43019. this.keysReset = [220];
  43020. this.panningSensibility = 50.0;
  43021. this.zoomingSensibility = 25.0;
  43022. this.useAltToZoom = true;
  43023. }
  43024. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  43025. var _this = this;
  43026. if (this._onCanvasBlurObserver) {
  43027. return;
  43028. }
  43029. this._scene = this.camera.getScene();
  43030. this._engine = this._scene.getEngine();
  43031. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  43032. _this._keys = [];
  43033. });
  43034. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  43035. var evt = info.event;
  43036. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  43037. _this._ctrlPressed = evt.ctrlKey;
  43038. _this._altPressed = evt.altKey;
  43039. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  43040. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  43041. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  43042. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  43043. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  43044. var index = _this._keys.indexOf(evt.keyCode);
  43045. if (index === -1) {
  43046. _this._keys.push(evt.keyCode);
  43047. }
  43048. if (evt.preventDefault) {
  43049. if (!noPreventDefault) {
  43050. evt.preventDefault();
  43051. }
  43052. }
  43053. }
  43054. }
  43055. else {
  43056. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  43057. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  43058. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  43059. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  43060. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  43061. var index = _this._keys.indexOf(evt.keyCode);
  43062. if (index >= 0) {
  43063. _this._keys.splice(index, 1);
  43064. }
  43065. if (evt.preventDefault) {
  43066. if (!noPreventDefault) {
  43067. evt.preventDefault();
  43068. }
  43069. }
  43070. }
  43071. }
  43072. });
  43073. };
  43074. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  43075. if (this._scene) {
  43076. if (this._onKeyboardObserver) {
  43077. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  43078. }
  43079. if (this._onCanvasBlurObserver) {
  43080. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  43081. }
  43082. this._onKeyboardObserver = null;
  43083. this._onCanvasBlurObserver = null;
  43084. }
  43085. this._keys = [];
  43086. };
  43087. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  43088. if (this._onKeyboardObserver) {
  43089. var camera = this.camera;
  43090. for (var index = 0; index < this._keys.length; index++) {
  43091. var keyCode = this._keys[index];
  43092. if (this.keysLeft.indexOf(keyCode) !== -1) {
  43093. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  43094. camera.inertialPanningX -= 1 / this.panningSensibility;
  43095. }
  43096. else {
  43097. camera.inertialAlphaOffset -= 0.01;
  43098. }
  43099. }
  43100. else if (this.keysUp.indexOf(keyCode) !== -1) {
  43101. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  43102. camera.inertialPanningY += 1 / this.panningSensibility;
  43103. }
  43104. else if (this._altPressed && this.useAltToZoom) {
  43105. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  43106. }
  43107. else {
  43108. camera.inertialBetaOffset -= 0.01;
  43109. }
  43110. }
  43111. else if (this.keysRight.indexOf(keyCode) !== -1) {
  43112. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  43113. camera.inertialPanningX += 1 / this.panningSensibility;
  43114. }
  43115. else {
  43116. camera.inertialAlphaOffset += 0.01;
  43117. }
  43118. }
  43119. else if (this.keysDown.indexOf(keyCode) !== -1) {
  43120. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  43121. camera.inertialPanningY -= 1 / this.panningSensibility;
  43122. }
  43123. else if (this._altPressed && this.useAltToZoom) {
  43124. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  43125. }
  43126. else {
  43127. camera.inertialBetaOffset += 0.01;
  43128. }
  43129. }
  43130. else if (this.keysReset.indexOf(keyCode) !== -1) {
  43131. camera.restoreState();
  43132. }
  43133. }
  43134. }
  43135. };
  43136. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  43137. return "ArcRotateCameraKeyboardMoveInput";
  43138. };
  43139. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  43140. return "keyboard";
  43141. };
  43142. __decorate([
  43143. BABYLON.serialize()
  43144. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  43145. __decorate([
  43146. BABYLON.serialize()
  43147. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  43148. __decorate([
  43149. BABYLON.serialize()
  43150. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  43151. __decorate([
  43152. BABYLON.serialize()
  43153. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  43154. __decorate([
  43155. BABYLON.serialize()
  43156. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  43157. __decorate([
  43158. BABYLON.serialize()
  43159. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  43160. __decorate([
  43161. BABYLON.serialize()
  43162. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  43163. __decorate([
  43164. BABYLON.serialize()
  43165. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  43166. return ArcRotateCameraKeyboardMoveInput;
  43167. }());
  43168. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  43169. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  43170. })(BABYLON || (BABYLON = {}));
  43171. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  43172. var BABYLON;
  43173. (function (BABYLON) {
  43174. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  43175. function ArcRotateCameraMouseWheelInput() {
  43176. this.wheelPrecision = 3.0;
  43177. /**
  43178. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  43179. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  43180. */
  43181. this.wheelDeltaPercentage = 0;
  43182. }
  43183. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  43184. var _this = this;
  43185. this._wheel = function (p, s) {
  43186. //sanity check - this should be a PointerWheel event.
  43187. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  43188. return;
  43189. var event = p.event;
  43190. var delta = 0;
  43191. if (event.wheelDelta) {
  43192. delta = _this.wheelDeltaPercentage ? (event.wheelDelta * 0.01) * _this.camera.radius * _this.wheelDeltaPercentage : event.wheelDelta / (_this.wheelPrecision * 40);
  43193. }
  43194. else if (event.detail) {
  43195. delta = -event.detail / _this.wheelPrecision;
  43196. }
  43197. if (delta)
  43198. _this.camera.inertialRadiusOffset += delta;
  43199. if (event.preventDefault) {
  43200. if (!noPreventDefault) {
  43201. event.preventDefault();
  43202. }
  43203. }
  43204. };
  43205. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  43206. };
  43207. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  43208. if (this._observer && element) {
  43209. this.camera.getScene().onPointerObservable.remove(this._observer);
  43210. this._observer = null;
  43211. this._wheel = null;
  43212. }
  43213. };
  43214. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  43215. return "ArcRotateCameraMouseWheelInput";
  43216. };
  43217. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  43218. return "mousewheel";
  43219. };
  43220. __decorate([
  43221. BABYLON.serialize()
  43222. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  43223. __decorate([
  43224. BABYLON.serialize()
  43225. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  43226. return ArcRotateCameraMouseWheelInput;
  43227. }());
  43228. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  43229. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  43230. })(BABYLON || (BABYLON = {}));
  43231. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  43232. var BABYLON;
  43233. (function (BABYLON) {
  43234. var ArcRotateCameraPointersInput = /** @class */ (function () {
  43235. function ArcRotateCameraPointersInput() {
  43236. this.buttons = [0, 1, 2];
  43237. this.angularSensibilityX = 1000.0;
  43238. this.angularSensibilityY = 1000.0;
  43239. this.pinchPrecision = 12.0;
  43240. /**
  43241. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  43242. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  43243. */
  43244. this.pinchDeltaPercentage = 0;
  43245. this.panningSensibility = 1000.0;
  43246. this.multiTouchPanning = true;
  43247. this.multiTouchPanAndZoom = true;
  43248. this._isPanClick = false;
  43249. this.pinchInwards = true;
  43250. }
  43251. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  43252. var _this = this;
  43253. var engine = this.camera.getEngine();
  43254. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  43255. var pointA = null;
  43256. var pointB = null;
  43257. var previousPinchSquaredDistance = 0;
  43258. var initialDistance = 0;
  43259. var twoFingerActivityCount = 0;
  43260. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  43261. this._pointerInput = function (p, s) {
  43262. var evt = p.event;
  43263. var isTouch = p.event.pointerType === "touch";
  43264. if (engine.isInVRExclusivePointerMode) {
  43265. return;
  43266. }
  43267. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  43268. return;
  43269. }
  43270. var srcElement = (evt.srcElement || evt.target);
  43271. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  43272. try {
  43273. srcElement.setPointerCapture(evt.pointerId);
  43274. }
  43275. catch (e) {
  43276. //Nothing to do with the error. Execution will continue.
  43277. }
  43278. // Manage panning with pan button click
  43279. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  43280. // manage pointers
  43281. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  43282. if (pointA === null) {
  43283. pointA = cacheSoloPointer;
  43284. }
  43285. else if (pointB === null) {
  43286. pointB = cacheSoloPointer;
  43287. }
  43288. if (!noPreventDefault) {
  43289. evt.preventDefault();
  43290. element.focus();
  43291. }
  43292. }
  43293. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  43294. _this.camera.restoreState();
  43295. }
  43296. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  43297. try {
  43298. srcElement.releasePointerCapture(evt.pointerId);
  43299. }
  43300. catch (e) {
  43301. //Nothing to do with the error.
  43302. }
  43303. cacheSoloPointer = null;
  43304. previousPinchSquaredDistance = 0;
  43305. previousMultiTouchPanPosition.isPaning = false;
  43306. previousMultiTouchPanPosition.isPinching = false;
  43307. twoFingerActivityCount = 0;
  43308. initialDistance = 0;
  43309. if (!isTouch) {
  43310. pointB = null; // Mouse and pen are mono pointer
  43311. }
  43312. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  43313. //but emptying completly pointers collection is required to fix a bug on iPhone :
  43314. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  43315. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  43316. if (engine.badOS) {
  43317. pointA = pointB = null;
  43318. }
  43319. else {
  43320. //only remove the impacted pointer in case of multitouch allowing on most
  43321. //platforms switching from rotate to zoom and pan seamlessly.
  43322. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  43323. pointA = pointB;
  43324. pointB = null;
  43325. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  43326. }
  43327. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  43328. pointB = null;
  43329. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  43330. }
  43331. else {
  43332. pointA = pointB = null;
  43333. }
  43334. }
  43335. if (!noPreventDefault) {
  43336. evt.preventDefault();
  43337. }
  43338. }
  43339. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  43340. if (!noPreventDefault) {
  43341. evt.preventDefault();
  43342. }
  43343. // One button down
  43344. if (pointA && pointB === null && cacheSoloPointer) {
  43345. if (_this.panningSensibility !== 0 &&
  43346. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  43347. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  43348. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  43349. }
  43350. else {
  43351. var offsetX = evt.clientX - cacheSoloPointer.x;
  43352. var offsetY = evt.clientY - cacheSoloPointer.y;
  43353. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  43354. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  43355. }
  43356. cacheSoloPointer.x = evt.clientX;
  43357. cacheSoloPointer.y = evt.clientY;
  43358. }
  43359. else if (pointA && pointB) {
  43360. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  43361. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  43362. ed.x = evt.clientX;
  43363. ed.y = evt.clientY;
  43364. var direction = _this.pinchInwards ? 1 : -1;
  43365. var distX = pointA.x - pointB.x;
  43366. var distY = pointA.y - pointB.y;
  43367. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  43368. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  43369. if (previousPinchSquaredDistance === 0) {
  43370. initialDistance = pinchDistance;
  43371. previousPinchSquaredDistance = pinchSquaredDistance;
  43372. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  43373. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  43374. return;
  43375. }
  43376. if (_this.multiTouchPanAndZoom) {
  43377. if (_this.pinchDeltaPercentage) {
  43378. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  43379. }
  43380. else {
  43381. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  43382. (_this.pinchPrecision *
  43383. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  43384. direction);
  43385. }
  43386. if (_this.panningSensibility !== 0) {
  43387. var pointersCenterX = (pointA.x + pointB.x) / 2;
  43388. var pointersCenterY = (pointA.y + pointB.y) / 2;
  43389. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  43390. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  43391. previousMultiTouchPanPosition.x = pointersCenterX;
  43392. previousMultiTouchPanPosition.y = pointersCenterY;
  43393. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  43394. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  43395. }
  43396. }
  43397. else {
  43398. twoFingerActivityCount++;
  43399. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  43400. if (_this.pinchDeltaPercentage) {
  43401. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  43402. }
  43403. else {
  43404. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  43405. (_this.pinchPrecision *
  43406. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  43407. direction);
  43408. }
  43409. previousMultiTouchPanPosition.isPaning = false;
  43410. previousMultiTouchPanPosition.isPinching = true;
  43411. }
  43412. else {
  43413. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  43414. if (!previousMultiTouchPanPosition.isPaning) {
  43415. previousMultiTouchPanPosition.isPaning = true;
  43416. previousMultiTouchPanPosition.isPinching = false;
  43417. previousMultiTouchPanPosition.x = ed.x;
  43418. previousMultiTouchPanPosition.y = ed.y;
  43419. return;
  43420. }
  43421. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  43422. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  43423. }
  43424. }
  43425. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  43426. previousMultiTouchPanPosition.x = ed.x;
  43427. previousMultiTouchPanPosition.y = ed.y;
  43428. }
  43429. }
  43430. previousPinchSquaredDistance = pinchSquaredDistance;
  43431. }
  43432. }
  43433. };
  43434. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  43435. this._onContextMenu = function (evt) {
  43436. evt.preventDefault();
  43437. };
  43438. if (!this.camera._useCtrlForPanning) {
  43439. element.addEventListener("contextmenu", this._onContextMenu, false);
  43440. }
  43441. this._onLostFocus = function () {
  43442. //this._keys = [];
  43443. pointA = pointB = null;
  43444. previousPinchSquaredDistance = 0;
  43445. previousMultiTouchPanPosition.isPaning = false;
  43446. previousMultiTouchPanPosition.isPinching = false;
  43447. twoFingerActivityCount = 0;
  43448. cacheSoloPointer = null;
  43449. initialDistance = 0;
  43450. };
  43451. this._onMouseMove = function (evt) {
  43452. if (!engine.isPointerLock) {
  43453. return;
  43454. }
  43455. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  43456. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  43457. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  43458. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  43459. if (!noPreventDefault) {
  43460. evt.preventDefault();
  43461. }
  43462. };
  43463. this._onGestureStart = function (e) {
  43464. if (window.MSGesture === undefined) {
  43465. return;
  43466. }
  43467. if (!_this._MSGestureHandler) {
  43468. _this._MSGestureHandler = new MSGesture();
  43469. _this._MSGestureHandler.target = element;
  43470. }
  43471. _this._MSGestureHandler.addPointer(e.pointerId);
  43472. };
  43473. this._onGesture = function (e) {
  43474. _this.camera.radius *= e.scale;
  43475. if (e.preventDefault) {
  43476. if (!noPreventDefault) {
  43477. e.stopPropagation();
  43478. e.preventDefault();
  43479. }
  43480. }
  43481. };
  43482. element.addEventListener("mousemove", this._onMouseMove, false);
  43483. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  43484. element.addEventListener("MSGestureChange", this._onGesture, false);
  43485. BABYLON.Tools.RegisterTopRootEvents([
  43486. { name: "blur", handler: this._onLostFocus }
  43487. ]);
  43488. };
  43489. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  43490. if (this._onLostFocus) {
  43491. BABYLON.Tools.UnregisterTopRootEvents([
  43492. { name: "blur", handler: this._onLostFocus }
  43493. ]);
  43494. }
  43495. if (element && this._observer) {
  43496. this.camera.getScene().onPointerObservable.remove(this._observer);
  43497. this._observer = null;
  43498. if (this._onContextMenu) {
  43499. element.removeEventListener("contextmenu", this._onContextMenu);
  43500. }
  43501. if (this._onMouseMove) {
  43502. element.removeEventListener("mousemove", this._onMouseMove);
  43503. }
  43504. if (this._onGestureStart) {
  43505. element.removeEventListener("MSPointerDown", this._onGestureStart);
  43506. }
  43507. if (this._onGesture) {
  43508. element.removeEventListener("MSGestureChange", this._onGesture);
  43509. }
  43510. this._isPanClick = false;
  43511. this.pinchInwards = true;
  43512. this._onMouseMove = null;
  43513. this._onGestureStart = null;
  43514. this._onGesture = null;
  43515. this._MSGestureHandler = null;
  43516. this._onLostFocus = null;
  43517. this._onContextMenu = null;
  43518. }
  43519. };
  43520. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  43521. return "ArcRotateCameraPointersInput";
  43522. };
  43523. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  43524. return "pointers";
  43525. };
  43526. __decorate([
  43527. BABYLON.serialize()
  43528. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  43529. __decorate([
  43530. BABYLON.serialize()
  43531. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  43532. __decorate([
  43533. BABYLON.serialize()
  43534. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  43535. __decorate([
  43536. BABYLON.serialize()
  43537. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  43538. __decorate([
  43539. BABYLON.serialize()
  43540. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  43541. __decorate([
  43542. BABYLON.serialize()
  43543. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  43544. __decorate([
  43545. BABYLON.serialize()
  43546. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  43547. __decorate([
  43548. BABYLON.serialize()
  43549. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  43550. return ArcRotateCameraPointersInput;
  43551. }());
  43552. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  43553. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  43554. })(BABYLON || (BABYLON = {}));
  43555. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  43556. var BABYLON;
  43557. (function (BABYLON) {
  43558. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  43559. __extends(ArcRotateCameraInputsManager, _super);
  43560. function ArcRotateCameraInputsManager(camera) {
  43561. return _super.call(this, camera) || this;
  43562. }
  43563. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  43564. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  43565. return this;
  43566. };
  43567. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  43568. this.add(new BABYLON.ArcRotateCameraPointersInput());
  43569. return this;
  43570. };
  43571. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  43572. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  43573. return this;
  43574. };
  43575. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  43576. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  43577. return this;
  43578. };
  43579. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  43580. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  43581. return this;
  43582. };
  43583. return ArcRotateCameraInputsManager;
  43584. }(BABYLON.CameraInputsManager));
  43585. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  43586. })(BABYLON || (BABYLON = {}));
  43587. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  43588. var BABYLON;
  43589. (function (BABYLON) {
  43590. var ArcRotateCamera = /** @class */ (function (_super) {
  43591. __extends(ArcRotateCamera, _super);
  43592. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  43593. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  43594. _this.inertialAlphaOffset = 0;
  43595. _this.inertialBetaOffset = 0;
  43596. _this.inertialRadiusOffset = 0;
  43597. _this.lowerAlphaLimit = null;
  43598. _this.upperAlphaLimit = null;
  43599. _this.lowerBetaLimit = 0.01;
  43600. _this.upperBetaLimit = Math.PI;
  43601. _this.lowerRadiusLimit = null;
  43602. _this.upperRadiusLimit = null;
  43603. _this.inertialPanningX = 0;
  43604. _this.inertialPanningY = 0;
  43605. _this.pinchToPanMaxDistance = 20;
  43606. _this.panningDistanceLimit = null;
  43607. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  43608. _this.panningInertia = 0.9;
  43609. //-- end properties for backward compatibility for inputs
  43610. _this.zoomOnFactor = 1;
  43611. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  43612. _this.allowUpsideDown = true;
  43613. _this._viewMatrix = new BABYLON.Matrix();
  43614. // Panning
  43615. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  43616. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  43617. _this.checkCollisions = false;
  43618. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  43619. _this._previousPosition = BABYLON.Vector3.Zero();
  43620. _this._collisionVelocity = BABYLON.Vector3.Zero();
  43621. _this._newPosition = BABYLON.Vector3.Zero();
  43622. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  43623. if (collidedMesh === void 0) { collidedMesh = null; }
  43624. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  43625. newPosition.multiplyInPlace(_this._collider._radius);
  43626. }
  43627. if (!collidedMesh) {
  43628. _this._previousPosition.copyFrom(_this.position);
  43629. }
  43630. else {
  43631. _this.setPosition(newPosition);
  43632. if (_this.onCollide) {
  43633. _this.onCollide(collidedMesh);
  43634. }
  43635. }
  43636. // Recompute because of constraints
  43637. var cosa = Math.cos(_this.alpha);
  43638. var sina = Math.sin(_this.alpha);
  43639. var cosb = Math.cos(_this.beta);
  43640. var sinb = Math.sin(_this.beta);
  43641. if (sinb === 0) {
  43642. sinb = 0.0001;
  43643. }
  43644. var target = _this._getTargetPosition();
  43645. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  43646. _this.position.copyFrom(_this._newPosition);
  43647. var up = _this.upVector;
  43648. if (_this.allowUpsideDown && _this.beta < 0) {
  43649. up = up.clone();
  43650. up = up.negate();
  43651. }
  43652. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  43653. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  43654. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  43655. _this._collisionTriggered = false;
  43656. };
  43657. _this._target = BABYLON.Vector3.Zero();
  43658. if (target) {
  43659. _this.setTarget(target);
  43660. }
  43661. _this.alpha = alpha;
  43662. _this.beta = beta;
  43663. _this.radius = radius;
  43664. _this.getViewMatrix();
  43665. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  43666. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  43667. return _this;
  43668. }
  43669. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  43670. get: function () {
  43671. return this._target;
  43672. },
  43673. set: function (value) {
  43674. this.setTarget(value);
  43675. },
  43676. enumerable: true,
  43677. configurable: true
  43678. });
  43679. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  43680. //-- begin properties for backward compatibility for inputs
  43681. get: function () {
  43682. var pointers = this.inputs.attached["pointers"];
  43683. if (pointers)
  43684. return pointers.angularSensibilityX;
  43685. return 0;
  43686. },
  43687. set: function (value) {
  43688. var pointers = this.inputs.attached["pointers"];
  43689. if (pointers) {
  43690. pointers.angularSensibilityX = value;
  43691. }
  43692. },
  43693. enumerable: true,
  43694. configurable: true
  43695. });
  43696. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  43697. get: function () {
  43698. var pointers = this.inputs.attached["pointers"];
  43699. if (pointers)
  43700. return pointers.angularSensibilityY;
  43701. return 0;
  43702. },
  43703. set: function (value) {
  43704. var pointers = this.inputs.attached["pointers"];
  43705. if (pointers) {
  43706. pointers.angularSensibilityY = value;
  43707. }
  43708. },
  43709. enumerable: true,
  43710. configurable: true
  43711. });
  43712. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  43713. get: function () {
  43714. var pointers = this.inputs.attached["pointers"];
  43715. if (pointers)
  43716. return pointers.pinchPrecision;
  43717. return 0;
  43718. },
  43719. set: function (value) {
  43720. var pointers = this.inputs.attached["pointers"];
  43721. if (pointers) {
  43722. pointers.pinchPrecision = value;
  43723. }
  43724. },
  43725. enumerable: true,
  43726. configurable: true
  43727. });
  43728. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  43729. get: function () {
  43730. var pointers = this.inputs.attached["pointers"];
  43731. if (pointers)
  43732. return pointers.pinchDeltaPercentage;
  43733. return 0;
  43734. },
  43735. set: function (value) {
  43736. var pointers = this.inputs.attached["pointers"];
  43737. if (pointers) {
  43738. pointers.pinchDeltaPercentage = value;
  43739. }
  43740. },
  43741. enumerable: true,
  43742. configurable: true
  43743. });
  43744. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  43745. get: function () {
  43746. var pointers = this.inputs.attached["pointers"];
  43747. if (pointers)
  43748. return pointers.panningSensibility;
  43749. return 0;
  43750. },
  43751. set: function (value) {
  43752. var pointers = this.inputs.attached["pointers"];
  43753. if (pointers) {
  43754. pointers.panningSensibility = value;
  43755. }
  43756. },
  43757. enumerable: true,
  43758. configurable: true
  43759. });
  43760. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  43761. get: function () {
  43762. var keyboard = this.inputs.attached["keyboard"];
  43763. if (keyboard)
  43764. return keyboard.keysUp;
  43765. return [];
  43766. },
  43767. set: function (value) {
  43768. var keyboard = this.inputs.attached["keyboard"];
  43769. if (keyboard)
  43770. keyboard.keysUp = value;
  43771. },
  43772. enumerable: true,
  43773. configurable: true
  43774. });
  43775. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  43776. get: function () {
  43777. var keyboard = this.inputs.attached["keyboard"];
  43778. if (keyboard)
  43779. return keyboard.keysDown;
  43780. return [];
  43781. },
  43782. set: function (value) {
  43783. var keyboard = this.inputs.attached["keyboard"];
  43784. if (keyboard)
  43785. keyboard.keysDown = value;
  43786. },
  43787. enumerable: true,
  43788. configurable: true
  43789. });
  43790. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  43791. get: function () {
  43792. var keyboard = this.inputs.attached["keyboard"];
  43793. if (keyboard)
  43794. return keyboard.keysLeft;
  43795. return [];
  43796. },
  43797. set: function (value) {
  43798. var keyboard = this.inputs.attached["keyboard"];
  43799. if (keyboard)
  43800. keyboard.keysLeft = value;
  43801. },
  43802. enumerable: true,
  43803. configurable: true
  43804. });
  43805. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  43806. get: function () {
  43807. var keyboard = this.inputs.attached["keyboard"];
  43808. if (keyboard)
  43809. return keyboard.keysRight;
  43810. return [];
  43811. },
  43812. set: function (value) {
  43813. var keyboard = this.inputs.attached["keyboard"];
  43814. if (keyboard)
  43815. keyboard.keysRight = value;
  43816. },
  43817. enumerable: true,
  43818. configurable: true
  43819. });
  43820. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  43821. get: function () {
  43822. var mousewheel = this.inputs.attached["mousewheel"];
  43823. if (mousewheel)
  43824. return mousewheel.wheelPrecision;
  43825. return 0;
  43826. },
  43827. set: function (value) {
  43828. var mousewheel = this.inputs.attached["mousewheel"];
  43829. if (mousewheel)
  43830. mousewheel.wheelPrecision = value;
  43831. },
  43832. enumerable: true,
  43833. configurable: true
  43834. });
  43835. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  43836. get: function () {
  43837. var mousewheel = this.inputs.attached["mousewheel"];
  43838. if (mousewheel)
  43839. return mousewheel.wheelDeltaPercentage;
  43840. return 0;
  43841. },
  43842. set: function (value) {
  43843. var mousewheel = this.inputs.attached["mousewheel"];
  43844. if (mousewheel)
  43845. mousewheel.wheelDeltaPercentage = value;
  43846. },
  43847. enumerable: true,
  43848. configurable: true
  43849. });
  43850. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  43851. get: function () {
  43852. return this._bouncingBehavior;
  43853. },
  43854. enumerable: true,
  43855. configurable: true
  43856. });
  43857. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  43858. get: function () {
  43859. return this._bouncingBehavior != null;
  43860. },
  43861. set: function (value) {
  43862. if (value === this.useBouncingBehavior) {
  43863. return;
  43864. }
  43865. if (value) {
  43866. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  43867. this.addBehavior(this._bouncingBehavior);
  43868. }
  43869. else if (this._bouncingBehavior) {
  43870. this.removeBehavior(this._bouncingBehavior);
  43871. this._bouncingBehavior = null;
  43872. }
  43873. },
  43874. enumerable: true,
  43875. configurable: true
  43876. });
  43877. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  43878. get: function () {
  43879. return this._framingBehavior;
  43880. },
  43881. enumerable: true,
  43882. configurable: true
  43883. });
  43884. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  43885. get: function () {
  43886. return this._framingBehavior != null;
  43887. },
  43888. set: function (value) {
  43889. if (value === this.useFramingBehavior) {
  43890. return;
  43891. }
  43892. if (value) {
  43893. this._framingBehavior = new BABYLON.FramingBehavior();
  43894. this.addBehavior(this._framingBehavior);
  43895. }
  43896. else if (this._framingBehavior) {
  43897. this.removeBehavior(this._framingBehavior);
  43898. this._framingBehavior = null;
  43899. }
  43900. },
  43901. enumerable: true,
  43902. configurable: true
  43903. });
  43904. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  43905. get: function () {
  43906. return this._autoRotationBehavior;
  43907. },
  43908. enumerable: true,
  43909. configurable: true
  43910. });
  43911. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  43912. get: function () {
  43913. return this._autoRotationBehavior != null;
  43914. },
  43915. set: function (value) {
  43916. if (value === this.useAutoRotationBehavior) {
  43917. return;
  43918. }
  43919. if (value) {
  43920. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  43921. this.addBehavior(this._autoRotationBehavior);
  43922. }
  43923. else if (this._autoRotationBehavior) {
  43924. this.removeBehavior(this._autoRotationBehavior);
  43925. this._autoRotationBehavior = null;
  43926. }
  43927. },
  43928. enumerable: true,
  43929. configurable: true
  43930. });
  43931. // Cache
  43932. ArcRotateCamera.prototype._initCache = function () {
  43933. _super.prototype._initCache.call(this);
  43934. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  43935. this._cache.alpha = undefined;
  43936. this._cache.beta = undefined;
  43937. this._cache.radius = undefined;
  43938. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  43939. };
  43940. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  43941. if (!ignoreParentClass) {
  43942. _super.prototype._updateCache.call(this);
  43943. }
  43944. this._cache._target.copyFrom(this._getTargetPosition());
  43945. this._cache.alpha = this.alpha;
  43946. this._cache.beta = this.beta;
  43947. this._cache.radius = this.radius;
  43948. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  43949. };
  43950. ArcRotateCamera.prototype._getTargetPosition = function () {
  43951. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  43952. var pos = this._targetHost.getAbsolutePosition();
  43953. if (this._targetBoundingCenter) {
  43954. pos.addToRef(this._targetBoundingCenter, this._target);
  43955. }
  43956. else {
  43957. this._target.copyFrom(pos);
  43958. }
  43959. }
  43960. var lockedTargetPosition = this._getLockedTargetPosition();
  43961. if (lockedTargetPosition) {
  43962. return lockedTargetPosition;
  43963. }
  43964. return this._target;
  43965. };
  43966. ArcRotateCamera.prototype.storeState = function () {
  43967. this._storedAlpha = this.alpha;
  43968. this._storedBeta = this.beta;
  43969. this._storedRadius = this.radius;
  43970. this._storedTarget = this._getTargetPosition().clone();
  43971. return _super.prototype.storeState.call(this);
  43972. };
  43973. /**
  43974. * Restored camera state. You must call storeState() first
  43975. */
  43976. ArcRotateCamera.prototype._restoreStateValues = function () {
  43977. if (!_super.prototype._restoreStateValues.call(this)) {
  43978. return false;
  43979. }
  43980. this.alpha = this._storedAlpha;
  43981. this.beta = this._storedBeta;
  43982. this.radius = this._storedRadius;
  43983. this.setTarget(this._storedTarget.clone());
  43984. this.inertialAlphaOffset = 0;
  43985. this.inertialBetaOffset = 0;
  43986. this.inertialRadiusOffset = 0;
  43987. this.inertialPanningX = 0;
  43988. this.inertialPanningY = 0;
  43989. return true;
  43990. };
  43991. // Synchronized
  43992. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  43993. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  43994. return false;
  43995. return this._cache._target.equals(this._getTargetPosition())
  43996. && this._cache.alpha === this.alpha
  43997. && this._cache.beta === this.beta
  43998. && this._cache.radius === this.radius
  43999. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  44000. };
  44001. // Methods
  44002. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  44003. var _this = this;
  44004. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  44005. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  44006. this._useCtrlForPanning = useCtrlForPanning;
  44007. this._panningMouseButton = panningMouseButton;
  44008. this.inputs.attachElement(element, noPreventDefault);
  44009. this._reset = function () {
  44010. _this.inertialAlphaOffset = 0;
  44011. _this.inertialBetaOffset = 0;
  44012. _this.inertialRadiusOffset = 0;
  44013. _this.inertialPanningX = 0;
  44014. _this.inertialPanningY = 0;
  44015. };
  44016. };
  44017. ArcRotateCamera.prototype.detachControl = function (element) {
  44018. this.inputs.detachElement(element);
  44019. if (this._reset) {
  44020. this._reset();
  44021. }
  44022. };
  44023. ArcRotateCamera.prototype._checkInputs = function () {
  44024. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  44025. if (this._collisionTriggered) {
  44026. return;
  44027. }
  44028. this.inputs.checkInputs();
  44029. // Inertia
  44030. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  44031. if (this.getScene().useRightHandedSystem) {
  44032. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  44033. }
  44034. else {
  44035. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  44036. }
  44037. this.beta += this.inertialBetaOffset;
  44038. this.radius -= this.inertialRadiusOffset;
  44039. this.inertialAlphaOffset *= this.inertia;
  44040. this.inertialBetaOffset *= this.inertia;
  44041. this.inertialRadiusOffset *= this.inertia;
  44042. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  44043. this.inertialAlphaOffset = 0;
  44044. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  44045. this.inertialBetaOffset = 0;
  44046. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  44047. this.inertialRadiusOffset = 0;
  44048. }
  44049. // Panning inertia
  44050. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  44051. if (!this._localDirection) {
  44052. this._localDirection = BABYLON.Vector3.Zero();
  44053. this._transformedDirection = BABYLON.Vector3.Zero();
  44054. }
  44055. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  44056. this._localDirection.multiplyInPlace(this.panningAxis);
  44057. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  44058. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  44059. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  44060. if (!this.panningAxis.y) {
  44061. this._transformedDirection.y = 0;
  44062. }
  44063. if (!this._targetHost) {
  44064. if (this.panningDistanceLimit) {
  44065. this._transformedDirection.addInPlace(this._target);
  44066. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  44067. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  44068. this._target.copyFrom(this._transformedDirection);
  44069. }
  44070. }
  44071. else {
  44072. this._target.addInPlace(this._transformedDirection);
  44073. }
  44074. }
  44075. this.inertialPanningX *= this.panningInertia;
  44076. this.inertialPanningY *= this.panningInertia;
  44077. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  44078. this.inertialPanningX = 0;
  44079. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  44080. this.inertialPanningY = 0;
  44081. }
  44082. // Limits
  44083. this._checkLimits();
  44084. _super.prototype._checkInputs.call(this);
  44085. };
  44086. ArcRotateCamera.prototype._checkLimits = function () {
  44087. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  44088. if (this.allowUpsideDown && this.beta > Math.PI) {
  44089. this.beta = this.beta - (2 * Math.PI);
  44090. }
  44091. }
  44092. else {
  44093. if (this.beta < this.lowerBetaLimit) {
  44094. this.beta = this.lowerBetaLimit;
  44095. }
  44096. }
  44097. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  44098. if (this.allowUpsideDown && this.beta < -Math.PI) {
  44099. this.beta = this.beta + (2 * Math.PI);
  44100. }
  44101. }
  44102. else {
  44103. if (this.beta > this.upperBetaLimit) {
  44104. this.beta = this.upperBetaLimit;
  44105. }
  44106. }
  44107. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  44108. this.alpha = this.lowerAlphaLimit;
  44109. }
  44110. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  44111. this.alpha = this.upperAlphaLimit;
  44112. }
  44113. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  44114. this.radius = this.lowerRadiusLimit;
  44115. }
  44116. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  44117. this.radius = this.upperRadiusLimit;
  44118. }
  44119. };
  44120. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  44121. var radiusv3 = this.position.subtract(this._getTargetPosition());
  44122. this.radius = radiusv3.length();
  44123. if (this.radius === 0) {
  44124. this.radius = 0.0001; // Just to avoid division by zero
  44125. }
  44126. // Alpha
  44127. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  44128. if (radiusv3.z < 0) {
  44129. this.alpha = 2 * Math.PI - this.alpha;
  44130. }
  44131. // Beta
  44132. this.beta = Math.acos(radiusv3.y / this.radius);
  44133. this._checkLimits();
  44134. };
  44135. ArcRotateCamera.prototype.setPosition = function (position) {
  44136. if (this.position.equals(position)) {
  44137. return;
  44138. }
  44139. this.position.copyFrom(position);
  44140. this.rebuildAnglesAndRadius();
  44141. };
  44142. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  44143. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  44144. if (allowSamePosition === void 0) { allowSamePosition = false; }
  44145. if (target.getBoundingInfo) {
  44146. if (toBoundingCenter) {
  44147. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  44148. }
  44149. else {
  44150. this._targetBoundingCenter = null;
  44151. }
  44152. this._targetHost = target;
  44153. this._target = this._getTargetPosition();
  44154. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  44155. }
  44156. else {
  44157. var newTarget = target;
  44158. var currentTarget = this._getTargetPosition();
  44159. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  44160. return;
  44161. }
  44162. this._targetHost = null;
  44163. this._target = newTarget;
  44164. this._targetBoundingCenter = null;
  44165. this.onMeshTargetChangedObservable.notifyObservers(null);
  44166. }
  44167. this.rebuildAnglesAndRadius();
  44168. };
  44169. ArcRotateCamera.prototype._getViewMatrix = function () {
  44170. // Compute
  44171. var cosa = Math.cos(this.alpha);
  44172. var sina = Math.sin(this.alpha);
  44173. var cosb = Math.cos(this.beta);
  44174. var sinb = Math.sin(this.beta);
  44175. if (sinb === 0) {
  44176. sinb = 0.0001;
  44177. }
  44178. var target = this._getTargetPosition();
  44179. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  44180. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  44181. if (!this._collider) {
  44182. this._collider = new BABYLON.Collider();
  44183. }
  44184. this._collider._radius = this.collisionRadius;
  44185. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  44186. this._collisionTriggered = true;
  44187. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  44188. }
  44189. else {
  44190. this.position.copyFrom(this._newPosition);
  44191. var up = this.upVector;
  44192. if (this.allowUpsideDown && sinb < 0) {
  44193. up = up.clone();
  44194. up = up.negate();
  44195. }
  44196. if (this.getScene().useRightHandedSystem) {
  44197. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  44198. }
  44199. else {
  44200. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  44201. }
  44202. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  44203. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  44204. }
  44205. this._currentTarget = target;
  44206. return this._viewMatrix;
  44207. };
  44208. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  44209. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  44210. meshes = meshes || this.getScene().meshes;
  44211. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  44212. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  44213. this.radius = distance * this.zoomOnFactor;
  44214. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  44215. };
  44216. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  44217. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  44218. var meshesOrMinMaxVector;
  44219. var distance;
  44220. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  44221. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  44222. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  44223. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  44224. }
  44225. else {
  44226. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  44227. meshesOrMinMaxVector = minMaxVectorAndDistance;
  44228. distance = minMaxVectorAndDistance.distance;
  44229. }
  44230. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  44231. if (!doNotUpdateMaxZ) {
  44232. this.maxZ = distance * 2;
  44233. }
  44234. };
  44235. /**
  44236. * @override
  44237. * Override Camera.createRigCamera
  44238. */
  44239. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  44240. var alphaShift = 0;
  44241. switch (this.cameraRigMode) {
  44242. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  44243. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  44244. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  44245. case BABYLON.Camera.RIG_MODE_VR:
  44246. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  44247. break;
  44248. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  44249. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  44250. break;
  44251. }
  44252. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  44253. rigCam._cameraRigParams = {};
  44254. return rigCam;
  44255. };
  44256. /**
  44257. * @override
  44258. * Override Camera._updateRigCameras
  44259. */
  44260. ArcRotateCamera.prototype._updateRigCameras = function () {
  44261. var camLeft = this._rigCameras[0];
  44262. var camRight = this._rigCameras[1];
  44263. camLeft.beta = camRight.beta = this.beta;
  44264. camLeft.radius = camRight.radius = this.radius;
  44265. switch (this.cameraRigMode) {
  44266. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  44267. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  44268. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  44269. case BABYLON.Camera.RIG_MODE_VR:
  44270. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  44271. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  44272. break;
  44273. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  44274. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  44275. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  44276. break;
  44277. }
  44278. _super.prototype._updateRigCameras.call(this);
  44279. };
  44280. ArcRotateCamera.prototype.dispose = function () {
  44281. this.inputs.clear();
  44282. _super.prototype.dispose.call(this);
  44283. };
  44284. ArcRotateCamera.prototype.getClassName = function () {
  44285. return "ArcRotateCamera";
  44286. };
  44287. __decorate([
  44288. BABYLON.serialize()
  44289. ], ArcRotateCamera.prototype, "alpha", void 0);
  44290. __decorate([
  44291. BABYLON.serialize()
  44292. ], ArcRotateCamera.prototype, "beta", void 0);
  44293. __decorate([
  44294. BABYLON.serialize()
  44295. ], ArcRotateCamera.prototype, "radius", void 0);
  44296. __decorate([
  44297. BABYLON.serializeAsVector3("target")
  44298. ], ArcRotateCamera.prototype, "_target", void 0);
  44299. __decorate([
  44300. BABYLON.serialize()
  44301. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  44302. __decorate([
  44303. BABYLON.serialize()
  44304. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  44305. __decorate([
  44306. BABYLON.serialize()
  44307. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  44308. __decorate([
  44309. BABYLON.serialize()
  44310. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  44311. __decorate([
  44312. BABYLON.serialize()
  44313. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  44314. __decorate([
  44315. BABYLON.serialize()
  44316. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  44317. __decorate([
  44318. BABYLON.serialize()
  44319. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  44320. __decorate([
  44321. BABYLON.serialize()
  44322. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  44323. __decorate([
  44324. BABYLON.serialize()
  44325. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  44326. __decorate([
  44327. BABYLON.serialize()
  44328. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  44329. __decorate([
  44330. BABYLON.serialize()
  44331. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  44332. __decorate([
  44333. BABYLON.serialize()
  44334. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  44335. __decorate([
  44336. BABYLON.serialize()
  44337. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  44338. __decorate([
  44339. BABYLON.serializeAsVector3()
  44340. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  44341. __decorate([
  44342. BABYLON.serialize()
  44343. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  44344. __decorate([
  44345. BABYLON.serialize()
  44346. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  44347. __decorate([
  44348. BABYLON.serialize()
  44349. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  44350. return ArcRotateCamera;
  44351. }(BABYLON.TargetCamera));
  44352. BABYLON.ArcRotateCamera = ArcRotateCamera;
  44353. })(BABYLON || (BABYLON = {}));
  44354. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  44355. var BABYLON;
  44356. (function (BABYLON) {
  44357. /**
  44358. * The HemisphericLight simulates the ambient environment light,
  44359. * so the passed direction is the light reflection direction, not the incoming direction.
  44360. */
  44361. var HemisphericLight = /** @class */ (function (_super) {
  44362. __extends(HemisphericLight, _super);
  44363. /**
  44364. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  44365. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  44366. * The HemisphericLight can't cast shadows.
  44367. * Documentation : http://doc.babylonjs.com/tutorials/lights
  44368. * @param name The friendly name of the light
  44369. * @param direction The direction of the light reflection
  44370. * @param scene The scene the light belongs to
  44371. */
  44372. function HemisphericLight(name, direction, scene) {
  44373. var _this = _super.call(this, name, scene) || this;
  44374. /**
  44375. * The groundColor is the light in the opposite direction to the one specified during creation.
  44376. * 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.
  44377. */
  44378. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  44379. _this.direction = direction || BABYLON.Vector3.Up();
  44380. return _this;
  44381. }
  44382. HemisphericLight.prototype._buildUniformLayout = function () {
  44383. this._uniformBuffer.addUniform("vLightData", 4);
  44384. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  44385. this._uniformBuffer.addUniform("vLightSpecular", 3);
  44386. this._uniformBuffer.addUniform("vLightGround", 3);
  44387. this._uniformBuffer.addUniform("shadowsInfo", 3);
  44388. this._uniformBuffer.addUniform("depthValues", 2);
  44389. this._uniformBuffer.create();
  44390. };
  44391. /**
  44392. * Returns the string "HemisphericLight".
  44393. * @return The class name
  44394. */
  44395. HemisphericLight.prototype.getClassName = function () {
  44396. return "HemisphericLight";
  44397. };
  44398. /**
  44399. * Sets the HemisphericLight direction towards the passed target (Vector3).
  44400. * Returns the updated direction.
  44401. * @param target The target the direction should point to
  44402. * @return The computed direction
  44403. */
  44404. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  44405. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  44406. return this.direction;
  44407. };
  44408. /**
  44409. * Returns the shadow generator associated to the light.
  44410. * @returns Always null for hemispheric lights because it does not support shadows.
  44411. */
  44412. HemisphericLight.prototype.getShadowGenerator = function () {
  44413. return null;
  44414. };
  44415. /**
  44416. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  44417. * @param effect The effect to update
  44418. * @param lightIndex The index of the light in the effect to update
  44419. * @returns The hemispheric light
  44420. */
  44421. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  44422. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  44423. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  44424. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  44425. return this;
  44426. };
  44427. /**
  44428. * @ignore internal use only.
  44429. */
  44430. HemisphericLight.prototype._getWorldMatrix = function () {
  44431. if (!this._worldMatrix) {
  44432. this._worldMatrix = BABYLON.Matrix.Identity();
  44433. }
  44434. return this._worldMatrix;
  44435. };
  44436. /**
  44437. * Returns the integer 3.
  44438. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  44439. */
  44440. HemisphericLight.prototype.getTypeID = function () {
  44441. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  44442. };
  44443. __decorate([
  44444. BABYLON.serializeAsColor3()
  44445. ], HemisphericLight.prototype, "groundColor", void 0);
  44446. __decorate([
  44447. BABYLON.serializeAsVector3()
  44448. ], HemisphericLight.prototype, "direction", void 0);
  44449. return HemisphericLight;
  44450. }(BABYLON.Light));
  44451. BABYLON.HemisphericLight = HemisphericLight;
  44452. })(BABYLON || (BABYLON = {}));
  44453. //# sourceMappingURL=babylon.hemisphericLight.js.map
  44454. var BABYLON;
  44455. (function (BABYLON) {
  44456. /**
  44457. * Base implementation of @see IShadowLight
  44458. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  44459. */
  44460. var ShadowLight = /** @class */ (function (_super) {
  44461. __extends(ShadowLight, _super);
  44462. function ShadowLight() {
  44463. var _this = _super !== null && _super.apply(this, arguments) || this;
  44464. _this._needProjectionMatrixCompute = true;
  44465. return _this;
  44466. }
  44467. ShadowLight.prototype._setPosition = function (value) {
  44468. this._position = value;
  44469. };
  44470. Object.defineProperty(ShadowLight.prototype, "position", {
  44471. /**
  44472. * Sets the position the shadow will be casted from. Also use as the light position for both
  44473. * point and spot lights.
  44474. */
  44475. get: function () {
  44476. return this._position;
  44477. },
  44478. /**
  44479. * Sets the position the shadow will be casted from. Also use as the light position for both
  44480. * point and spot lights.
  44481. */
  44482. set: function (value) {
  44483. this._setPosition(value);
  44484. },
  44485. enumerable: true,
  44486. configurable: true
  44487. });
  44488. ShadowLight.prototype._setDirection = function (value) {
  44489. this._direction = value;
  44490. };
  44491. Object.defineProperty(ShadowLight.prototype, "direction", {
  44492. /**
  44493. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  44494. * Also use as the light direction on spot and directional lights.
  44495. */
  44496. get: function () {
  44497. return this._direction;
  44498. },
  44499. /**
  44500. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  44501. * Also use as the light direction on spot and directional lights.
  44502. */
  44503. set: function (value) {
  44504. this._setDirection(value);
  44505. },
  44506. enumerable: true,
  44507. configurable: true
  44508. });
  44509. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  44510. /**
  44511. * Gets the shadow projection clipping minimum z value.
  44512. */
  44513. get: function () {
  44514. return this._shadowMinZ;
  44515. },
  44516. /**
  44517. * Sets the shadow projection clipping minimum z value.
  44518. */
  44519. set: function (value) {
  44520. this._shadowMinZ = value;
  44521. this.forceProjectionMatrixCompute();
  44522. },
  44523. enumerable: true,
  44524. configurable: true
  44525. });
  44526. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  44527. /**
  44528. * Sets the shadow projection clipping maximum z value.
  44529. */
  44530. get: function () {
  44531. return this._shadowMaxZ;
  44532. },
  44533. /**
  44534. * Gets the shadow projection clipping maximum z value.
  44535. */
  44536. set: function (value) {
  44537. this._shadowMaxZ = value;
  44538. this.forceProjectionMatrixCompute();
  44539. },
  44540. enumerable: true,
  44541. configurable: true
  44542. });
  44543. /**
  44544. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  44545. * @returns true if the information has been computed, false if it does not need to (no parenting)
  44546. */
  44547. ShadowLight.prototype.computeTransformedInformation = function () {
  44548. if (this.parent && this.parent.getWorldMatrix) {
  44549. if (!this.transformedPosition) {
  44550. this.transformedPosition = BABYLON.Vector3.Zero();
  44551. }
  44552. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  44553. // In case the direction is present.
  44554. if (this.direction) {
  44555. if (!this.transformedDirection) {
  44556. this.transformedDirection = BABYLON.Vector3.Zero();
  44557. }
  44558. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  44559. }
  44560. return true;
  44561. }
  44562. return false;
  44563. };
  44564. /**
  44565. * Return the depth scale used for the shadow map.
  44566. * @returns the depth scale.
  44567. */
  44568. ShadowLight.prototype.getDepthScale = function () {
  44569. return 50.0;
  44570. };
  44571. /**
  44572. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  44573. * @param faceIndex The index of the face we are computed the direction to generate shadow
  44574. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  44575. */
  44576. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  44577. return this.transformedDirection ? this.transformedDirection : this.direction;
  44578. };
  44579. /**
  44580. * Returns the ShadowLight absolute position in the World.
  44581. * @returns the position vector in world space
  44582. */
  44583. ShadowLight.prototype.getAbsolutePosition = function () {
  44584. return this.transformedPosition ? this.transformedPosition : this.position;
  44585. };
  44586. /**
  44587. * Sets the ShadowLight direction toward the passed target.
  44588. * @param target The point tot target in local space
  44589. * @returns the updated ShadowLight direction
  44590. */
  44591. ShadowLight.prototype.setDirectionToTarget = function (target) {
  44592. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  44593. return this.direction;
  44594. };
  44595. /**
  44596. * Returns the light rotation in euler definition.
  44597. * @returns the x y z rotation in local space.
  44598. */
  44599. ShadowLight.prototype.getRotation = function () {
  44600. this.direction.normalize();
  44601. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  44602. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  44603. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  44604. };
  44605. /**
  44606. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  44607. * @returns true if a cube texture needs to be use
  44608. */
  44609. ShadowLight.prototype.needCube = function () {
  44610. return false;
  44611. };
  44612. /**
  44613. * Detects if the projection matrix requires to be recomputed this frame.
  44614. * @returns true if it requires to be recomputed otherwise, false.
  44615. */
  44616. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  44617. return this._needProjectionMatrixCompute;
  44618. };
  44619. /**
  44620. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  44621. */
  44622. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  44623. this._needProjectionMatrixCompute = true;
  44624. };
  44625. /**
  44626. * Get the world matrix of the sahdow lights.
  44627. * @ignore Internal Use Only
  44628. */
  44629. ShadowLight.prototype._getWorldMatrix = function () {
  44630. if (!this._worldMatrix) {
  44631. this._worldMatrix = BABYLON.Matrix.Identity();
  44632. }
  44633. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  44634. return this._worldMatrix;
  44635. };
  44636. /**
  44637. * Gets the minZ used for shadow according to both the scene and the light.
  44638. * @param activeCamera The camera we are returning the min for
  44639. * @returns the depth min z
  44640. */
  44641. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  44642. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  44643. };
  44644. /**
  44645. * Gets the maxZ used for shadow according to both the scene and the light.
  44646. * @param activeCamera The camera we are returning the max for
  44647. * @returns the depth max z
  44648. */
  44649. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  44650. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  44651. };
  44652. /**
  44653. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  44654. * @param matrix The materix to updated with the projection information
  44655. * @param viewMatrix The transform matrix of the light
  44656. * @param renderList The list of mesh to render in the map
  44657. * @returns The current light
  44658. */
  44659. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  44660. if (this.customProjectionMatrixBuilder) {
  44661. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  44662. }
  44663. else {
  44664. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  44665. }
  44666. return this;
  44667. };
  44668. __decorate([
  44669. BABYLON.serializeAsVector3()
  44670. ], ShadowLight.prototype, "position", null);
  44671. __decorate([
  44672. BABYLON.serializeAsVector3()
  44673. ], ShadowLight.prototype, "direction", null);
  44674. __decorate([
  44675. BABYLON.serialize()
  44676. ], ShadowLight.prototype, "shadowMinZ", null);
  44677. __decorate([
  44678. BABYLON.serialize()
  44679. ], ShadowLight.prototype, "shadowMaxZ", null);
  44680. return ShadowLight;
  44681. }(BABYLON.Light));
  44682. BABYLON.ShadowLight = ShadowLight;
  44683. })(BABYLON || (BABYLON = {}));
  44684. //# sourceMappingURL=babylon.shadowLight.js.map
  44685. var BABYLON;
  44686. (function (BABYLON) {
  44687. /**
  44688. * A point light is a light defined by an unique point in world space.
  44689. * The light is emitted in every direction from this point.
  44690. * A good example of a point light is a standard light bulb.
  44691. * Documentation: https://doc.babylonjs.com/babylon101/lights
  44692. */
  44693. var PointLight = /** @class */ (function (_super) {
  44694. __extends(PointLight, _super);
  44695. /**
  44696. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  44697. * A PointLight emits the light in every direction.
  44698. * It can cast shadows.
  44699. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  44700. * ```javascript
  44701. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  44702. * ```
  44703. * Documentation : http://doc.babylonjs.com/tutorials/lights
  44704. * @param name The light friendly name
  44705. * @param position The position of the point light in the scene
  44706. * @param scene The scene the lights belongs to
  44707. */
  44708. function PointLight(name, position, scene) {
  44709. var _this = _super.call(this, name, scene) || this;
  44710. _this._shadowAngle = Math.PI / 2;
  44711. _this.position = position;
  44712. return _this;
  44713. }
  44714. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  44715. /**
  44716. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  44717. * This specifies what angle the shadow will use to be created.
  44718. *
  44719. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  44720. */
  44721. get: function () {
  44722. return this._shadowAngle;
  44723. },
  44724. /**
  44725. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  44726. * This specifies what angle the shadow will use to be created.
  44727. *
  44728. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  44729. */
  44730. set: function (value) {
  44731. this._shadowAngle = value;
  44732. this.forceProjectionMatrixCompute();
  44733. },
  44734. enumerable: true,
  44735. configurable: true
  44736. });
  44737. Object.defineProperty(PointLight.prototype, "direction", {
  44738. /**
  44739. * Gets the direction if it has been set.
  44740. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  44741. */
  44742. get: function () {
  44743. return this._direction;
  44744. },
  44745. /**
  44746. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  44747. */
  44748. set: function (value) {
  44749. var previousNeedCube = this.needCube();
  44750. this._direction = value;
  44751. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  44752. this._shadowGenerator.recreateShadowMap();
  44753. }
  44754. },
  44755. enumerable: true,
  44756. configurable: true
  44757. });
  44758. /**
  44759. * Returns the string "PointLight"
  44760. * @returns the class name
  44761. */
  44762. PointLight.prototype.getClassName = function () {
  44763. return "PointLight";
  44764. };
  44765. /**
  44766. * Returns the integer 0.
  44767. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  44768. */
  44769. PointLight.prototype.getTypeID = function () {
  44770. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  44771. };
  44772. /**
  44773. * Specifies wether or not the shadowmap should be a cube texture.
  44774. * @returns true if the shadowmap needs to be a cube texture.
  44775. */
  44776. PointLight.prototype.needCube = function () {
  44777. return !this.direction;
  44778. };
  44779. /**
  44780. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  44781. * @param faceIndex The index of the face we are computed the direction to generate shadow
  44782. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  44783. */
  44784. PointLight.prototype.getShadowDirection = function (faceIndex) {
  44785. if (this.direction) {
  44786. return _super.prototype.getShadowDirection.call(this, faceIndex);
  44787. }
  44788. else {
  44789. switch (faceIndex) {
  44790. case 0:
  44791. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  44792. case 1:
  44793. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  44794. case 2:
  44795. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  44796. case 3:
  44797. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  44798. case 4:
  44799. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  44800. case 5:
  44801. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  44802. }
  44803. }
  44804. return BABYLON.Vector3.Zero();
  44805. };
  44806. /**
  44807. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  44808. * - fov = PI / 2
  44809. * - aspect ratio : 1.0
  44810. * - z-near and far equal to the active camera minZ and maxZ.
  44811. * Returns the PointLight.
  44812. */
  44813. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  44814. var activeCamera = this.getScene().activeCamera;
  44815. if (!activeCamera) {
  44816. return;
  44817. }
  44818. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  44819. };
  44820. PointLight.prototype._buildUniformLayout = function () {
  44821. this._uniformBuffer.addUniform("vLightData", 4);
  44822. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  44823. this._uniformBuffer.addUniform("vLightSpecular", 3);
  44824. this._uniformBuffer.addUniform("shadowsInfo", 3);
  44825. this._uniformBuffer.addUniform("depthValues", 2);
  44826. this._uniformBuffer.create();
  44827. };
  44828. /**
  44829. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  44830. * @param effect The effect to update
  44831. * @param lightIndex The index of the light in the effect to update
  44832. * @returns The point light
  44833. */
  44834. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  44835. if (this.computeTransformedInformation()) {
  44836. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  44837. return this;
  44838. }
  44839. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  44840. return this;
  44841. };
  44842. __decorate([
  44843. BABYLON.serialize()
  44844. ], PointLight.prototype, "shadowAngle", null);
  44845. return PointLight;
  44846. }(BABYLON.ShadowLight));
  44847. BABYLON.PointLight = PointLight;
  44848. })(BABYLON || (BABYLON = {}));
  44849. //# sourceMappingURL=babylon.pointLight.js.map
  44850. var BABYLON;
  44851. (function (BABYLON) {
  44852. /**
  44853. * A directional light is defined by a direction (what a surprise!).
  44854. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  44855. * 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.
  44856. * Documentation: https://doc.babylonjs.com/babylon101/lights
  44857. */
  44858. var DirectionalLight = /** @class */ (function (_super) {
  44859. __extends(DirectionalLight, _super);
  44860. /**
  44861. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  44862. * The directional light is emitted from everywhere in the given direction.
  44863. * It can cast shawdows.
  44864. * Documentation : http://doc.babylonjs.com/tutorials/lights
  44865. * @param name The friendly name of the light
  44866. * @param direction The direction of the light
  44867. * @param scene The scene the light belongs to
  44868. */
  44869. function DirectionalLight(name, direction, scene) {
  44870. var _this = _super.call(this, name, scene) || this;
  44871. _this._shadowFrustumSize = 0;
  44872. _this._shadowOrthoScale = 0.5;
  44873. /**
  44874. * Automatically compute the projection matrix to best fit (including all the casters)
  44875. * on each frame.
  44876. */
  44877. _this.autoUpdateExtends = true;
  44878. // Cache
  44879. _this._orthoLeft = Number.MAX_VALUE;
  44880. _this._orthoRight = Number.MIN_VALUE;
  44881. _this._orthoTop = Number.MIN_VALUE;
  44882. _this._orthoBottom = Number.MAX_VALUE;
  44883. _this.position = direction.scale(-1.0);
  44884. _this.direction = direction;
  44885. return _this;
  44886. }
  44887. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  44888. /**
  44889. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  44890. */
  44891. get: function () {
  44892. return this._shadowFrustumSize;
  44893. },
  44894. /**
  44895. * Specifies a fix frustum size for the shadow generation.
  44896. */
  44897. set: function (value) {
  44898. this._shadowFrustumSize = value;
  44899. this.forceProjectionMatrixCompute();
  44900. },
  44901. enumerable: true,
  44902. configurable: true
  44903. });
  44904. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  44905. /**
  44906. * Gets the shadow projection scale against the optimal computed one.
  44907. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  44908. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  44909. */
  44910. get: function () {
  44911. return this._shadowOrthoScale;
  44912. },
  44913. /**
  44914. * Sets the shadow projection scale against the optimal computed one.
  44915. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  44916. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  44917. */
  44918. set: function (value) {
  44919. this._shadowOrthoScale = value;
  44920. this.forceProjectionMatrixCompute();
  44921. },
  44922. enumerable: true,
  44923. configurable: true
  44924. });
  44925. /**
  44926. * Returns the string "DirectionalLight".
  44927. * @return The class name
  44928. */
  44929. DirectionalLight.prototype.getClassName = function () {
  44930. return "DirectionalLight";
  44931. };
  44932. /**
  44933. * Returns the integer 1.
  44934. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  44935. */
  44936. DirectionalLight.prototype.getTypeID = function () {
  44937. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  44938. };
  44939. /**
  44940. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  44941. * Returns the DirectionalLight Shadow projection matrix.
  44942. */
  44943. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  44944. if (this.shadowFrustumSize > 0) {
  44945. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  44946. }
  44947. else {
  44948. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  44949. }
  44950. };
  44951. /**
  44952. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  44953. * Returns the DirectionalLight Shadow projection matrix.
  44954. */
  44955. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  44956. var activeCamera = this.getScene().activeCamera;
  44957. if (!activeCamera) {
  44958. return;
  44959. }
  44960. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  44961. };
  44962. /**
  44963. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  44964. * Returns the DirectionalLight Shadow projection matrix.
  44965. */
  44966. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  44967. var activeCamera = this.getScene().activeCamera;
  44968. if (!activeCamera) {
  44969. return;
  44970. }
  44971. // Check extends
  44972. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  44973. var tempVector3 = BABYLON.Vector3.Zero();
  44974. this._orthoLeft = Number.MAX_VALUE;
  44975. this._orthoRight = Number.MIN_VALUE;
  44976. this._orthoTop = Number.MIN_VALUE;
  44977. this._orthoBottom = Number.MAX_VALUE;
  44978. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  44979. var mesh = renderList[meshIndex];
  44980. if (!mesh) {
  44981. continue;
  44982. }
  44983. var boundingInfo = mesh.getBoundingInfo();
  44984. var boundingBox = boundingInfo.boundingBox;
  44985. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  44986. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  44987. if (tempVector3.x < this._orthoLeft)
  44988. this._orthoLeft = tempVector3.x;
  44989. if (tempVector3.y < this._orthoBottom)
  44990. this._orthoBottom = tempVector3.y;
  44991. if (tempVector3.x > this._orthoRight)
  44992. this._orthoRight = tempVector3.x;
  44993. if (tempVector3.y > this._orthoTop)
  44994. this._orthoTop = tempVector3.y;
  44995. }
  44996. }
  44997. }
  44998. var xOffset = this._orthoRight - this._orthoLeft;
  44999. var yOffset = this._orthoTop - this._orthoBottom;
  45000. 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);
  45001. };
  45002. DirectionalLight.prototype._buildUniformLayout = function () {
  45003. this._uniformBuffer.addUniform("vLightData", 4);
  45004. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  45005. this._uniformBuffer.addUniform("vLightSpecular", 3);
  45006. this._uniformBuffer.addUniform("shadowsInfo", 3);
  45007. this._uniformBuffer.addUniform("depthValues", 2);
  45008. this._uniformBuffer.create();
  45009. };
  45010. /**
  45011. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  45012. * @param effect The effect to update
  45013. * @param lightIndex The index of the light in the effect to update
  45014. * @returns The directional light
  45015. */
  45016. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  45017. if (this.computeTransformedInformation()) {
  45018. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  45019. return this;
  45020. }
  45021. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  45022. return this;
  45023. };
  45024. /**
  45025. * Gets the minZ used for shadow according to both the scene and the light.
  45026. *
  45027. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  45028. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  45029. * @param activeCamera The camera we are returning the min for
  45030. * @returns the depth min z
  45031. */
  45032. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  45033. return 1;
  45034. };
  45035. /**
  45036. * Gets the maxZ used for shadow according to both the scene and the light.
  45037. *
  45038. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  45039. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  45040. * @param activeCamera The camera we are returning the max for
  45041. * @returns the depth max z
  45042. */
  45043. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  45044. return 1;
  45045. };
  45046. __decorate([
  45047. BABYLON.serialize()
  45048. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  45049. __decorate([
  45050. BABYLON.serialize()
  45051. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  45052. __decorate([
  45053. BABYLON.serialize()
  45054. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  45055. return DirectionalLight;
  45056. }(BABYLON.ShadowLight));
  45057. BABYLON.DirectionalLight = DirectionalLight;
  45058. })(BABYLON || (BABYLON = {}));
  45059. //# sourceMappingURL=babylon.directionalLight.js.map
  45060. var BABYLON;
  45061. (function (BABYLON) {
  45062. /**
  45063. * A spot light is defined by a position, a direction, an angle, and an exponent.
  45064. * These values define a cone of light starting from the position, emitting toward the direction.
  45065. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  45066. * and the exponent defines the speed of the decay of the light with distance (reach).
  45067. * Documentation: https://doc.babylonjs.com/babylon101/lights
  45068. */
  45069. var SpotLight = /** @class */ (function (_super) {
  45070. __extends(SpotLight, _super);
  45071. /**
  45072. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  45073. * It can cast shadows.
  45074. * Documentation : http://doc.babylonjs.com/tutorials/lights
  45075. * @param name The light friendly name
  45076. * @param position The position of the spot light in the scene
  45077. * @param direction The direction of the light in the scene
  45078. * @param angle The cone angle of the light in Radians
  45079. * @param exponent The light decay speed with the distance from the emission spot
  45080. * @param scene The scene the lights belongs to
  45081. */
  45082. function SpotLight(name, position, direction, angle, exponent, scene) {
  45083. var _this = _super.call(this, name, scene) || this;
  45084. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  45085. _this._projectionTextureLightNear = 1e-6;
  45086. _this._projectionTextureLightFar = 1000.0;
  45087. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  45088. _this._projectionTextureViewLightDirty = true;
  45089. _this._projectionTextureProjectionLightDirty = true;
  45090. _this._projectionTextureDirty = true;
  45091. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  45092. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  45093. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  45094. _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);
  45095. _this.position = position;
  45096. _this.direction = direction;
  45097. _this.angle = angle;
  45098. _this.exponent = exponent;
  45099. return _this;
  45100. }
  45101. Object.defineProperty(SpotLight.prototype, "angle", {
  45102. /**
  45103. * Gets the cone angle of the spot light in Radians.
  45104. */
  45105. get: function () {
  45106. return this._angle;
  45107. },
  45108. /**
  45109. * Sets the cone angle of the spot light in Radians.
  45110. */
  45111. set: function (value) {
  45112. this._angle = value;
  45113. this._projectionTextureProjectionLightDirty = true;
  45114. this.forceProjectionMatrixCompute();
  45115. },
  45116. enumerable: true,
  45117. configurable: true
  45118. });
  45119. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  45120. /**
  45121. * Allows scaling the angle of the light for shadow generation only.
  45122. */
  45123. get: function () {
  45124. return this._shadowAngleScale;
  45125. },
  45126. /**
  45127. * Allows scaling the angle of the light for shadow generation only.
  45128. */
  45129. set: function (value) {
  45130. this._shadowAngleScale = value;
  45131. this.forceProjectionMatrixCompute();
  45132. },
  45133. enumerable: true,
  45134. configurable: true
  45135. });
  45136. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  45137. /**
  45138. * Allows reading the projecton texture
  45139. */
  45140. get: function () {
  45141. return this._projectionTextureMatrix;
  45142. },
  45143. enumerable: true,
  45144. configurable: true
  45145. });
  45146. ;
  45147. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  45148. /**
  45149. * Gets the near clip of the Spotlight for texture projection.
  45150. */
  45151. get: function () {
  45152. return this._projectionTextureLightNear;
  45153. },
  45154. /**
  45155. * Sets the near clip of the Spotlight for texture projection.
  45156. */
  45157. set: function (value) {
  45158. this._projectionTextureLightNear = value;
  45159. this._projectionTextureProjectionLightDirty = true;
  45160. },
  45161. enumerable: true,
  45162. configurable: true
  45163. });
  45164. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  45165. /**
  45166. * Gets the far clip of the Spotlight for texture projection.
  45167. */
  45168. get: function () {
  45169. return this._projectionTextureLightFar;
  45170. },
  45171. /**
  45172. * Sets the far clip of the Spotlight for texture projection.
  45173. */
  45174. set: function (value) {
  45175. this._projectionTextureLightFar = value;
  45176. this._projectionTextureProjectionLightDirty = true;
  45177. },
  45178. enumerable: true,
  45179. configurable: true
  45180. });
  45181. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  45182. /**
  45183. * Gets the Up vector of the Spotlight for texture projection.
  45184. */
  45185. get: function () {
  45186. return this._projectionTextureUpDirection;
  45187. },
  45188. /**
  45189. * Sets the Up vector of the Spotlight for texture projection.
  45190. */
  45191. set: function (value) {
  45192. this._projectionTextureUpDirection = value;
  45193. this._projectionTextureProjectionLightDirty = true;
  45194. },
  45195. enumerable: true,
  45196. configurable: true
  45197. });
  45198. ;
  45199. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  45200. /**
  45201. * Gets the projection texture of the light.
  45202. */
  45203. get: function () {
  45204. return this._projectionTexture;
  45205. },
  45206. /**
  45207. * Sets the projection texture of the light.
  45208. */
  45209. set: function (value) {
  45210. this._projectionTexture = value;
  45211. this._projectionTextureDirty = true;
  45212. },
  45213. enumerable: true,
  45214. configurable: true
  45215. });
  45216. /**
  45217. * Returns the string "SpotLight".
  45218. * @returns the class name
  45219. */
  45220. SpotLight.prototype.getClassName = function () {
  45221. return "SpotLight";
  45222. };
  45223. /**
  45224. * Returns the integer 2.
  45225. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  45226. */
  45227. SpotLight.prototype.getTypeID = function () {
  45228. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  45229. };
  45230. /**
  45231. * Overrides the direction setter to recompute the projection texture view light Matrix.
  45232. */
  45233. SpotLight.prototype._setDirection = function (value) {
  45234. _super.prototype._setDirection.call(this, value);
  45235. this._projectionTextureViewLightDirty = true;
  45236. };
  45237. /**
  45238. * Overrides the position setter to recompute the projection texture view light Matrix.
  45239. */
  45240. SpotLight.prototype._setPosition = function (value) {
  45241. _super.prototype._setPosition.call(this, value);
  45242. this._projectionTextureViewLightDirty = true;
  45243. };
  45244. /**
  45245. * 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.
  45246. * Returns the SpotLight.
  45247. */
  45248. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  45249. var activeCamera = this.getScene().activeCamera;
  45250. if (!activeCamera) {
  45251. return;
  45252. }
  45253. this._shadowAngleScale = this._shadowAngleScale || 1;
  45254. var angle = this._shadowAngleScale * this._angle;
  45255. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  45256. };
  45257. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  45258. this._projectionTextureViewLightDirty = false;
  45259. this._projectionTextureDirty = true;
  45260. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  45261. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  45262. };
  45263. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  45264. this._projectionTextureProjectionLightDirty = false;
  45265. this._projectionTextureDirty = true;
  45266. var light_far = this.projectionTextureLightFar;
  45267. var light_near = this.projectionTextureLightNear;
  45268. var P = light_far / (light_far - light_near);
  45269. var Q = -P * light_near;
  45270. var S = 1.0 / Math.tan(this._angle / 2.0);
  45271. var A = 1.0;
  45272. 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);
  45273. };
  45274. /**
  45275. * Main function for light texture projection matrix computing.
  45276. */
  45277. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  45278. this._projectionTextureDirty = false;
  45279. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  45280. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  45281. };
  45282. SpotLight.prototype._buildUniformLayout = function () {
  45283. this._uniformBuffer.addUniform("vLightData", 4);
  45284. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  45285. this._uniformBuffer.addUniform("vLightSpecular", 3);
  45286. this._uniformBuffer.addUniform("vLightDirection", 3);
  45287. this._uniformBuffer.addUniform("shadowsInfo", 3);
  45288. this._uniformBuffer.addUniform("depthValues", 2);
  45289. this._uniformBuffer.create();
  45290. };
  45291. /**
  45292. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  45293. * @param effect The effect to update
  45294. * @param lightIndex The index of the light in the effect to update
  45295. * @returns The spot light
  45296. */
  45297. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  45298. var normalizeDirection;
  45299. if (this.computeTransformedInformation()) {
  45300. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  45301. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  45302. }
  45303. else {
  45304. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  45305. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  45306. }
  45307. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  45308. if (this.projectionTexture && this.projectionTexture.isReady()) {
  45309. if (this._projectionTextureViewLightDirty) {
  45310. this._computeProjectionTextureViewLightMatrix();
  45311. }
  45312. if (this._projectionTextureProjectionLightDirty) {
  45313. this._computeProjectionTextureProjectionLightMatrix();
  45314. }
  45315. if (this._projectionTextureDirty) {
  45316. this._computeProjectionTextureMatrix();
  45317. }
  45318. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  45319. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  45320. }
  45321. return this;
  45322. };
  45323. /**
  45324. * Disposes the light and the associated resources.
  45325. */
  45326. SpotLight.prototype.dispose = function () {
  45327. _super.prototype.dispose.call(this);
  45328. if (this._projectionTexture) {
  45329. this._projectionTexture.dispose();
  45330. }
  45331. };
  45332. __decorate([
  45333. BABYLON.serialize()
  45334. ], SpotLight.prototype, "angle", null);
  45335. __decorate([
  45336. BABYLON.serialize()
  45337. ], SpotLight.prototype, "shadowAngleScale", null);
  45338. __decorate([
  45339. BABYLON.serialize()
  45340. ], SpotLight.prototype, "exponent", void 0);
  45341. __decorate([
  45342. BABYLON.serialize()
  45343. ], SpotLight.prototype, "projectionTextureLightNear", null);
  45344. __decorate([
  45345. BABYLON.serialize()
  45346. ], SpotLight.prototype, "projectionTextureLightFar", null);
  45347. __decorate([
  45348. BABYLON.serialize()
  45349. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  45350. __decorate([
  45351. BABYLON.serializeAsTexture("projectedLightTexture")
  45352. ], SpotLight.prototype, "_projectionTexture", void 0);
  45353. return SpotLight;
  45354. }(BABYLON.ShadowLight));
  45355. BABYLON.SpotLight = SpotLight;
  45356. })(BABYLON || (BABYLON = {}));
  45357. //# sourceMappingURL=babylon.spotLight.js.map
  45358. var BABYLON;
  45359. (function (BABYLON) {
  45360. var AnimationRange = /** @class */ (function () {
  45361. function AnimationRange(name, from, to) {
  45362. this.name = name;
  45363. this.from = from;
  45364. this.to = to;
  45365. }
  45366. AnimationRange.prototype.clone = function () {
  45367. return new AnimationRange(this.name, this.from, this.to);
  45368. };
  45369. return AnimationRange;
  45370. }());
  45371. BABYLON.AnimationRange = AnimationRange;
  45372. /**
  45373. * Composed of a frame, and an action function
  45374. */
  45375. var AnimationEvent = /** @class */ (function () {
  45376. function AnimationEvent(frame, action, onlyOnce) {
  45377. this.frame = frame;
  45378. this.action = action;
  45379. this.onlyOnce = onlyOnce;
  45380. this.isDone = false;
  45381. }
  45382. return AnimationEvent;
  45383. }());
  45384. BABYLON.AnimationEvent = AnimationEvent;
  45385. var PathCursor = /** @class */ (function () {
  45386. function PathCursor(path) {
  45387. this.path = path;
  45388. this._onchange = new Array();
  45389. this.value = 0;
  45390. this.animations = new Array();
  45391. }
  45392. PathCursor.prototype.getPoint = function () {
  45393. var point = this.path.getPointAtLengthPosition(this.value);
  45394. return new BABYLON.Vector3(point.x, 0, point.y);
  45395. };
  45396. PathCursor.prototype.moveAhead = function (step) {
  45397. if (step === void 0) { step = 0.002; }
  45398. this.move(step);
  45399. return this;
  45400. };
  45401. PathCursor.prototype.moveBack = function (step) {
  45402. if (step === void 0) { step = 0.002; }
  45403. this.move(-step);
  45404. return this;
  45405. };
  45406. PathCursor.prototype.move = function (step) {
  45407. if (Math.abs(step) > 1) {
  45408. throw "step size should be less than 1.";
  45409. }
  45410. this.value += step;
  45411. this.ensureLimits();
  45412. this.raiseOnChange();
  45413. return this;
  45414. };
  45415. PathCursor.prototype.ensureLimits = function () {
  45416. while (this.value > 1) {
  45417. this.value -= 1;
  45418. }
  45419. while (this.value < 0) {
  45420. this.value += 1;
  45421. }
  45422. return this;
  45423. };
  45424. // used by animation engine
  45425. PathCursor.prototype.raiseOnChange = function () {
  45426. var _this = this;
  45427. this._onchange.forEach(function (f) { return f(_this); });
  45428. return this;
  45429. };
  45430. PathCursor.prototype.onchange = function (f) {
  45431. this._onchange.push(f);
  45432. return this;
  45433. };
  45434. return PathCursor;
  45435. }());
  45436. BABYLON.PathCursor = PathCursor;
  45437. var AnimationKeyInterpolation;
  45438. (function (AnimationKeyInterpolation) {
  45439. /**
  45440. * Do not interpolate between keys and use the start key value only. Tangents are ignored.
  45441. */
  45442. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  45443. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  45444. var Animation = /** @class */ (function () {
  45445. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  45446. this.name = name;
  45447. this.targetProperty = targetProperty;
  45448. this.framePerSecond = framePerSecond;
  45449. this.dataType = dataType;
  45450. this.loopMode = loopMode;
  45451. this.enableBlending = enableBlending;
  45452. this._runtimeAnimations = new Array();
  45453. // The set of event that will be linked to this animation
  45454. this._events = new Array();
  45455. this.blendingSpeed = 0.01;
  45456. this._ranges = {};
  45457. this.targetPropertyPath = targetProperty.split(".");
  45458. this.dataType = dataType;
  45459. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  45460. }
  45461. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  45462. var dataType = undefined;
  45463. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  45464. dataType = Animation.ANIMATIONTYPE_FLOAT;
  45465. }
  45466. else if (from instanceof BABYLON.Quaternion) {
  45467. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  45468. }
  45469. else if (from instanceof BABYLON.Vector3) {
  45470. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  45471. }
  45472. else if (from instanceof BABYLON.Vector2) {
  45473. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  45474. }
  45475. else if (from instanceof BABYLON.Color3) {
  45476. dataType = Animation.ANIMATIONTYPE_COLOR3;
  45477. }
  45478. else if (from instanceof BABYLON.Size) {
  45479. dataType = Animation.ANIMATIONTYPE_SIZE;
  45480. }
  45481. if (dataType == undefined) {
  45482. return null;
  45483. }
  45484. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  45485. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  45486. animation.setKeys(keys);
  45487. if (easingFunction !== undefined) {
  45488. animation.setEasingFunction(easingFunction);
  45489. }
  45490. return animation;
  45491. };
  45492. /**
  45493. * Sets up an animation.
  45494. * @param property the property to animate
  45495. * @param animationType the animation type to apply
  45496. * @param easingFunction the easing function used in the animation
  45497. * @returns The created animation
  45498. */
  45499. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  45500. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  45501. animation.setEasingFunction(easingFunction);
  45502. return animation;
  45503. };
  45504. /**
  45505. * Create and start an animation on a node
  45506. * @param {string} name defines the name of the global animation that will be run on all nodes
  45507. * @param {BABYLON.Node} node defines the root node where the animation will take place
  45508. * @param {string} targetProperty defines property to animate
  45509. * @param {number} framePerSecond defines the number of frame per second yo use
  45510. * @param {number} totalFrame defines the number of frames in total
  45511. * @param {any} from defines the initial value
  45512. * @param {any} to defines the final value
  45513. * @param {number} loopMode defines which loop mode you want to use (off by default)
  45514. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  45515. * @param onAnimationEnd defines the callback to call when animation end
  45516. * @returns the animatable created for this animation
  45517. */
  45518. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  45519. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  45520. if (!animation) {
  45521. return null;
  45522. }
  45523. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  45524. };
  45525. /**
  45526. * Create and start an animation on a node and its descendants
  45527. * @param {string} name defines the name of the global animation that will be run on all nodes
  45528. * @param {BABYLON.Node} node defines the root node where the animation will take place
  45529. * @param {boolean} 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.
  45530. * @param {string} targetProperty defines property to animate
  45531. * @param {number} framePerSecond defines the number of frame per second yo use
  45532. * @param {number} totalFrame defines the number of frames in total
  45533. * @param {any} from defines the initial value
  45534. * @param {any} to defines the final value
  45535. * @param {number} loopMode defines which loop mode you want to use (off by default)
  45536. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  45537. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  45538. * @returns the list of animatables created for all nodes
  45539. * @example https://www.babylonjs-playground.com/#MH0VLI
  45540. */
  45541. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  45542. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  45543. if (!animation) {
  45544. return null;
  45545. }
  45546. var scene = node.getScene();
  45547. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  45548. };
  45549. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  45550. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  45551. if (!animation) {
  45552. return null;
  45553. }
  45554. node.animations.push(animation);
  45555. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  45556. };
  45557. /**
  45558. * Transition property of the Camera to the target Value.
  45559. * @param property The property to transition
  45560. * @param targetValue The target Value of the property
  45561. * @param host The object where the property to animate belongs
  45562. * @param scene Scene used to run the animation
  45563. * @param frameRate Framerate (in frame/s) to use
  45564. * @param transition The transition type we want to use
  45565. * @param duration The duration of the animation, in milliseconds
  45566. * @param onAnimationEnd Call back trigger at the end of the animation.
  45567. */
  45568. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  45569. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  45570. if (duration <= 0) {
  45571. host[property] = targetValue;
  45572. if (onAnimationEnd) {
  45573. onAnimationEnd();
  45574. }
  45575. return null;
  45576. }
  45577. var endFrame = frameRate * (duration / 1000);
  45578. transition.setKeys([{
  45579. frame: 0,
  45580. value: host[property].clone ? host[property].clone() : host[property]
  45581. },
  45582. {
  45583. frame: endFrame,
  45584. value: targetValue
  45585. }]);
  45586. if (!host.animations) {
  45587. host.animations = [];
  45588. }
  45589. host.animations.push(transition);
  45590. var animation = scene.beginAnimation(host, 0, endFrame, false);
  45591. animation.onAnimationEnd = onAnimationEnd;
  45592. return animation;
  45593. };
  45594. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  45595. /**
  45596. * Return the array of runtime animations currently using this animation
  45597. */
  45598. get: function () {
  45599. return this._runtimeAnimations;
  45600. },
  45601. enumerable: true,
  45602. configurable: true
  45603. });
  45604. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  45605. get: function () {
  45606. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  45607. var runtimeAnimation = _a[_i];
  45608. if (!runtimeAnimation.isStopped) {
  45609. return true;
  45610. }
  45611. }
  45612. return false;
  45613. },
  45614. enumerable: true,
  45615. configurable: true
  45616. });
  45617. // Methods
  45618. /**
  45619. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  45620. */
  45621. Animation.prototype.toString = function (fullDetails) {
  45622. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  45623. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  45624. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  45625. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  45626. if (fullDetails) {
  45627. ret += ", Ranges: {";
  45628. var first = true;
  45629. for (var name in this._ranges) {
  45630. if (first) {
  45631. ret += ", ";
  45632. first = false;
  45633. }
  45634. ret += name;
  45635. }
  45636. ret += "}";
  45637. }
  45638. return ret;
  45639. };
  45640. /**
  45641. * Add an event to this animation.
  45642. */
  45643. Animation.prototype.addEvent = function (event) {
  45644. this._events.push(event);
  45645. };
  45646. /**
  45647. * Remove all events found at the given frame
  45648. * @param frame
  45649. */
  45650. Animation.prototype.removeEvents = function (frame) {
  45651. for (var index = 0; index < this._events.length; index++) {
  45652. if (this._events[index].frame === frame) {
  45653. this._events.splice(index, 1);
  45654. index--;
  45655. }
  45656. }
  45657. };
  45658. Animation.prototype.getEvents = function () {
  45659. return this._events;
  45660. };
  45661. Animation.prototype.createRange = function (name, from, to) {
  45662. // check name not already in use; could happen for bones after serialized
  45663. if (!this._ranges[name]) {
  45664. this._ranges[name] = new AnimationRange(name, from, to);
  45665. }
  45666. };
  45667. Animation.prototype.deleteRange = function (name, deleteFrames) {
  45668. if (deleteFrames === void 0) { deleteFrames = true; }
  45669. var range = this._ranges[name];
  45670. if (!range) {
  45671. return;
  45672. }
  45673. if (deleteFrames) {
  45674. var from = range.from;
  45675. var to = range.to;
  45676. // this loop MUST go high to low for multiple splices to work
  45677. for (var key = this._keys.length - 1; key >= 0; key--) {
  45678. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  45679. this._keys.splice(key, 1);
  45680. }
  45681. }
  45682. }
  45683. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  45684. };
  45685. Animation.prototype.getRange = function (name) {
  45686. return this._ranges[name];
  45687. };
  45688. Animation.prototype.getKeys = function () {
  45689. return this._keys;
  45690. };
  45691. Animation.prototype.getHighestFrame = function () {
  45692. var ret = 0;
  45693. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  45694. if (ret < this._keys[key].frame) {
  45695. ret = this._keys[key].frame;
  45696. }
  45697. }
  45698. return ret;
  45699. };
  45700. Animation.prototype.getEasingFunction = function () {
  45701. return this._easingFunction;
  45702. };
  45703. Animation.prototype.setEasingFunction = function (easingFunction) {
  45704. this._easingFunction = easingFunction;
  45705. };
  45706. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  45707. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  45708. };
  45709. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  45710. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  45711. };
  45712. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  45713. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  45714. };
  45715. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  45716. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  45717. };
  45718. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  45719. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  45720. };
  45721. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  45722. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  45723. };
  45724. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  45725. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  45726. };
  45727. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  45728. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  45729. };
  45730. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  45731. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  45732. };
  45733. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  45734. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  45735. };
  45736. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  45737. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  45738. };
  45739. Animation.prototype.clone = function () {
  45740. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  45741. clone.enableBlending = this.enableBlending;
  45742. clone.blendingSpeed = this.blendingSpeed;
  45743. if (this._keys) {
  45744. clone.setKeys(this._keys);
  45745. }
  45746. if (this._ranges) {
  45747. clone._ranges = {};
  45748. for (var name in this._ranges) {
  45749. var range = this._ranges[name];
  45750. if (!range) {
  45751. continue;
  45752. }
  45753. clone._ranges[name] = range.clone();
  45754. }
  45755. }
  45756. return clone;
  45757. };
  45758. Animation.prototype.setKeys = function (values) {
  45759. this._keys = values.slice(0);
  45760. };
  45761. Animation.prototype.serialize = function () {
  45762. var serializationObject = {};
  45763. serializationObject.name = this.name;
  45764. serializationObject.property = this.targetProperty;
  45765. serializationObject.framePerSecond = this.framePerSecond;
  45766. serializationObject.dataType = this.dataType;
  45767. serializationObject.loopBehavior = this.loopMode;
  45768. serializationObject.enableBlending = this.enableBlending;
  45769. serializationObject.blendingSpeed = this.blendingSpeed;
  45770. var dataType = this.dataType;
  45771. serializationObject.keys = [];
  45772. var keys = this.getKeys();
  45773. for (var index = 0; index < keys.length; index++) {
  45774. var animationKey = keys[index];
  45775. var key = {};
  45776. key.frame = animationKey.frame;
  45777. switch (dataType) {
  45778. case Animation.ANIMATIONTYPE_FLOAT:
  45779. key.values = [animationKey.value];
  45780. break;
  45781. case Animation.ANIMATIONTYPE_QUATERNION:
  45782. case Animation.ANIMATIONTYPE_MATRIX:
  45783. case Animation.ANIMATIONTYPE_VECTOR3:
  45784. case Animation.ANIMATIONTYPE_COLOR3:
  45785. key.values = animationKey.value.asArray();
  45786. break;
  45787. }
  45788. serializationObject.keys.push(key);
  45789. }
  45790. serializationObject.ranges = [];
  45791. for (var name in this._ranges) {
  45792. var source = this._ranges[name];
  45793. if (!source) {
  45794. continue;
  45795. }
  45796. var range = {};
  45797. range.name = name;
  45798. range.from = source.from;
  45799. range.to = source.to;
  45800. serializationObject.ranges.push(range);
  45801. }
  45802. return serializationObject;
  45803. };
  45804. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  45805. get: function () {
  45806. return Animation._ANIMATIONTYPE_FLOAT;
  45807. },
  45808. enumerable: true,
  45809. configurable: true
  45810. });
  45811. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  45812. get: function () {
  45813. return Animation._ANIMATIONTYPE_VECTOR3;
  45814. },
  45815. enumerable: true,
  45816. configurable: true
  45817. });
  45818. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  45819. get: function () {
  45820. return Animation._ANIMATIONTYPE_VECTOR2;
  45821. },
  45822. enumerable: true,
  45823. configurable: true
  45824. });
  45825. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  45826. get: function () {
  45827. return Animation._ANIMATIONTYPE_SIZE;
  45828. },
  45829. enumerable: true,
  45830. configurable: true
  45831. });
  45832. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  45833. get: function () {
  45834. return Animation._ANIMATIONTYPE_QUATERNION;
  45835. },
  45836. enumerable: true,
  45837. configurable: true
  45838. });
  45839. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  45840. get: function () {
  45841. return Animation._ANIMATIONTYPE_MATRIX;
  45842. },
  45843. enumerable: true,
  45844. configurable: true
  45845. });
  45846. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  45847. get: function () {
  45848. return Animation._ANIMATIONTYPE_COLOR3;
  45849. },
  45850. enumerable: true,
  45851. configurable: true
  45852. });
  45853. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  45854. get: function () {
  45855. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  45856. },
  45857. enumerable: true,
  45858. configurable: true
  45859. });
  45860. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  45861. get: function () {
  45862. return Animation._ANIMATIONLOOPMODE_CYCLE;
  45863. },
  45864. enumerable: true,
  45865. configurable: true
  45866. });
  45867. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  45868. get: function () {
  45869. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  45870. },
  45871. enumerable: true,
  45872. configurable: true
  45873. });
  45874. Animation.Parse = function (parsedAnimation) {
  45875. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  45876. var dataType = parsedAnimation.dataType;
  45877. var keys = [];
  45878. var data;
  45879. var index;
  45880. if (parsedAnimation.enableBlending) {
  45881. animation.enableBlending = parsedAnimation.enableBlending;
  45882. }
  45883. if (parsedAnimation.blendingSpeed) {
  45884. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  45885. }
  45886. for (index = 0; index < parsedAnimation.keys.length; index++) {
  45887. var key = parsedAnimation.keys[index];
  45888. var inTangent;
  45889. var outTangent;
  45890. switch (dataType) {
  45891. case Animation.ANIMATIONTYPE_FLOAT:
  45892. data = key.values[0];
  45893. if (key.values.length >= 1) {
  45894. inTangent = key.values[1];
  45895. }
  45896. if (key.values.length >= 2) {
  45897. outTangent = key.values[2];
  45898. }
  45899. break;
  45900. case Animation.ANIMATIONTYPE_QUATERNION:
  45901. data = BABYLON.Quaternion.FromArray(key.values);
  45902. if (key.values.length >= 8) {
  45903. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  45904. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  45905. inTangent = _inTangent;
  45906. }
  45907. }
  45908. if (key.values.length >= 12) {
  45909. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  45910. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  45911. outTangent = _outTangent;
  45912. }
  45913. }
  45914. break;
  45915. case Animation.ANIMATIONTYPE_MATRIX:
  45916. data = BABYLON.Matrix.FromArray(key.values);
  45917. break;
  45918. case Animation.ANIMATIONTYPE_COLOR3:
  45919. data = BABYLON.Color3.FromArray(key.values);
  45920. break;
  45921. case Animation.ANIMATIONTYPE_VECTOR3:
  45922. default:
  45923. data = BABYLON.Vector3.FromArray(key.values);
  45924. break;
  45925. }
  45926. var keyData = {};
  45927. keyData.frame = key.frame;
  45928. keyData.value = data;
  45929. if (inTangent != undefined) {
  45930. keyData.inTangent = inTangent;
  45931. }
  45932. if (outTangent != undefined) {
  45933. keyData.outTangent = outTangent;
  45934. }
  45935. keys.push(keyData);
  45936. }
  45937. animation.setKeys(keys);
  45938. if (parsedAnimation.ranges) {
  45939. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  45940. data = parsedAnimation.ranges[index];
  45941. animation.createRange(data.name, data.from, data.to);
  45942. }
  45943. }
  45944. return animation;
  45945. };
  45946. Animation.AppendSerializedAnimations = function (source, destination) {
  45947. if (source.animations) {
  45948. destination.animations = [];
  45949. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  45950. var animation = source.animations[animationIndex];
  45951. destination.animations.push(animation.serialize());
  45952. }
  45953. }
  45954. };
  45955. Animation.AllowMatricesInterpolation = false;
  45956. // Statics
  45957. Animation._ANIMATIONTYPE_FLOAT = 0;
  45958. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  45959. Animation._ANIMATIONTYPE_QUATERNION = 2;
  45960. Animation._ANIMATIONTYPE_MATRIX = 3;
  45961. Animation._ANIMATIONTYPE_COLOR3 = 4;
  45962. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  45963. Animation._ANIMATIONTYPE_SIZE = 6;
  45964. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  45965. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  45966. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  45967. return Animation;
  45968. }());
  45969. BABYLON.Animation = Animation;
  45970. })(BABYLON || (BABYLON = {}));
  45971. //# sourceMappingURL=babylon.animation.js.map
  45972. var BABYLON;
  45973. (function (BABYLON) {
  45974. /**
  45975. * This class defines the direct association between an animation and a target
  45976. */
  45977. var TargetedAnimation = /** @class */ (function () {
  45978. function TargetedAnimation() {
  45979. }
  45980. return TargetedAnimation;
  45981. }());
  45982. BABYLON.TargetedAnimation = TargetedAnimation;
  45983. /**
  45984. * Use this class to create coordinated animations on multiple targets
  45985. */
  45986. var AnimationGroup = /** @class */ (function () {
  45987. function AnimationGroup(name, scene) {
  45988. if (scene === void 0) { scene = null; }
  45989. this.name = name;
  45990. this._targetedAnimations = new Array();
  45991. this._animatables = new Array();
  45992. this._from = Number.MAX_VALUE;
  45993. this._to = -Number.MAX_VALUE;
  45994. this._speedRatio = 1;
  45995. this.onAnimationEndObservable = new BABYLON.Observable();
  45996. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  45997. this._scene.animationGroups.push(this);
  45998. }
  45999. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  46000. /**
  46001. * Define if the animations are started
  46002. */
  46003. get: function () {
  46004. return this._isStarted;
  46005. },
  46006. enumerable: true,
  46007. configurable: true
  46008. });
  46009. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  46010. /**
  46011. * Gets or sets the speed ratio to use for all animations
  46012. */
  46013. get: function () {
  46014. return this._speedRatio;
  46015. },
  46016. /**
  46017. * Gets or sets the speed ratio to use for all animations
  46018. */
  46019. set: function (value) {
  46020. if (this._speedRatio === value) {
  46021. return;
  46022. }
  46023. this._speedRatio = value;
  46024. for (var index = 0; index < this._animatables.length; index++) {
  46025. var animatable = this._animatables[index];
  46026. animatable.speedRatio = this._speedRatio;
  46027. }
  46028. },
  46029. enumerable: true,
  46030. configurable: true
  46031. });
  46032. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  46033. /**
  46034. * Gets the targeted animations for this animation group
  46035. */
  46036. get: function () {
  46037. return this._targetedAnimations;
  46038. },
  46039. enumerable: true,
  46040. configurable: true
  46041. });
  46042. /**
  46043. * Add an animation (with its target) in the group
  46044. * @param animation defines the animation we want to add
  46045. * @param target defines the target of the animation
  46046. * @returns the {BABYLON.TargetedAnimation} object
  46047. */
  46048. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  46049. var targetedAnimation = {
  46050. animation: animation,
  46051. target: target
  46052. };
  46053. var keys = animation.getKeys();
  46054. if (this._from > keys[0].frame) {
  46055. this._from = keys[0].frame;
  46056. }
  46057. if (this._to < keys[keys.length - 1].frame) {
  46058. this._to = keys[keys.length - 1].frame;
  46059. }
  46060. this._targetedAnimations.push(targetedAnimation);
  46061. return targetedAnimation;
  46062. };
  46063. /**
  46064. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  46065. * It can add constant keys at begin or end
  46066. * @param beginFrame defines the new begin frame for all animations. It can't be bigger than the smallest begin frame of all animations
  46067. * @param endFrame defines the new end frame for all animations. It can't be smaller than the largest end frame of all animations
  46068. */
  46069. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  46070. if (beginFrame === void 0) { beginFrame = -Number.MAX_VALUE; }
  46071. if (endFrame === void 0) { endFrame = Number.MAX_VALUE; }
  46072. beginFrame = Math.max(beginFrame, this._from);
  46073. endFrame = Math.min(endFrame, this._to);
  46074. for (var index = 0; index < this._targetedAnimations.length; index++) {
  46075. var targetedAnimation = this._targetedAnimations[index];
  46076. var keys = targetedAnimation.animation.getKeys();
  46077. var startKey = keys[0];
  46078. var endKey = keys[keys.length - 1];
  46079. if (startKey.frame > beginFrame) {
  46080. var newKey = {
  46081. frame: beginFrame,
  46082. value: startKey.value,
  46083. inTangent: startKey.inTangent,
  46084. outTangent: startKey.outTangent,
  46085. interpolation: startKey.interpolation
  46086. };
  46087. keys.splice(0, 0, newKey);
  46088. }
  46089. if (endKey.frame < endFrame) {
  46090. var newKey = {
  46091. frame: endFrame,
  46092. value: endKey.value,
  46093. inTangent: endKey.outTangent,
  46094. outTangent: endKey.outTangent,
  46095. interpolation: endKey.interpolation
  46096. };
  46097. keys.push(newKey);
  46098. }
  46099. }
  46100. return this;
  46101. };
  46102. /**
  46103. * Start all animations on given targets
  46104. * @param loop defines if animations must loop
  46105. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  46106. */
  46107. AnimationGroup.prototype.start = function (loop, speedRatio) {
  46108. var _this = this;
  46109. if (loop === void 0) { loop = false; }
  46110. if (speedRatio === void 0) { speedRatio = 1; }
  46111. if (this._isStarted || this._targetedAnimations.length === 0) {
  46112. return this;
  46113. }
  46114. var _loop_1 = function () {
  46115. var targetedAnimation = this_1._targetedAnimations[index];
  46116. this_1._animatables.push(this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], this_1._from, this_1._to, loop, speedRatio, function () {
  46117. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  46118. }));
  46119. };
  46120. var this_1 = this;
  46121. for (var index = 0; index < this._targetedAnimations.length; index++) {
  46122. _loop_1();
  46123. }
  46124. this._speedRatio = speedRatio;
  46125. this._isStarted = true;
  46126. return this;
  46127. };
  46128. /**
  46129. * Pause all animations
  46130. */
  46131. AnimationGroup.prototype.pause = function () {
  46132. if (!this._isStarted) {
  46133. return this;
  46134. }
  46135. for (var index = 0; index < this._animatables.length; index++) {
  46136. var animatable = this._animatables[index];
  46137. animatable.pause();
  46138. }
  46139. return this;
  46140. };
  46141. /**
  46142. * Play all animations to initial state
  46143. * This function will start() the animations if they were not started or will restart() them if they were paused
  46144. * @param loop defines if animations must loop
  46145. */
  46146. AnimationGroup.prototype.play = function (loop) {
  46147. if (this.isStarted) {
  46148. if (loop !== undefined) {
  46149. for (var index = 0; index < this._animatables.length; index++) {
  46150. var animatable = this._animatables[index];
  46151. animatable.loopAnimation = loop;
  46152. }
  46153. }
  46154. this.restart();
  46155. }
  46156. else {
  46157. this.start(loop, this._speedRatio);
  46158. }
  46159. return this;
  46160. };
  46161. /**
  46162. * Reset all animations to initial state
  46163. */
  46164. AnimationGroup.prototype.reset = function () {
  46165. if (!this._isStarted) {
  46166. return this;
  46167. }
  46168. for (var index = 0; index < this._animatables.length; index++) {
  46169. var animatable = this._animatables[index];
  46170. animatable.reset();
  46171. }
  46172. return this;
  46173. };
  46174. /**
  46175. * Restart animations from key 0
  46176. */
  46177. AnimationGroup.prototype.restart = function () {
  46178. if (!this._isStarted) {
  46179. return this;
  46180. }
  46181. for (var index = 0; index < this._animatables.length; index++) {
  46182. var animatable = this._animatables[index];
  46183. animatable.restart();
  46184. }
  46185. return this;
  46186. };
  46187. /**
  46188. * Stop all animations
  46189. */
  46190. AnimationGroup.prototype.stop = function () {
  46191. if (!this._isStarted) {
  46192. return this;
  46193. }
  46194. for (var index = 0; index < this._animatables.length; index++) {
  46195. var animatable = this._animatables[index];
  46196. animatable.stop();
  46197. }
  46198. this._isStarted = false;
  46199. return this;
  46200. };
  46201. /**
  46202. * Dispose all associated resources
  46203. */
  46204. AnimationGroup.prototype.dispose = function () {
  46205. this._targetedAnimations = [];
  46206. this._animatables = [];
  46207. var index = this._scene.animationGroups.indexOf(this);
  46208. if (index > -1) {
  46209. this._scene.animationGroups.splice(index, 1);
  46210. }
  46211. };
  46212. return AnimationGroup;
  46213. }());
  46214. BABYLON.AnimationGroup = AnimationGroup;
  46215. })(BABYLON || (BABYLON = {}));
  46216. //# sourceMappingURL=babylon.animationGroup.js.map
  46217. var BABYLON;
  46218. (function (BABYLON) {
  46219. var RuntimeAnimation = /** @class */ (function () {
  46220. function RuntimeAnimation(target, animation) {
  46221. this._offsetsCache = {};
  46222. this._highLimitsCache = {};
  46223. this._stopped = false;
  46224. this._blendingFactor = 0;
  46225. this._ratioOffset = 0;
  46226. this._animation = animation;
  46227. this._target = target;
  46228. animation._runtimeAnimations.push(this);
  46229. }
  46230. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  46231. get: function () {
  46232. return this._animation;
  46233. },
  46234. enumerable: true,
  46235. configurable: true
  46236. });
  46237. RuntimeAnimation.prototype.reset = function () {
  46238. this._offsetsCache = {};
  46239. this._highLimitsCache = {};
  46240. this.currentFrame = 0;
  46241. this._blendingFactor = 0;
  46242. this._originalBlendValue = null;
  46243. };
  46244. RuntimeAnimation.prototype.isStopped = function () {
  46245. return this._stopped;
  46246. };
  46247. RuntimeAnimation.prototype.dispose = function () {
  46248. var index = this._animation.runtimeAnimations.indexOf(this);
  46249. if (index > -1) {
  46250. this._animation.runtimeAnimations.splice(index, 1);
  46251. }
  46252. };
  46253. RuntimeAnimation.prototype._getKeyValue = function (value) {
  46254. if (typeof value === "function") {
  46255. return value();
  46256. }
  46257. return value;
  46258. };
  46259. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  46260. if (loopMode === BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  46261. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  46262. }
  46263. this.currentFrame = currentFrame;
  46264. var keys = this._animation.getKeys();
  46265. // Try to get a hash to find the right key
  46266. 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));
  46267. if (keys[startKeyIndex].frame >= currentFrame) {
  46268. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  46269. startKeyIndex--;
  46270. }
  46271. }
  46272. for (var key = startKeyIndex; key < keys.length; key++) {
  46273. var endKey = keys[key + 1];
  46274. if (endKey.frame >= currentFrame) {
  46275. var startKey = keys[key];
  46276. var startValue = this._getKeyValue(startKey.value);
  46277. if (startKey.interpolation === BABYLON.AnimationKeyInterpolation.STEP) {
  46278. return startValue;
  46279. }
  46280. var endValue = this._getKeyValue(endKey.value);
  46281. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  46282. var frameDelta = endKey.frame - startKey.frame;
  46283. // gradient : percent of currentFrame between the frame inf and the frame sup
  46284. var gradient = (currentFrame - startKey.frame) / frameDelta;
  46285. // check for easingFunction and correction of gradient
  46286. var easingFunction = this._animation.getEasingFunction();
  46287. if (easingFunction != null) {
  46288. gradient = easingFunction.ease(gradient);
  46289. }
  46290. switch (this._animation.dataType) {
  46291. // Float
  46292. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  46293. var floatValue = useTangent ? this._animation.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this._animation.floatInterpolateFunction(startValue, endValue, gradient);
  46294. switch (loopMode) {
  46295. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  46296. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  46297. return floatValue;
  46298. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  46299. return offsetValue * repeatCount + floatValue;
  46300. }
  46301. break;
  46302. // Quaternion
  46303. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  46304. var quatValue = useTangent ? this._animation.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.quaternionInterpolateFunction(startValue, endValue, gradient);
  46305. switch (loopMode) {
  46306. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  46307. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  46308. return quatValue;
  46309. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  46310. return quatValue.add(offsetValue.scale(repeatCount));
  46311. }
  46312. return quatValue;
  46313. // Vector3
  46314. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  46315. var vec3Value = useTangent ? this._animation.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector3InterpolateFunction(startValue, endValue, gradient);
  46316. switch (loopMode) {
  46317. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  46318. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  46319. return vec3Value;
  46320. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  46321. return vec3Value.add(offsetValue.scale(repeatCount));
  46322. }
  46323. // Vector2
  46324. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  46325. var vec2Value = useTangent ? this._animation.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector2InterpolateFunction(startValue, endValue, gradient);
  46326. switch (loopMode) {
  46327. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  46328. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  46329. return vec2Value;
  46330. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  46331. return vec2Value.add(offsetValue.scale(repeatCount));
  46332. }
  46333. // Size
  46334. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  46335. switch (loopMode) {
  46336. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  46337. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  46338. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient);
  46339. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  46340. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  46341. }
  46342. // Color3
  46343. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  46344. switch (loopMode) {
  46345. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  46346. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  46347. return this._animation.color3InterpolateFunction(startValue, endValue, gradient);
  46348. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  46349. return this._animation.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  46350. }
  46351. // Matrix
  46352. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  46353. switch (loopMode) {
  46354. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  46355. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  46356. if (BABYLON.Animation.AllowMatricesInterpolation) {
  46357. return this._animation.matrixInterpolateFunction(startValue, endValue, gradient);
  46358. }
  46359. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  46360. return startValue;
  46361. }
  46362. default:
  46363. break;
  46364. }
  46365. break;
  46366. }
  46367. }
  46368. return this._getKeyValue(keys[keys.length - 1].value);
  46369. };
  46370. RuntimeAnimation.prototype.setValue = function (currentValue, blend) {
  46371. if (blend === void 0) { blend = false; }
  46372. // Set value
  46373. var path;
  46374. var destination;
  46375. var targetPropertyPath = this._animation.targetPropertyPath;
  46376. if (targetPropertyPath.length > 1) {
  46377. var property = this._target[targetPropertyPath[0]];
  46378. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  46379. property = property[targetPropertyPath[index]];
  46380. }
  46381. path = targetPropertyPath[targetPropertyPath.length - 1];
  46382. destination = property;
  46383. }
  46384. else {
  46385. path = targetPropertyPath[0];
  46386. destination = this._target;
  46387. }
  46388. // Blending
  46389. if (this._animation.enableBlending && this._blendingFactor <= 1.0) {
  46390. if (!this._originalBlendValue) {
  46391. if (destination[path].clone) {
  46392. this._originalBlendValue = destination[path].clone();
  46393. }
  46394. else {
  46395. this._originalBlendValue = destination[path];
  46396. }
  46397. }
  46398. if (this._originalBlendValue.prototype) {
  46399. if (this._originalBlendValue.prototype.Lerp) {
  46400. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  46401. }
  46402. else {
  46403. destination[path] = currentValue;
  46404. }
  46405. }
  46406. else if (this._originalBlendValue.m) {
  46407. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  46408. }
  46409. else {
  46410. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  46411. }
  46412. this._blendingFactor += this._animation.blendingSpeed;
  46413. }
  46414. else {
  46415. destination[path] = currentValue;
  46416. }
  46417. if (this._target.markAsDirty) {
  46418. this._target.markAsDirty(this._animation.targetProperty);
  46419. }
  46420. };
  46421. RuntimeAnimation.prototype.goToFrame = function (frame) {
  46422. var keys = this._animation.getKeys();
  46423. if (frame < keys[0].frame) {
  46424. frame = keys[0].frame;
  46425. }
  46426. else if (frame > keys[keys.length - 1].frame) {
  46427. frame = keys[keys.length - 1].frame;
  46428. }
  46429. var currentValue = this._interpolate(frame, 0, this._animation.loopMode);
  46430. this.setValue(currentValue);
  46431. };
  46432. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  46433. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  46434. this._ratioOffset = this._previousRatio - newRatio;
  46435. };
  46436. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  46437. if (blend === void 0) { blend = false; }
  46438. var targetPropertyPath = this._animation.targetPropertyPath;
  46439. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  46440. this._stopped = true;
  46441. return false;
  46442. }
  46443. var returnValue = true;
  46444. var keys = this._animation.getKeys();
  46445. // Adding a start key at frame 0 if missing
  46446. if (keys[0].frame !== 0) {
  46447. var newKey = { frame: 0, value: keys[0].value };
  46448. keys.splice(0, 0, newKey);
  46449. }
  46450. // Check limits
  46451. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  46452. from = keys[0].frame;
  46453. }
  46454. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  46455. to = keys[keys.length - 1].frame;
  46456. }
  46457. //to and from cannot be the same key
  46458. if (from === to) {
  46459. if (from > keys[0].frame) {
  46460. from--;
  46461. }
  46462. else if (to < keys[keys.length - 1].frame) {
  46463. to++;
  46464. }
  46465. }
  46466. // Compute ratio
  46467. var range = to - from;
  46468. var offsetValue;
  46469. // ratio represents the frame delta between from and to
  46470. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  46471. var highLimitValue = 0;
  46472. this._previousDelay = delay;
  46473. this._previousRatio = ratio;
  46474. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) {
  46475. returnValue = false;
  46476. highLimitValue = this._getKeyValue(keys[keys.length - 1].value);
  46477. }
  46478. else {
  46479. // Get max value if required
  46480. if (this._animation.loopMode !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  46481. var keyOffset = to.toString() + from.toString();
  46482. if (!this._offsetsCache[keyOffset]) {
  46483. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  46484. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  46485. switch (this._animation.dataType) {
  46486. // Float
  46487. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  46488. this._offsetsCache[keyOffset] = toValue - fromValue;
  46489. break;
  46490. // Quaternion
  46491. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  46492. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  46493. break;
  46494. // Vector3
  46495. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  46496. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  46497. // Vector2
  46498. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  46499. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  46500. // Size
  46501. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  46502. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  46503. // Color3
  46504. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  46505. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  46506. default:
  46507. break;
  46508. }
  46509. this._highLimitsCache[keyOffset] = toValue;
  46510. }
  46511. highLimitValue = this._highLimitsCache[keyOffset];
  46512. offsetValue = this._offsetsCache[keyOffset];
  46513. }
  46514. }
  46515. if (offsetValue === undefined) {
  46516. switch (this._animation.dataType) {
  46517. // Float
  46518. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  46519. offsetValue = 0;
  46520. break;
  46521. // Quaternion
  46522. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  46523. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  46524. break;
  46525. // Vector3
  46526. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  46527. offsetValue = BABYLON.Vector3.Zero();
  46528. break;
  46529. // Vector2
  46530. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  46531. offsetValue = BABYLON.Vector2.Zero();
  46532. break;
  46533. // Size
  46534. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  46535. offsetValue = BABYLON.Size.Zero();
  46536. break;
  46537. // Color3
  46538. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  46539. offsetValue = BABYLON.Color3.Black();
  46540. }
  46541. }
  46542. // Compute value
  46543. var repeatCount = (ratio / range) >> 0;
  46544. var currentFrame = returnValue ? from + ratio % range : to;
  46545. var currentValue = this._interpolate(currentFrame, repeatCount, this._animation.loopMode, offsetValue, highLimitValue);
  46546. // Set value
  46547. this.setValue(currentValue);
  46548. // Check events
  46549. var events = this._animation.getEvents();
  46550. for (var index = 0; index < events.length; index++) {
  46551. // Make sure current frame has passed event frame and that event frame is within the current range
  46552. // Also, handle both forward and reverse animations
  46553. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  46554. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  46555. var event = events[index];
  46556. if (!event.isDone) {
  46557. // If event should be done only once, remove it.
  46558. if (event.onlyOnce) {
  46559. events.splice(index, 1);
  46560. index--;
  46561. }
  46562. event.isDone = true;
  46563. event.action();
  46564. } // Don't do anything if the event has already be done.
  46565. }
  46566. else if (events[index].isDone && !events[index].onlyOnce) {
  46567. // reset event, the animation is looping
  46568. events[index].isDone = false;
  46569. }
  46570. }
  46571. if (!returnValue) {
  46572. this._stopped = true;
  46573. }
  46574. return returnValue;
  46575. };
  46576. return RuntimeAnimation;
  46577. }());
  46578. BABYLON.RuntimeAnimation = RuntimeAnimation;
  46579. })(BABYLON || (BABYLON = {}));
  46580. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  46581. var BABYLON;
  46582. (function (BABYLON) {
  46583. var Animatable = /** @class */ (function () {
  46584. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  46585. if (fromFrame === void 0) { fromFrame = 0; }
  46586. if (toFrame === void 0) { toFrame = 100; }
  46587. if (loopAnimation === void 0) { loopAnimation = false; }
  46588. if (speedRatio === void 0) { speedRatio = 1.0; }
  46589. this.target = target;
  46590. this.fromFrame = fromFrame;
  46591. this.toFrame = toFrame;
  46592. this.loopAnimation = loopAnimation;
  46593. this.onAnimationEnd = onAnimationEnd;
  46594. this._localDelayOffset = null;
  46595. this._pausedDelay = null;
  46596. this._runtimeAnimations = new Array();
  46597. this._paused = false;
  46598. this._speedRatio = 1;
  46599. this.animationStarted = false;
  46600. if (animations) {
  46601. this.appendAnimations(target, animations);
  46602. }
  46603. this._speedRatio = speedRatio;
  46604. this._scene = scene;
  46605. scene._activeAnimatables.push(this);
  46606. }
  46607. Object.defineProperty(Animatable.prototype, "speedRatio", {
  46608. get: function () {
  46609. return this._speedRatio;
  46610. },
  46611. set: function (value) {
  46612. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  46613. var animation = this._runtimeAnimations[index];
  46614. animation._prepareForSpeedRatioChange(value);
  46615. }
  46616. this._speedRatio = value;
  46617. },
  46618. enumerable: true,
  46619. configurable: true
  46620. });
  46621. // Methods
  46622. Animatable.prototype.getAnimations = function () {
  46623. return this._runtimeAnimations;
  46624. };
  46625. Animatable.prototype.appendAnimations = function (target, animations) {
  46626. for (var index = 0; index < animations.length; index++) {
  46627. var animation = animations[index];
  46628. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation));
  46629. }
  46630. };
  46631. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  46632. var runtimeAnimations = this._runtimeAnimations;
  46633. for (var index = 0; index < runtimeAnimations.length; index++) {
  46634. if (runtimeAnimations[index].animation.targetProperty === property) {
  46635. return runtimeAnimations[index].animation;
  46636. }
  46637. }
  46638. return null;
  46639. };
  46640. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  46641. var runtimeAnimations = this._runtimeAnimations;
  46642. for (var index = 0; index < runtimeAnimations.length; index++) {
  46643. if (runtimeAnimations[index].animation.targetProperty === property) {
  46644. return runtimeAnimations[index];
  46645. }
  46646. }
  46647. return null;
  46648. };
  46649. Animatable.prototype.reset = function () {
  46650. var runtimeAnimations = this._runtimeAnimations;
  46651. for (var index = 0; index < runtimeAnimations.length; index++) {
  46652. runtimeAnimations[index].reset();
  46653. }
  46654. // Reset to original value
  46655. for (index = 0; index < runtimeAnimations.length; index++) {
  46656. var animation = runtimeAnimations[index];
  46657. animation.animate(0, this.fromFrame, this.toFrame, false, this._speedRatio);
  46658. }
  46659. this._localDelayOffset = null;
  46660. this._pausedDelay = null;
  46661. };
  46662. Animatable.prototype.enableBlending = function (blendingSpeed) {
  46663. var runtimeAnimations = this._runtimeAnimations;
  46664. for (var index = 0; index < runtimeAnimations.length; index++) {
  46665. runtimeAnimations[index].animation.enableBlending = true;
  46666. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  46667. }
  46668. };
  46669. Animatable.prototype.disableBlending = function () {
  46670. var runtimeAnimations = this._runtimeAnimations;
  46671. for (var index = 0; index < runtimeAnimations.length; index++) {
  46672. runtimeAnimations[index].animation.enableBlending = false;
  46673. }
  46674. };
  46675. Animatable.prototype.goToFrame = function (frame) {
  46676. var runtimeAnimations = this._runtimeAnimations;
  46677. if (runtimeAnimations[0]) {
  46678. var fps = runtimeAnimations[0].animation.framePerSecond;
  46679. var currentFrame = runtimeAnimations[0].currentFrame;
  46680. var adjustTime = frame - currentFrame;
  46681. var delay = adjustTime * 1000 / fps;
  46682. if (this._localDelayOffset === null) {
  46683. this._localDelayOffset = 0;
  46684. }
  46685. this._localDelayOffset -= delay;
  46686. }
  46687. for (var index = 0; index < runtimeAnimations.length; index++) {
  46688. runtimeAnimations[index].goToFrame(frame);
  46689. }
  46690. };
  46691. Animatable.prototype.pause = function () {
  46692. if (this._paused) {
  46693. return;
  46694. }
  46695. this._paused = true;
  46696. };
  46697. Animatable.prototype.restart = function () {
  46698. this._paused = false;
  46699. };
  46700. Animatable.prototype.stop = function (animationName) {
  46701. if (animationName) {
  46702. var idx = this._scene._activeAnimatables.indexOf(this);
  46703. if (idx > -1) {
  46704. var runtimeAnimations = this._runtimeAnimations;
  46705. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  46706. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  46707. continue;
  46708. }
  46709. runtimeAnimations[index].dispose();
  46710. runtimeAnimations.splice(index, 1);
  46711. }
  46712. if (runtimeAnimations.length == 0) {
  46713. this._scene._activeAnimatables.splice(idx, 1);
  46714. if (this.onAnimationEnd) {
  46715. this.onAnimationEnd();
  46716. }
  46717. }
  46718. }
  46719. }
  46720. else {
  46721. var index = this._scene._activeAnimatables.indexOf(this);
  46722. if (index > -1) {
  46723. this._scene._activeAnimatables.splice(index, 1);
  46724. var runtimeAnimations = this._runtimeAnimations;
  46725. for (var index = 0; index < runtimeAnimations.length; index++) {
  46726. runtimeAnimations[index].dispose();
  46727. }
  46728. if (this.onAnimationEnd) {
  46729. this.onAnimationEnd();
  46730. }
  46731. }
  46732. }
  46733. };
  46734. Animatable.prototype._animate = function (delay) {
  46735. if (this._paused) {
  46736. this.animationStarted = false;
  46737. if (this._pausedDelay === null) {
  46738. this._pausedDelay = delay;
  46739. }
  46740. return true;
  46741. }
  46742. if (this._localDelayOffset === null) {
  46743. this._localDelayOffset = delay;
  46744. this._pausedDelay = null;
  46745. }
  46746. else if (this._pausedDelay !== null) {
  46747. this._localDelayOffset += delay - this._pausedDelay;
  46748. this._pausedDelay = null;
  46749. }
  46750. // Animating
  46751. var running = false;
  46752. var runtimeAnimations = this._runtimeAnimations;
  46753. var index;
  46754. for (index = 0; index < runtimeAnimations.length; index++) {
  46755. var animation = runtimeAnimations[index];
  46756. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio);
  46757. running = running || isRunning;
  46758. }
  46759. this.animationStarted = running;
  46760. if (!running) {
  46761. // Remove from active animatables
  46762. index = this._scene._activeAnimatables.indexOf(this);
  46763. this._scene._activeAnimatables.splice(index, 1);
  46764. // Dispose all runtime animations
  46765. for (index = 0; index < runtimeAnimations.length; index++) {
  46766. runtimeAnimations[index].dispose();
  46767. }
  46768. }
  46769. if (!running && this.onAnimationEnd) {
  46770. this.onAnimationEnd();
  46771. this.onAnimationEnd = null;
  46772. }
  46773. return running;
  46774. };
  46775. return Animatable;
  46776. }());
  46777. BABYLON.Animatable = Animatable;
  46778. })(BABYLON || (BABYLON = {}));
  46779. //# sourceMappingURL=babylon.animatable.js.map
  46780. var BABYLON;
  46781. (function (BABYLON) {
  46782. var EasingFunction = /** @class */ (function () {
  46783. function EasingFunction() {
  46784. // Properties
  46785. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  46786. }
  46787. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  46788. get: function () {
  46789. return EasingFunction._EASINGMODE_EASEIN;
  46790. },
  46791. enumerable: true,
  46792. configurable: true
  46793. });
  46794. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  46795. get: function () {
  46796. return EasingFunction._EASINGMODE_EASEOUT;
  46797. },
  46798. enumerable: true,
  46799. configurable: true
  46800. });
  46801. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  46802. get: function () {
  46803. return EasingFunction._EASINGMODE_EASEINOUT;
  46804. },
  46805. enumerable: true,
  46806. configurable: true
  46807. });
  46808. EasingFunction.prototype.setEasingMode = function (easingMode) {
  46809. var n = Math.min(Math.max(easingMode, 0), 2);
  46810. this._easingMode = n;
  46811. };
  46812. EasingFunction.prototype.getEasingMode = function () {
  46813. return this._easingMode;
  46814. };
  46815. EasingFunction.prototype.easeInCore = function (gradient) {
  46816. throw new Error('You must implement this method');
  46817. };
  46818. EasingFunction.prototype.ease = function (gradient) {
  46819. switch (this._easingMode) {
  46820. case EasingFunction.EASINGMODE_EASEIN:
  46821. return this.easeInCore(gradient);
  46822. case EasingFunction.EASINGMODE_EASEOUT:
  46823. return (1 - this.easeInCore(1 - gradient));
  46824. }
  46825. if (gradient >= 0.5) {
  46826. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  46827. }
  46828. return (this.easeInCore(gradient * 2) * 0.5);
  46829. };
  46830. //Statics
  46831. EasingFunction._EASINGMODE_EASEIN = 0;
  46832. EasingFunction._EASINGMODE_EASEOUT = 1;
  46833. EasingFunction._EASINGMODE_EASEINOUT = 2;
  46834. return EasingFunction;
  46835. }());
  46836. BABYLON.EasingFunction = EasingFunction;
  46837. var CircleEase = /** @class */ (function (_super) {
  46838. __extends(CircleEase, _super);
  46839. function CircleEase() {
  46840. return _super !== null && _super.apply(this, arguments) || this;
  46841. }
  46842. CircleEase.prototype.easeInCore = function (gradient) {
  46843. gradient = Math.max(0, Math.min(1, gradient));
  46844. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  46845. };
  46846. return CircleEase;
  46847. }(EasingFunction));
  46848. BABYLON.CircleEase = CircleEase;
  46849. var BackEase = /** @class */ (function (_super) {
  46850. __extends(BackEase, _super);
  46851. function BackEase(amplitude) {
  46852. if (amplitude === void 0) { amplitude = 1; }
  46853. var _this = _super.call(this) || this;
  46854. _this.amplitude = amplitude;
  46855. return _this;
  46856. }
  46857. BackEase.prototype.easeInCore = function (gradient) {
  46858. var num = Math.max(0, this.amplitude);
  46859. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  46860. };
  46861. return BackEase;
  46862. }(EasingFunction));
  46863. BABYLON.BackEase = BackEase;
  46864. var BounceEase = /** @class */ (function (_super) {
  46865. __extends(BounceEase, _super);
  46866. function BounceEase(bounces, bounciness) {
  46867. if (bounces === void 0) { bounces = 3; }
  46868. if (bounciness === void 0) { bounciness = 2; }
  46869. var _this = _super.call(this) || this;
  46870. _this.bounces = bounces;
  46871. _this.bounciness = bounciness;
  46872. return _this;
  46873. }
  46874. BounceEase.prototype.easeInCore = function (gradient) {
  46875. var y = Math.max(0.0, this.bounces);
  46876. var bounciness = this.bounciness;
  46877. if (bounciness <= 1.0) {
  46878. bounciness = 1.001;
  46879. }
  46880. var num9 = Math.pow(bounciness, y);
  46881. var num5 = 1.0 - bounciness;
  46882. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  46883. var num15 = gradient * num4;
  46884. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  46885. var num3 = Math.floor(num65);
  46886. var num13 = num3 + 1.0;
  46887. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  46888. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  46889. var num7 = (num8 + num12) * 0.5;
  46890. var num6 = gradient - num7;
  46891. var num2 = num7 - num8;
  46892. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  46893. };
  46894. return BounceEase;
  46895. }(EasingFunction));
  46896. BABYLON.BounceEase = BounceEase;
  46897. var CubicEase = /** @class */ (function (_super) {
  46898. __extends(CubicEase, _super);
  46899. function CubicEase() {
  46900. return _super !== null && _super.apply(this, arguments) || this;
  46901. }
  46902. CubicEase.prototype.easeInCore = function (gradient) {
  46903. return (gradient * gradient * gradient);
  46904. };
  46905. return CubicEase;
  46906. }(EasingFunction));
  46907. BABYLON.CubicEase = CubicEase;
  46908. var ElasticEase = /** @class */ (function (_super) {
  46909. __extends(ElasticEase, _super);
  46910. function ElasticEase(oscillations, springiness) {
  46911. if (oscillations === void 0) { oscillations = 3; }
  46912. if (springiness === void 0) { springiness = 3; }
  46913. var _this = _super.call(this) || this;
  46914. _this.oscillations = oscillations;
  46915. _this.springiness = springiness;
  46916. return _this;
  46917. }
  46918. ElasticEase.prototype.easeInCore = function (gradient) {
  46919. var num2;
  46920. var num3 = Math.max(0.0, this.oscillations);
  46921. var num = Math.max(0.0, this.springiness);
  46922. if (num == 0) {
  46923. num2 = gradient;
  46924. }
  46925. else {
  46926. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  46927. }
  46928. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  46929. };
  46930. return ElasticEase;
  46931. }(EasingFunction));
  46932. BABYLON.ElasticEase = ElasticEase;
  46933. var ExponentialEase = /** @class */ (function (_super) {
  46934. __extends(ExponentialEase, _super);
  46935. function ExponentialEase(exponent) {
  46936. if (exponent === void 0) { exponent = 2; }
  46937. var _this = _super.call(this) || this;
  46938. _this.exponent = exponent;
  46939. return _this;
  46940. }
  46941. ExponentialEase.prototype.easeInCore = function (gradient) {
  46942. if (this.exponent <= 0) {
  46943. return gradient;
  46944. }
  46945. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  46946. };
  46947. return ExponentialEase;
  46948. }(EasingFunction));
  46949. BABYLON.ExponentialEase = ExponentialEase;
  46950. var PowerEase = /** @class */ (function (_super) {
  46951. __extends(PowerEase, _super);
  46952. function PowerEase(power) {
  46953. if (power === void 0) { power = 2; }
  46954. var _this = _super.call(this) || this;
  46955. _this.power = power;
  46956. return _this;
  46957. }
  46958. PowerEase.prototype.easeInCore = function (gradient) {
  46959. var y = Math.max(0.0, this.power);
  46960. return Math.pow(gradient, y);
  46961. };
  46962. return PowerEase;
  46963. }(EasingFunction));
  46964. BABYLON.PowerEase = PowerEase;
  46965. var QuadraticEase = /** @class */ (function (_super) {
  46966. __extends(QuadraticEase, _super);
  46967. function QuadraticEase() {
  46968. return _super !== null && _super.apply(this, arguments) || this;
  46969. }
  46970. QuadraticEase.prototype.easeInCore = function (gradient) {
  46971. return (gradient * gradient);
  46972. };
  46973. return QuadraticEase;
  46974. }(EasingFunction));
  46975. BABYLON.QuadraticEase = QuadraticEase;
  46976. var QuarticEase = /** @class */ (function (_super) {
  46977. __extends(QuarticEase, _super);
  46978. function QuarticEase() {
  46979. return _super !== null && _super.apply(this, arguments) || this;
  46980. }
  46981. QuarticEase.prototype.easeInCore = function (gradient) {
  46982. return (gradient * gradient * gradient * gradient);
  46983. };
  46984. return QuarticEase;
  46985. }(EasingFunction));
  46986. BABYLON.QuarticEase = QuarticEase;
  46987. var QuinticEase = /** @class */ (function (_super) {
  46988. __extends(QuinticEase, _super);
  46989. function QuinticEase() {
  46990. return _super !== null && _super.apply(this, arguments) || this;
  46991. }
  46992. QuinticEase.prototype.easeInCore = function (gradient) {
  46993. return (gradient * gradient * gradient * gradient * gradient);
  46994. };
  46995. return QuinticEase;
  46996. }(EasingFunction));
  46997. BABYLON.QuinticEase = QuinticEase;
  46998. var SineEase = /** @class */ (function (_super) {
  46999. __extends(SineEase, _super);
  47000. function SineEase() {
  47001. return _super !== null && _super.apply(this, arguments) || this;
  47002. }
  47003. SineEase.prototype.easeInCore = function (gradient) {
  47004. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  47005. };
  47006. return SineEase;
  47007. }(EasingFunction));
  47008. BABYLON.SineEase = SineEase;
  47009. var BezierCurveEase = /** @class */ (function (_super) {
  47010. __extends(BezierCurveEase, _super);
  47011. function BezierCurveEase(x1, y1, x2, y2) {
  47012. if (x1 === void 0) { x1 = 0; }
  47013. if (y1 === void 0) { y1 = 0; }
  47014. if (x2 === void 0) { x2 = 1; }
  47015. if (y2 === void 0) { y2 = 1; }
  47016. var _this = _super.call(this) || this;
  47017. _this.x1 = x1;
  47018. _this.y1 = y1;
  47019. _this.x2 = x2;
  47020. _this.y2 = y2;
  47021. return _this;
  47022. }
  47023. BezierCurveEase.prototype.easeInCore = function (gradient) {
  47024. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  47025. };
  47026. return BezierCurveEase;
  47027. }(EasingFunction));
  47028. BABYLON.BezierCurveEase = BezierCurveEase;
  47029. })(BABYLON || (BABYLON = {}));
  47030. //# sourceMappingURL=babylon.easing.js.map
  47031. var BABYLON;
  47032. (function (BABYLON) {
  47033. var Condition = /** @class */ (function () {
  47034. function Condition(actionManager) {
  47035. this._actionManager = actionManager;
  47036. }
  47037. Condition.prototype.isValid = function () {
  47038. return true;
  47039. };
  47040. Condition.prototype._getProperty = function (propertyPath) {
  47041. return this._actionManager._getProperty(propertyPath);
  47042. };
  47043. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  47044. return this._actionManager._getEffectiveTarget(target, propertyPath);
  47045. };
  47046. Condition.prototype.serialize = function () {
  47047. };
  47048. Condition.prototype._serialize = function (serializedCondition) {
  47049. return {
  47050. type: 2,
  47051. children: [],
  47052. name: serializedCondition.name,
  47053. properties: serializedCondition.properties
  47054. };
  47055. };
  47056. return Condition;
  47057. }());
  47058. BABYLON.Condition = Condition;
  47059. var ValueCondition = /** @class */ (function (_super) {
  47060. __extends(ValueCondition, _super);
  47061. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  47062. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  47063. var _this = _super.call(this, actionManager) || this;
  47064. _this.propertyPath = propertyPath;
  47065. _this.value = value;
  47066. _this.operator = operator;
  47067. _this._target = target;
  47068. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  47069. _this._property = _this._getProperty(_this.propertyPath);
  47070. return _this;
  47071. }
  47072. Object.defineProperty(ValueCondition, "IsEqual", {
  47073. get: function () {
  47074. return ValueCondition._IsEqual;
  47075. },
  47076. enumerable: true,
  47077. configurable: true
  47078. });
  47079. Object.defineProperty(ValueCondition, "IsDifferent", {
  47080. get: function () {
  47081. return ValueCondition._IsDifferent;
  47082. },
  47083. enumerable: true,
  47084. configurable: true
  47085. });
  47086. Object.defineProperty(ValueCondition, "IsGreater", {
  47087. get: function () {
  47088. return ValueCondition._IsGreater;
  47089. },
  47090. enumerable: true,
  47091. configurable: true
  47092. });
  47093. Object.defineProperty(ValueCondition, "IsLesser", {
  47094. get: function () {
  47095. return ValueCondition._IsLesser;
  47096. },
  47097. enumerable: true,
  47098. configurable: true
  47099. });
  47100. // Methods
  47101. ValueCondition.prototype.isValid = function () {
  47102. switch (this.operator) {
  47103. case ValueCondition.IsGreater:
  47104. return this._effectiveTarget[this._property] > this.value;
  47105. case ValueCondition.IsLesser:
  47106. return this._effectiveTarget[this._property] < this.value;
  47107. case ValueCondition.IsEqual:
  47108. case ValueCondition.IsDifferent:
  47109. var check;
  47110. if (this.value.equals) {
  47111. check = this.value.equals(this._effectiveTarget[this._property]);
  47112. }
  47113. else {
  47114. check = this.value === this._effectiveTarget[this._property];
  47115. }
  47116. return this.operator === ValueCondition.IsEqual ? check : !check;
  47117. }
  47118. return false;
  47119. };
  47120. ValueCondition.prototype.serialize = function () {
  47121. return this._serialize({
  47122. name: "ValueCondition",
  47123. properties: [
  47124. BABYLON.Action._GetTargetProperty(this._target),
  47125. { name: "propertyPath", value: this.propertyPath },
  47126. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  47127. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  47128. ]
  47129. });
  47130. };
  47131. ValueCondition.GetOperatorName = function (operator) {
  47132. switch (operator) {
  47133. case ValueCondition._IsEqual: return "IsEqual";
  47134. case ValueCondition._IsDifferent: return "IsDifferent";
  47135. case ValueCondition._IsGreater: return "IsGreater";
  47136. case ValueCondition._IsLesser: return "IsLesser";
  47137. default: return "";
  47138. }
  47139. };
  47140. // Statics
  47141. ValueCondition._IsEqual = 0;
  47142. ValueCondition._IsDifferent = 1;
  47143. ValueCondition._IsGreater = 2;
  47144. ValueCondition._IsLesser = 3;
  47145. return ValueCondition;
  47146. }(Condition));
  47147. BABYLON.ValueCondition = ValueCondition;
  47148. var PredicateCondition = /** @class */ (function (_super) {
  47149. __extends(PredicateCondition, _super);
  47150. function PredicateCondition(actionManager, predicate) {
  47151. var _this = _super.call(this, actionManager) || this;
  47152. _this.predicate = predicate;
  47153. return _this;
  47154. }
  47155. PredicateCondition.prototype.isValid = function () {
  47156. return this.predicate();
  47157. };
  47158. return PredicateCondition;
  47159. }(Condition));
  47160. BABYLON.PredicateCondition = PredicateCondition;
  47161. var StateCondition = /** @class */ (function (_super) {
  47162. __extends(StateCondition, _super);
  47163. function StateCondition(actionManager, target, value) {
  47164. var _this = _super.call(this, actionManager) || this;
  47165. _this.value = value;
  47166. _this._target = target;
  47167. return _this;
  47168. }
  47169. // Methods
  47170. StateCondition.prototype.isValid = function () {
  47171. return this._target.state === this.value;
  47172. };
  47173. StateCondition.prototype.serialize = function () {
  47174. return this._serialize({
  47175. name: "StateCondition",
  47176. properties: [
  47177. BABYLON.Action._GetTargetProperty(this._target),
  47178. { name: "value", value: this.value }
  47179. ]
  47180. });
  47181. };
  47182. return StateCondition;
  47183. }(Condition));
  47184. BABYLON.StateCondition = StateCondition;
  47185. })(BABYLON || (BABYLON = {}));
  47186. //# sourceMappingURL=babylon.condition.js.map
  47187. var BABYLON;
  47188. (function (BABYLON) {
  47189. var Action = /** @class */ (function () {
  47190. function Action(triggerOptions, condition) {
  47191. this.triggerOptions = triggerOptions;
  47192. this.onBeforeExecuteObservable = new BABYLON.Observable();
  47193. if (triggerOptions.parameter) {
  47194. this.trigger = triggerOptions.trigger;
  47195. this._triggerParameter = triggerOptions.parameter;
  47196. }
  47197. else {
  47198. this.trigger = triggerOptions;
  47199. }
  47200. this._nextActiveAction = this;
  47201. this._condition = condition;
  47202. }
  47203. // Methods
  47204. Action.prototype._prepare = function () {
  47205. };
  47206. Action.prototype.getTriggerParameter = function () {
  47207. return this._triggerParameter;
  47208. };
  47209. Action.prototype._executeCurrent = function (evt) {
  47210. if (this._nextActiveAction._condition) {
  47211. var condition = this._nextActiveAction._condition;
  47212. var currentRenderId = this._actionManager.getScene().getRenderId();
  47213. // We cache the current evaluation for the current frame
  47214. if (condition._evaluationId === currentRenderId) {
  47215. if (!condition._currentResult) {
  47216. return;
  47217. }
  47218. }
  47219. else {
  47220. condition._evaluationId = currentRenderId;
  47221. if (!condition.isValid()) {
  47222. condition._currentResult = false;
  47223. return;
  47224. }
  47225. condition._currentResult = true;
  47226. }
  47227. }
  47228. this.onBeforeExecuteObservable.notifyObservers(this);
  47229. this._nextActiveAction.execute(evt);
  47230. this.skipToNextActiveAction();
  47231. };
  47232. Action.prototype.execute = function (evt) {
  47233. };
  47234. Action.prototype.skipToNextActiveAction = function () {
  47235. if (this._nextActiveAction._child) {
  47236. if (!this._nextActiveAction._child._actionManager) {
  47237. this._nextActiveAction._child._actionManager = this._actionManager;
  47238. }
  47239. this._nextActiveAction = this._nextActiveAction._child;
  47240. }
  47241. else {
  47242. this._nextActiveAction = this;
  47243. }
  47244. };
  47245. Action.prototype.then = function (action) {
  47246. this._child = action;
  47247. action._actionManager = this._actionManager;
  47248. action._prepare();
  47249. return action;
  47250. };
  47251. Action.prototype._getProperty = function (propertyPath) {
  47252. return this._actionManager._getProperty(propertyPath);
  47253. };
  47254. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  47255. return this._actionManager._getEffectiveTarget(target, propertyPath);
  47256. };
  47257. Action.prototype.serialize = function (parent) {
  47258. };
  47259. // Called by BABYLON.Action objects in serialize(...). Internal use
  47260. Action.prototype._serialize = function (serializedAction, parent) {
  47261. var serializationObject = {
  47262. type: 1,
  47263. children: [],
  47264. name: serializedAction.name,
  47265. properties: serializedAction.properties || []
  47266. };
  47267. // Serialize child
  47268. if (this._child) {
  47269. this._child.serialize(serializationObject);
  47270. }
  47271. // Check if "this" has a condition
  47272. if (this._condition) {
  47273. var serializedCondition = this._condition.serialize();
  47274. serializedCondition.children.push(serializationObject);
  47275. if (parent) {
  47276. parent.children.push(serializedCondition);
  47277. }
  47278. return serializedCondition;
  47279. }
  47280. if (parent) {
  47281. parent.children.push(serializationObject);
  47282. }
  47283. return serializationObject;
  47284. };
  47285. Action._SerializeValueAsString = function (value) {
  47286. if (typeof value === "number") {
  47287. return value.toString();
  47288. }
  47289. if (typeof value === "boolean") {
  47290. return value ? "true" : "false";
  47291. }
  47292. if (value instanceof BABYLON.Vector2) {
  47293. return value.x + ", " + value.y;
  47294. }
  47295. if (value instanceof BABYLON.Vector3) {
  47296. return value.x + ", " + value.y + ", " + value.z;
  47297. }
  47298. if (value instanceof BABYLON.Color3) {
  47299. return value.r + ", " + value.g + ", " + value.b;
  47300. }
  47301. if (value instanceof BABYLON.Color4) {
  47302. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  47303. }
  47304. return value; // string
  47305. };
  47306. Action._GetTargetProperty = function (target) {
  47307. return {
  47308. name: "target",
  47309. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  47310. : target instanceof BABYLON.Light ? "LightProperties"
  47311. : target instanceof BABYLON.Camera ? "CameraProperties"
  47312. : "SceneProperties",
  47313. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  47314. };
  47315. };
  47316. return Action;
  47317. }());
  47318. BABYLON.Action = Action;
  47319. })(BABYLON || (BABYLON = {}));
  47320. //# sourceMappingURL=babylon.action.js.map
  47321. var BABYLON;
  47322. (function (BABYLON) {
  47323. /**
  47324. * ActionEvent is the event beint sent when an action is triggered.
  47325. */
  47326. var ActionEvent = /** @class */ (function () {
  47327. /**
  47328. * @param source The mesh or sprite that triggered the action.
  47329. * @param pointerX The X mouse cursor position at the time of the event
  47330. * @param pointerY The Y mouse cursor position at the time of the event
  47331. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  47332. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  47333. */
  47334. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  47335. this.source = source;
  47336. this.pointerX = pointerX;
  47337. this.pointerY = pointerY;
  47338. this.meshUnderPointer = meshUnderPointer;
  47339. this.sourceEvent = sourceEvent;
  47340. this.additionalData = additionalData;
  47341. }
  47342. /**
  47343. * Helper function to auto-create an ActionEvent from a source mesh.
  47344. * @param source The source mesh that triggered the event
  47345. * @param evt {Event} The original (browser) event
  47346. */
  47347. ActionEvent.CreateNew = function (source, evt, additionalData) {
  47348. var scene = source.getScene();
  47349. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  47350. };
  47351. /**
  47352. * Helper function to auto-create an ActionEvent from a source mesh.
  47353. * @param source The source sprite that triggered the event
  47354. * @param scene Scene associated with the sprite
  47355. * @param evt {Event} The original (browser) event
  47356. */
  47357. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  47358. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  47359. };
  47360. /**
  47361. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  47362. * @param scene the scene where the event occurred
  47363. * @param evt {Event} The original (browser) event
  47364. */
  47365. ActionEvent.CreateNewFromScene = function (scene, evt) {
  47366. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  47367. };
  47368. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  47369. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  47370. };
  47371. return ActionEvent;
  47372. }());
  47373. BABYLON.ActionEvent = ActionEvent;
  47374. /**
  47375. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  47376. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  47377. */
  47378. var ActionManager = /** @class */ (function () {
  47379. function ActionManager(scene) {
  47380. // Members
  47381. this.actions = new Array();
  47382. this.hoverCursor = '';
  47383. this._scene = scene;
  47384. scene._actionManagers.push(this);
  47385. }
  47386. Object.defineProperty(ActionManager, "NothingTrigger", {
  47387. get: function () {
  47388. return ActionManager._NothingTrigger;
  47389. },
  47390. enumerable: true,
  47391. configurable: true
  47392. });
  47393. Object.defineProperty(ActionManager, "OnPickTrigger", {
  47394. get: function () {
  47395. return ActionManager._OnPickTrigger;
  47396. },
  47397. enumerable: true,
  47398. configurable: true
  47399. });
  47400. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  47401. get: function () {
  47402. return ActionManager._OnLeftPickTrigger;
  47403. },
  47404. enumerable: true,
  47405. configurable: true
  47406. });
  47407. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  47408. get: function () {
  47409. return ActionManager._OnRightPickTrigger;
  47410. },
  47411. enumerable: true,
  47412. configurable: true
  47413. });
  47414. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  47415. get: function () {
  47416. return ActionManager._OnCenterPickTrigger;
  47417. },
  47418. enumerable: true,
  47419. configurable: true
  47420. });
  47421. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  47422. get: function () {
  47423. return ActionManager._OnPickDownTrigger;
  47424. },
  47425. enumerable: true,
  47426. configurable: true
  47427. });
  47428. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  47429. get: function () {
  47430. return ActionManager._OnDoublePickTrigger;
  47431. },
  47432. enumerable: true,
  47433. configurable: true
  47434. });
  47435. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  47436. get: function () {
  47437. return ActionManager._OnPickUpTrigger;
  47438. },
  47439. enumerable: true,
  47440. configurable: true
  47441. });
  47442. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  47443. /// This trigger will only be raised if you also declared a OnPickDown
  47444. get: function () {
  47445. return ActionManager._OnPickOutTrigger;
  47446. },
  47447. enumerable: true,
  47448. configurable: true
  47449. });
  47450. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  47451. get: function () {
  47452. return ActionManager._OnLongPressTrigger;
  47453. },
  47454. enumerable: true,
  47455. configurable: true
  47456. });
  47457. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  47458. get: function () {
  47459. return ActionManager._OnPointerOverTrigger;
  47460. },
  47461. enumerable: true,
  47462. configurable: true
  47463. });
  47464. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  47465. get: function () {
  47466. return ActionManager._OnPointerOutTrigger;
  47467. },
  47468. enumerable: true,
  47469. configurable: true
  47470. });
  47471. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  47472. get: function () {
  47473. return ActionManager._OnEveryFrameTrigger;
  47474. },
  47475. enumerable: true,
  47476. configurable: true
  47477. });
  47478. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  47479. get: function () {
  47480. return ActionManager._OnIntersectionEnterTrigger;
  47481. },
  47482. enumerable: true,
  47483. configurable: true
  47484. });
  47485. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  47486. get: function () {
  47487. return ActionManager._OnIntersectionExitTrigger;
  47488. },
  47489. enumerable: true,
  47490. configurable: true
  47491. });
  47492. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  47493. get: function () {
  47494. return ActionManager._OnKeyDownTrigger;
  47495. },
  47496. enumerable: true,
  47497. configurable: true
  47498. });
  47499. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  47500. get: function () {
  47501. return ActionManager._OnKeyUpTrigger;
  47502. },
  47503. enumerable: true,
  47504. configurable: true
  47505. });
  47506. // Methods
  47507. ActionManager.prototype.dispose = function () {
  47508. var index = this._scene._actionManagers.indexOf(this);
  47509. for (var i = 0; i < this.actions.length; i++) {
  47510. var action = this.actions[i];
  47511. ActionManager.Triggers[action.trigger]--;
  47512. if (ActionManager.Triggers[action.trigger] === 0) {
  47513. delete ActionManager.Triggers[action.trigger];
  47514. }
  47515. }
  47516. if (index > -1) {
  47517. this._scene._actionManagers.splice(index, 1);
  47518. }
  47519. };
  47520. ActionManager.prototype.getScene = function () {
  47521. return this._scene;
  47522. };
  47523. /**
  47524. * Does this action manager handles actions of any of the given triggers
  47525. * @param {number[]} triggers - the triggers to be tested
  47526. * @return {boolean} whether one (or more) of the triggers is handeled
  47527. */
  47528. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  47529. for (var index = 0; index < this.actions.length; index++) {
  47530. var action = this.actions[index];
  47531. if (triggers.indexOf(action.trigger) > -1) {
  47532. return true;
  47533. }
  47534. }
  47535. return false;
  47536. };
  47537. /**
  47538. * Does this action manager handles actions of a given trigger
  47539. * @param {number} trigger - the trigger to be tested
  47540. * @return {boolean} whether the trigger is handeled
  47541. */
  47542. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  47543. for (var index = 0; index < this.actions.length; index++) {
  47544. var action = this.actions[index];
  47545. if (action.trigger === trigger) {
  47546. return true;
  47547. }
  47548. }
  47549. return false;
  47550. };
  47551. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  47552. /**
  47553. * Does this action manager has pointer triggers
  47554. * @return {boolean} whether or not it has pointer triggers
  47555. */
  47556. get: function () {
  47557. for (var index = 0; index < this.actions.length; index++) {
  47558. var action = this.actions[index];
  47559. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  47560. return true;
  47561. }
  47562. }
  47563. return false;
  47564. },
  47565. enumerable: true,
  47566. configurable: true
  47567. });
  47568. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  47569. /**
  47570. * Does this action manager has pick triggers
  47571. * @return {boolean} whether or not it has pick triggers
  47572. */
  47573. get: function () {
  47574. for (var index = 0; index < this.actions.length; index++) {
  47575. var action = this.actions[index];
  47576. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  47577. return true;
  47578. }
  47579. }
  47580. return false;
  47581. },
  47582. enumerable: true,
  47583. configurable: true
  47584. });
  47585. Object.defineProperty(ActionManager, "HasTriggers", {
  47586. /**
  47587. * Does exist one action manager with at least one trigger
  47588. * @return {boolean} whether or not it exists one action manager with one trigger
  47589. **/
  47590. get: function () {
  47591. for (var t in ActionManager.Triggers) {
  47592. if (ActionManager.Triggers.hasOwnProperty(t)) {
  47593. return true;
  47594. }
  47595. }
  47596. return false;
  47597. },
  47598. enumerable: true,
  47599. configurable: true
  47600. });
  47601. Object.defineProperty(ActionManager, "HasPickTriggers", {
  47602. /**
  47603. * Does exist one action manager with at least one pick trigger
  47604. * @return {boolean} whether or not it exists one action manager with one pick trigger
  47605. **/
  47606. get: function () {
  47607. for (var t in ActionManager.Triggers) {
  47608. if (ActionManager.Triggers.hasOwnProperty(t)) {
  47609. var t_int = parseInt(t);
  47610. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  47611. return true;
  47612. }
  47613. }
  47614. }
  47615. return false;
  47616. },
  47617. enumerable: true,
  47618. configurable: true
  47619. });
  47620. /**
  47621. * Does exist one action manager that handles actions of a given trigger
  47622. * @param {number} trigger - the trigger to be tested
  47623. * @return {boolean} whether the trigger is handeled by at least one action manager
  47624. **/
  47625. ActionManager.HasSpecificTrigger = function (trigger) {
  47626. for (var t in ActionManager.Triggers) {
  47627. if (ActionManager.Triggers.hasOwnProperty(t)) {
  47628. var t_int = parseInt(t);
  47629. if (t_int === trigger) {
  47630. return true;
  47631. }
  47632. }
  47633. }
  47634. return false;
  47635. };
  47636. /**
  47637. * Registers an action to this action manager
  47638. * @param {BABYLON.Action} action - the action to be registered
  47639. * @return {BABYLON.Action} the action amended (prepared) after registration
  47640. */
  47641. ActionManager.prototype.registerAction = function (action) {
  47642. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  47643. if (this.getScene().actionManager !== this) {
  47644. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  47645. return null;
  47646. }
  47647. }
  47648. this.actions.push(action);
  47649. if (ActionManager.Triggers[action.trigger]) {
  47650. ActionManager.Triggers[action.trigger]++;
  47651. }
  47652. else {
  47653. ActionManager.Triggers[action.trigger] = 1;
  47654. }
  47655. action._actionManager = this;
  47656. action._prepare();
  47657. return action;
  47658. };
  47659. /**
  47660. * Unregisters an action to this action manager
  47661. * @param action The action to be unregistered
  47662. * @return whether the action has been unregistered
  47663. */
  47664. ActionManager.prototype.unregisterAction = function (action) {
  47665. var index = this.actions.indexOf(action);
  47666. if (index !== -1) {
  47667. this.actions.splice(index, 1);
  47668. ActionManager.Triggers[action.trigger] -= 1;
  47669. if (ActionManager.Triggers[action.trigger] === 0) {
  47670. delete ActionManager.Triggers[action.trigger];
  47671. }
  47672. delete action._actionManager;
  47673. return true;
  47674. }
  47675. return false;
  47676. };
  47677. /**
  47678. * Process a specific trigger
  47679. * @param {number} trigger - the trigger to process
  47680. * @param evt {BABYLON.ActionEvent} the event details to be processed
  47681. */
  47682. ActionManager.prototype.processTrigger = function (trigger, evt) {
  47683. for (var index = 0; index < this.actions.length; index++) {
  47684. var action = this.actions[index];
  47685. if (action.trigger === trigger) {
  47686. if (evt) {
  47687. if (trigger === ActionManager.OnKeyUpTrigger
  47688. || trigger === ActionManager.OnKeyDownTrigger) {
  47689. var parameter = action.getTriggerParameter();
  47690. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  47691. if (!parameter.toLowerCase) {
  47692. continue;
  47693. }
  47694. var lowerCase = parameter.toLowerCase();
  47695. if (lowerCase !== evt.sourceEvent.key) {
  47696. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  47697. var actualkey = String.fromCharCode(unicode).toLowerCase();
  47698. if (actualkey !== lowerCase) {
  47699. continue;
  47700. }
  47701. }
  47702. }
  47703. }
  47704. }
  47705. action._executeCurrent(evt);
  47706. }
  47707. }
  47708. };
  47709. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  47710. var properties = propertyPath.split(".");
  47711. for (var index = 0; index < properties.length - 1; index++) {
  47712. target = target[properties[index]];
  47713. }
  47714. return target;
  47715. };
  47716. ActionManager.prototype._getProperty = function (propertyPath) {
  47717. var properties = propertyPath.split(".");
  47718. return properties[properties.length - 1];
  47719. };
  47720. ActionManager.prototype.serialize = function (name) {
  47721. var root = {
  47722. children: new Array(),
  47723. name: name,
  47724. type: 3,
  47725. properties: new Array() // Empty for root but required
  47726. };
  47727. for (var i = 0; i < this.actions.length; i++) {
  47728. var triggerObject = {
  47729. type: 0,
  47730. children: new Array(),
  47731. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  47732. properties: new Array()
  47733. };
  47734. var triggerOptions = this.actions[i].triggerOptions;
  47735. if (triggerOptions && typeof triggerOptions !== "number") {
  47736. if (triggerOptions.parameter instanceof BABYLON.Node) {
  47737. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  47738. }
  47739. else {
  47740. var parameter = {};
  47741. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  47742. if (triggerOptions.parameter.mesh) {
  47743. parameter._meshId = triggerOptions.parameter.mesh.id;
  47744. }
  47745. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  47746. }
  47747. }
  47748. // Serialize child action, recursively
  47749. this.actions[i].serialize(triggerObject);
  47750. // Add serialized trigger
  47751. root.children.push(triggerObject);
  47752. }
  47753. return root;
  47754. };
  47755. ActionManager.Parse = function (parsedActions, object, scene) {
  47756. var actionManager = new ActionManager(scene);
  47757. if (object === null)
  47758. scene.actionManager = actionManager;
  47759. else
  47760. object.actionManager = actionManager;
  47761. // instanciate a new object
  47762. var instanciate = function (name, params) {
  47763. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  47764. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  47765. newInstance.constructor.apply(newInstance, params);
  47766. return newInstance;
  47767. };
  47768. var parseParameter = function (name, value, target, propertyPath) {
  47769. if (propertyPath === null) {
  47770. // String, boolean or float
  47771. var floatValue = parseFloat(value);
  47772. if (value === "true" || value === "false")
  47773. return value === "true";
  47774. else
  47775. return isNaN(floatValue) ? value : floatValue;
  47776. }
  47777. var effectiveTarget = propertyPath.split(".");
  47778. var values = value.split(",");
  47779. // Get effective Target
  47780. for (var i = 0; i < effectiveTarget.length; i++) {
  47781. target = target[effectiveTarget[i]];
  47782. }
  47783. // Return appropriate value with its type
  47784. if (typeof (target) === "boolean")
  47785. return values[0] === "true";
  47786. if (typeof (target) === "string")
  47787. return values[0];
  47788. // Parameters with multiple values such as Vector3 etc.
  47789. var split = new Array();
  47790. for (var i = 0; i < values.length; i++)
  47791. split.push(parseFloat(values[i]));
  47792. if (target instanceof BABYLON.Vector3)
  47793. return BABYLON.Vector3.FromArray(split);
  47794. if (target instanceof BABYLON.Vector4)
  47795. return BABYLON.Vector4.FromArray(split);
  47796. if (target instanceof BABYLON.Color3)
  47797. return BABYLON.Color3.FromArray(split);
  47798. if (target instanceof BABYLON.Color4)
  47799. return BABYLON.Color4.FromArray(split);
  47800. return parseFloat(values[0]);
  47801. };
  47802. // traverse graph per trigger
  47803. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  47804. if (combineArray === void 0) { combineArray = null; }
  47805. if (parsedAction.detached)
  47806. return;
  47807. var parameters = new Array();
  47808. var target = null;
  47809. var propertyPath = null;
  47810. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  47811. // Parameters
  47812. if (parsedAction.type === 2)
  47813. parameters.push(actionManager);
  47814. else
  47815. parameters.push(trigger);
  47816. if (combine) {
  47817. var actions = new Array();
  47818. for (var j = 0; j < parsedAction.combine.length; j++) {
  47819. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  47820. }
  47821. parameters.push(actions);
  47822. }
  47823. else {
  47824. for (var i = 0; i < parsedAction.properties.length; i++) {
  47825. var value = parsedAction.properties[i].value;
  47826. var name = parsedAction.properties[i].name;
  47827. var targetType = parsedAction.properties[i].targetType;
  47828. if (name === "target")
  47829. if (targetType !== null && targetType === "SceneProperties")
  47830. value = target = scene;
  47831. else
  47832. value = target = scene.getNodeByName(value);
  47833. else if (name === "parent")
  47834. value = scene.getNodeByName(value);
  47835. else if (name === "sound")
  47836. value = scene.getSoundByName(value);
  47837. else if (name !== "propertyPath") {
  47838. if (parsedAction.type === 2 && name === "operator")
  47839. value = BABYLON.ValueCondition[value];
  47840. else
  47841. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  47842. }
  47843. else {
  47844. propertyPath = value;
  47845. }
  47846. parameters.push(value);
  47847. }
  47848. }
  47849. if (combineArray === null) {
  47850. parameters.push(condition);
  47851. }
  47852. else {
  47853. parameters.push(null);
  47854. }
  47855. // If interpolate value action
  47856. if (parsedAction.name === "InterpolateValueAction") {
  47857. var param = parameters[parameters.length - 2];
  47858. parameters[parameters.length - 1] = param;
  47859. parameters[parameters.length - 2] = condition;
  47860. }
  47861. // Action or condition(s) and not CombineAction
  47862. var newAction = instanciate(parsedAction.name, parameters);
  47863. if (newAction instanceof BABYLON.Condition && condition !== null) {
  47864. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  47865. if (action)
  47866. action.then(nothing);
  47867. else
  47868. actionManager.registerAction(nothing);
  47869. action = nothing;
  47870. }
  47871. if (combineArray === null) {
  47872. if (newAction instanceof BABYLON.Condition) {
  47873. condition = newAction;
  47874. newAction = action;
  47875. }
  47876. else {
  47877. condition = null;
  47878. if (action)
  47879. action.then(newAction);
  47880. else
  47881. actionManager.registerAction(newAction);
  47882. }
  47883. }
  47884. else {
  47885. combineArray.push(newAction);
  47886. }
  47887. for (var i = 0; i < parsedAction.children.length; i++)
  47888. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  47889. };
  47890. // triggers
  47891. for (var i = 0; i < parsedActions.children.length; i++) {
  47892. var triggerParams;
  47893. var trigger = parsedActions.children[i];
  47894. if (trigger.properties.length > 0) {
  47895. var param = trigger.properties[0].value;
  47896. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  47897. if (value._meshId) {
  47898. value.mesh = scene.getMeshByID(value._meshId);
  47899. }
  47900. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  47901. }
  47902. else
  47903. triggerParams = ActionManager[trigger.name];
  47904. for (var j = 0; j < trigger.children.length; j++) {
  47905. if (!trigger.detached)
  47906. traverse(trigger.children[j], triggerParams, null, null);
  47907. }
  47908. }
  47909. };
  47910. ActionManager.GetTriggerName = function (trigger) {
  47911. switch (trigger) {
  47912. case 0: return "NothingTrigger";
  47913. case 1: return "OnPickTrigger";
  47914. case 2: return "OnLeftPickTrigger";
  47915. case 3: return "OnRightPickTrigger";
  47916. case 4: return "OnCenterPickTrigger";
  47917. case 5: return "OnPickDownTrigger";
  47918. case 6: return "OnPickUpTrigger";
  47919. case 7: return "OnLongPressTrigger";
  47920. case 8: return "OnPointerOverTrigger";
  47921. case 9: return "OnPointerOutTrigger";
  47922. case 10: return "OnEveryFrameTrigger";
  47923. case 11: return "OnIntersectionEnterTrigger";
  47924. case 12: return "OnIntersectionExitTrigger";
  47925. case 13: return "OnKeyDownTrigger";
  47926. case 14: return "OnKeyUpTrigger";
  47927. case 15: return "OnPickOutTrigger";
  47928. default: return "";
  47929. }
  47930. };
  47931. // Statics
  47932. ActionManager._NothingTrigger = 0;
  47933. ActionManager._OnPickTrigger = 1;
  47934. ActionManager._OnLeftPickTrigger = 2;
  47935. ActionManager._OnRightPickTrigger = 3;
  47936. ActionManager._OnCenterPickTrigger = 4;
  47937. ActionManager._OnPickDownTrigger = 5;
  47938. ActionManager._OnDoublePickTrigger = 6;
  47939. ActionManager._OnPickUpTrigger = 7;
  47940. ActionManager._OnLongPressTrigger = 8;
  47941. ActionManager._OnPointerOverTrigger = 9;
  47942. ActionManager._OnPointerOutTrigger = 10;
  47943. ActionManager._OnEveryFrameTrigger = 11;
  47944. ActionManager._OnIntersectionEnterTrigger = 12;
  47945. ActionManager._OnIntersectionExitTrigger = 13;
  47946. ActionManager._OnKeyDownTrigger = 14;
  47947. ActionManager._OnKeyUpTrigger = 15;
  47948. ActionManager._OnPickOutTrigger = 16;
  47949. ActionManager.Triggers = {};
  47950. return ActionManager;
  47951. }());
  47952. BABYLON.ActionManager = ActionManager;
  47953. })(BABYLON || (BABYLON = {}));
  47954. //# sourceMappingURL=babylon.actionManager.js.map
  47955. var BABYLON;
  47956. (function (BABYLON) {
  47957. var InterpolateValueAction = /** @class */ (function (_super) {
  47958. __extends(InterpolateValueAction, _super);
  47959. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  47960. if (duration === void 0) { duration = 1000; }
  47961. var _this = _super.call(this, triggerOptions, condition) || this;
  47962. _this.propertyPath = propertyPath;
  47963. _this.value = value;
  47964. _this.duration = duration;
  47965. _this.stopOtherAnimations = stopOtherAnimations;
  47966. _this.onInterpolationDone = onInterpolationDone;
  47967. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  47968. _this._target = _this._effectiveTarget = target;
  47969. return _this;
  47970. }
  47971. InterpolateValueAction.prototype._prepare = function () {
  47972. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  47973. this._property = this._getProperty(this.propertyPath);
  47974. };
  47975. InterpolateValueAction.prototype.execute = function () {
  47976. var _this = this;
  47977. var scene = this._actionManager.getScene();
  47978. var keys = [
  47979. {
  47980. frame: 0,
  47981. value: this._effectiveTarget[this._property]
  47982. }, {
  47983. frame: 100,
  47984. value: this.value
  47985. }
  47986. ];
  47987. var dataType;
  47988. if (typeof this.value === "number") {
  47989. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  47990. }
  47991. else if (this.value instanceof BABYLON.Color3) {
  47992. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  47993. }
  47994. else if (this.value instanceof BABYLON.Vector3) {
  47995. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  47996. }
  47997. else if (this.value instanceof BABYLON.Matrix) {
  47998. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  47999. }
  48000. else if (this.value instanceof BABYLON.Quaternion) {
  48001. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  48002. }
  48003. else {
  48004. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  48005. return;
  48006. }
  48007. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  48008. animation.setKeys(keys);
  48009. if (this.stopOtherAnimations) {
  48010. scene.stopAnimation(this._effectiveTarget);
  48011. }
  48012. var wrapper = function () {
  48013. _this.onInterpolationDoneObservable.notifyObservers(_this);
  48014. if (_this.onInterpolationDone) {
  48015. _this.onInterpolationDone();
  48016. }
  48017. };
  48018. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  48019. };
  48020. InterpolateValueAction.prototype.serialize = function (parent) {
  48021. return _super.prototype._serialize.call(this, {
  48022. name: "InterpolateValueAction",
  48023. properties: [
  48024. BABYLON.Action._GetTargetProperty(this._target),
  48025. { name: "propertyPath", value: this.propertyPath },
  48026. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  48027. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  48028. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  48029. ]
  48030. }, parent);
  48031. };
  48032. return InterpolateValueAction;
  48033. }(BABYLON.Action));
  48034. BABYLON.InterpolateValueAction = InterpolateValueAction;
  48035. })(BABYLON || (BABYLON = {}));
  48036. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  48037. var BABYLON;
  48038. (function (BABYLON) {
  48039. var SwitchBooleanAction = /** @class */ (function (_super) {
  48040. __extends(SwitchBooleanAction, _super);
  48041. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  48042. var _this = _super.call(this, triggerOptions, condition) || this;
  48043. _this.propertyPath = propertyPath;
  48044. _this._target = _this._effectiveTarget = target;
  48045. return _this;
  48046. }
  48047. SwitchBooleanAction.prototype._prepare = function () {
  48048. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  48049. this._property = this._getProperty(this.propertyPath);
  48050. };
  48051. SwitchBooleanAction.prototype.execute = function () {
  48052. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  48053. };
  48054. SwitchBooleanAction.prototype.serialize = function (parent) {
  48055. return _super.prototype._serialize.call(this, {
  48056. name: "SwitchBooleanAction",
  48057. properties: [
  48058. BABYLON.Action._GetTargetProperty(this._target),
  48059. { name: "propertyPath", value: this.propertyPath }
  48060. ]
  48061. }, parent);
  48062. };
  48063. return SwitchBooleanAction;
  48064. }(BABYLON.Action));
  48065. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  48066. var SetStateAction = /** @class */ (function (_super) {
  48067. __extends(SetStateAction, _super);
  48068. function SetStateAction(triggerOptions, target, value, condition) {
  48069. var _this = _super.call(this, triggerOptions, condition) || this;
  48070. _this.value = value;
  48071. _this._target = target;
  48072. return _this;
  48073. }
  48074. SetStateAction.prototype.execute = function () {
  48075. this._target.state = this.value;
  48076. };
  48077. SetStateAction.prototype.serialize = function (parent) {
  48078. return _super.prototype._serialize.call(this, {
  48079. name: "SetStateAction",
  48080. properties: [
  48081. BABYLON.Action._GetTargetProperty(this._target),
  48082. { name: "value", value: this.value }
  48083. ]
  48084. }, parent);
  48085. };
  48086. return SetStateAction;
  48087. }(BABYLON.Action));
  48088. BABYLON.SetStateAction = SetStateAction;
  48089. var SetValueAction = /** @class */ (function (_super) {
  48090. __extends(SetValueAction, _super);
  48091. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  48092. var _this = _super.call(this, triggerOptions, condition) || this;
  48093. _this.propertyPath = propertyPath;
  48094. _this.value = value;
  48095. _this._target = _this._effectiveTarget = target;
  48096. return _this;
  48097. }
  48098. SetValueAction.prototype._prepare = function () {
  48099. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  48100. this._property = this._getProperty(this.propertyPath);
  48101. };
  48102. SetValueAction.prototype.execute = function () {
  48103. this._effectiveTarget[this._property] = this.value;
  48104. if (this._target.markAsDirty) {
  48105. this._target.markAsDirty(this._property);
  48106. }
  48107. };
  48108. SetValueAction.prototype.serialize = function (parent) {
  48109. return _super.prototype._serialize.call(this, {
  48110. name: "SetValueAction",
  48111. properties: [
  48112. BABYLON.Action._GetTargetProperty(this._target),
  48113. { name: "propertyPath", value: this.propertyPath },
  48114. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  48115. ]
  48116. }, parent);
  48117. };
  48118. return SetValueAction;
  48119. }(BABYLON.Action));
  48120. BABYLON.SetValueAction = SetValueAction;
  48121. var IncrementValueAction = /** @class */ (function (_super) {
  48122. __extends(IncrementValueAction, _super);
  48123. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  48124. var _this = _super.call(this, triggerOptions, condition) || this;
  48125. _this.propertyPath = propertyPath;
  48126. _this.value = value;
  48127. _this._target = _this._effectiveTarget = target;
  48128. return _this;
  48129. }
  48130. IncrementValueAction.prototype._prepare = function () {
  48131. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  48132. this._property = this._getProperty(this.propertyPath);
  48133. if (typeof this._effectiveTarget[this._property] !== "number") {
  48134. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  48135. }
  48136. };
  48137. IncrementValueAction.prototype.execute = function () {
  48138. this._effectiveTarget[this._property] += this.value;
  48139. if (this._target.markAsDirty) {
  48140. this._target.markAsDirty(this._property);
  48141. }
  48142. };
  48143. IncrementValueAction.prototype.serialize = function (parent) {
  48144. return _super.prototype._serialize.call(this, {
  48145. name: "IncrementValueAction",
  48146. properties: [
  48147. BABYLON.Action._GetTargetProperty(this._target),
  48148. { name: "propertyPath", value: this.propertyPath },
  48149. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  48150. ]
  48151. }, parent);
  48152. };
  48153. return IncrementValueAction;
  48154. }(BABYLON.Action));
  48155. BABYLON.IncrementValueAction = IncrementValueAction;
  48156. var PlayAnimationAction = /** @class */ (function (_super) {
  48157. __extends(PlayAnimationAction, _super);
  48158. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  48159. var _this = _super.call(this, triggerOptions, condition) || this;
  48160. _this.from = from;
  48161. _this.to = to;
  48162. _this.loop = loop;
  48163. _this._target = target;
  48164. return _this;
  48165. }
  48166. PlayAnimationAction.prototype._prepare = function () {
  48167. };
  48168. PlayAnimationAction.prototype.execute = function () {
  48169. var scene = this._actionManager.getScene();
  48170. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  48171. };
  48172. PlayAnimationAction.prototype.serialize = function (parent) {
  48173. return _super.prototype._serialize.call(this, {
  48174. name: "PlayAnimationAction",
  48175. properties: [
  48176. BABYLON.Action._GetTargetProperty(this._target),
  48177. { name: "from", value: String(this.from) },
  48178. { name: "to", value: String(this.to) },
  48179. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  48180. ]
  48181. }, parent);
  48182. };
  48183. return PlayAnimationAction;
  48184. }(BABYLON.Action));
  48185. BABYLON.PlayAnimationAction = PlayAnimationAction;
  48186. var StopAnimationAction = /** @class */ (function (_super) {
  48187. __extends(StopAnimationAction, _super);
  48188. function StopAnimationAction(triggerOptions, target, condition) {
  48189. var _this = _super.call(this, triggerOptions, condition) || this;
  48190. _this._target = target;
  48191. return _this;
  48192. }
  48193. StopAnimationAction.prototype._prepare = function () {
  48194. };
  48195. StopAnimationAction.prototype.execute = function () {
  48196. var scene = this._actionManager.getScene();
  48197. scene.stopAnimation(this._target);
  48198. };
  48199. StopAnimationAction.prototype.serialize = function (parent) {
  48200. return _super.prototype._serialize.call(this, {
  48201. name: "StopAnimationAction",
  48202. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  48203. }, parent);
  48204. };
  48205. return StopAnimationAction;
  48206. }(BABYLON.Action));
  48207. BABYLON.StopAnimationAction = StopAnimationAction;
  48208. var DoNothingAction = /** @class */ (function (_super) {
  48209. __extends(DoNothingAction, _super);
  48210. function DoNothingAction(triggerOptions, condition) {
  48211. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  48212. return _super.call(this, triggerOptions, condition) || this;
  48213. }
  48214. DoNothingAction.prototype.execute = function () {
  48215. };
  48216. DoNothingAction.prototype.serialize = function (parent) {
  48217. return _super.prototype._serialize.call(this, {
  48218. name: "DoNothingAction",
  48219. properties: []
  48220. }, parent);
  48221. };
  48222. return DoNothingAction;
  48223. }(BABYLON.Action));
  48224. BABYLON.DoNothingAction = DoNothingAction;
  48225. var CombineAction = /** @class */ (function (_super) {
  48226. __extends(CombineAction, _super);
  48227. function CombineAction(triggerOptions, children, condition) {
  48228. var _this = _super.call(this, triggerOptions, condition) || this;
  48229. _this.children = children;
  48230. return _this;
  48231. }
  48232. CombineAction.prototype._prepare = function () {
  48233. for (var index = 0; index < this.children.length; index++) {
  48234. this.children[index]._actionManager = this._actionManager;
  48235. this.children[index]._prepare();
  48236. }
  48237. };
  48238. CombineAction.prototype.execute = function (evt) {
  48239. for (var index = 0; index < this.children.length; index++) {
  48240. this.children[index].execute(evt);
  48241. }
  48242. };
  48243. CombineAction.prototype.serialize = function (parent) {
  48244. var serializationObject = _super.prototype._serialize.call(this, {
  48245. name: "CombineAction",
  48246. properties: [],
  48247. combine: []
  48248. }, parent);
  48249. for (var i = 0; i < this.children.length; i++) {
  48250. serializationObject.combine.push(this.children[i].serialize(null));
  48251. }
  48252. return serializationObject;
  48253. };
  48254. return CombineAction;
  48255. }(BABYLON.Action));
  48256. BABYLON.CombineAction = CombineAction;
  48257. var ExecuteCodeAction = /** @class */ (function (_super) {
  48258. __extends(ExecuteCodeAction, _super);
  48259. function ExecuteCodeAction(triggerOptions, func, condition) {
  48260. var _this = _super.call(this, triggerOptions, condition) || this;
  48261. _this.func = func;
  48262. return _this;
  48263. }
  48264. ExecuteCodeAction.prototype.execute = function (evt) {
  48265. this.func(evt);
  48266. };
  48267. return ExecuteCodeAction;
  48268. }(BABYLON.Action));
  48269. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  48270. var SetParentAction = /** @class */ (function (_super) {
  48271. __extends(SetParentAction, _super);
  48272. function SetParentAction(triggerOptions, target, parent, condition) {
  48273. var _this = _super.call(this, triggerOptions, condition) || this;
  48274. _this._target = target;
  48275. _this._parent = parent;
  48276. return _this;
  48277. }
  48278. SetParentAction.prototype._prepare = function () {
  48279. };
  48280. SetParentAction.prototype.execute = function () {
  48281. if (this._target.parent === this._parent) {
  48282. return;
  48283. }
  48284. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  48285. invertParentWorldMatrix.invert();
  48286. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  48287. this._target.parent = this._parent;
  48288. };
  48289. SetParentAction.prototype.serialize = function (parent) {
  48290. return _super.prototype._serialize.call(this, {
  48291. name: "SetParentAction",
  48292. properties: [
  48293. BABYLON.Action._GetTargetProperty(this._target),
  48294. BABYLON.Action._GetTargetProperty(this._parent),
  48295. ]
  48296. }, parent);
  48297. };
  48298. return SetParentAction;
  48299. }(BABYLON.Action));
  48300. BABYLON.SetParentAction = SetParentAction;
  48301. var PlaySoundAction = /** @class */ (function (_super) {
  48302. __extends(PlaySoundAction, _super);
  48303. function PlaySoundAction(triggerOptions, sound, condition) {
  48304. var _this = _super.call(this, triggerOptions, condition) || this;
  48305. _this._sound = sound;
  48306. return _this;
  48307. }
  48308. PlaySoundAction.prototype._prepare = function () {
  48309. };
  48310. PlaySoundAction.prototype.execute = function () {
  48311. if (this._sound !== undefined)
  48312. this._sound.play();
  48313. };
  48314. PlaySoundAction.prototype.serialize = function (parent) {
  48315. return _super.prototype._serialize.call(this, {
  48316. name: "PlaySoundAction",
  48317. properties: [{ name: "sound", value: this._sound.name }]
  48318. }, parent);
  48319. };
  48320. return PlaySoundAction;
  48321. }(BABYLON.Action));
  48322. BABYLON.PlaySoundAction = PlaySoundAction;
  48323. var StopSoundAction = /** @class */ (function (_super) {
  48324. __extends(StopSoundAction, _super);
  48325. function StopSoundAction(triggerOptions, sound, condition) {
  48326. var _this = _super.call(this, triggerOptions, condition) || this;
  48327. _this._sound = sound;
  48328. return _this;
  48329. }
  48330. StopSoundAction.prototype._prepare = function () {
  48331. };
  48332. StopSoundAction.prototype.execute = function () {
  48333. if (this._sound !== undefined)
  48334. this._sound.stop();
  48335. };
  48336. StopSoundAction.prototype.serialize = function (parent) {
  48337. return _super.prototype._serialize.call(this, {
  48338. name: "StopSoundAction",
  48339. properties: [{ name: "sound", value: this._sound.name }]
  48340. }, parent);
  48341. };
  48342. return StopSoundAction;
  48343. }(BABYLON.Action));
  48344. BABYLON.StopSoundAction = StopSoundAction;
  48345. })(BABYLON || (BABYLON = {}));
  48346. //# sourceMappingURL=babylon.directActions.js.map
  48347. var BABYLON;
  48348. (function (BABYLON) {
  48349. var SpriteManager = /** @class */ (function () {
  48350. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  48351. if (epsilon === void 0) { epsilon = 0.01; }
  48352. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  48353. this.name = name;
  48354. this.sprites = new Array();
  48355. this.renderingGroupId = 0;
  48356. this.layerMask = 0x0FFFFFFF;
  48357. this.fogEnabled = true;
  48358. this.isPickable = false;
  48359. /**
  48360. * An event triggered when the manager is disposed.
  48361. * @type {BABYLON.Observable}
  48362. */
  48363. this.onDisposeObservable = new BABYLON.Observable();
  48364. this._vertexBuffers = {};
  48365. this._capacity = capacity;
  48366. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  48367. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  48368. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  48369. if (cellSize.width && cellSize.height) {
  48370. this.cellWidth = cellSize.width;
  48371. this.cellHeight = cellSize.height;
  48372. }
  48373. else if (cellSize !== undefined) {
  48374. this.cellWidth = cellSize;
  48375. this.cellHeight = cellSize;
  48376. }
  48377. else {
  48378. return;
  48379. }
  48380. this._epsilon = epsilon;
  48381. this._scene = scene;
  48382. this._scene.spriteManagers.push(this);
  48383. var indices = [];
  48384. var index = 0;
  48385. for (var count = 0; count < capacity; count++) {
  48386. indices.push(index);
  48387. indices.push(index + 1);
  48388. indices.push(index + 2);
  48389. indices.push(index);
  48390. indices.push(index + 2);
  48391. indices.push(index + 3);
  48392. index += 4;
  48393. }
  48394. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  48395. // VBO
  48396. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  48397. this._vertexData = new Float32Array(capacity * 16 * 4);
  48398. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  48399. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  48400. var options = this._buffer.createVertexBuffer("options", 4, 4);
  48401. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  48402. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  48403. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  48404. this._vertexBuffers["options"] = options;
  48405. this._vertexBuffers["cellInfo"] = cellInfo;
  48406. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  48407. // Effects
  48408. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  48409. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  48410. }
  48411. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  48412. set: function (callback) {
  48413. if (this._onDisposeObserver) {
  48414. this.onDisposeObservable.remove(this._onDisposeObserver);
  48415. }
  48416. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  48417. },
  48418. enumerable: true,
  48419. configurable: true
  48420. });
  48421. Object.defineProperty(SpriteManager.prototype, "texture", {
  48422. get: function () {
  48423. return this._spriteTexture;
  48424. },
  48425. set: function (value) {
  48426. this._spriteTexture = value;
  48427. },
  48428. enumerable: true,
  48429. configurable: true
  48430. });
  48431. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  48432. var arrayOffset = index * 16;
  48433. if (offsetX === 0)
  48434. offsetX = this._epsilon;
  48435. else if (offsetX === 1)
  48436. offsetX = 1 - this._epsilon;
  48437. if (offsetY === 0)
  48438. offsetY = this._epsilon;
  48439. else if (offsetY === 1)
  48440. offsetY = 1 - this._epsilon;
  48441. this._vertexData[arrayOffset] = sprite.position.x;
  48442. this._vertexData[arrayOffset + 1] = sprite.position.y;
  48443. this._vertexData[arrayOffset + 2] = sprite.position.z;
  48444. this._vertexData[arrayOffset + 3] = sprite.angle;
  48445. this._vertexData[arrayOffset + 4] = sprite.width;
  48446. this._vertexData[arrayOffset + 5] = sprite.height;
  48447. this._vertexData[arrayOffset + 6] = offsetX;
  48448. this._vertexData[arrayOffset + 7] = offsetY;
  48449. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  48450. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  48451. var offset = (sprite.cellIndex / rowSize) >> 0;
  48452. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  48453. this._vertexData[arrayOffset + 11] = offset;
  48454. // Color
  48455. this._vertexData[arrayOffset + 12] = sprite.color.r;
  48456. this._vertexData[arrayOffset + 13] = sprite.color.g;
  48457. this._vertexData[arrayOffset + 14] = sprite.color.b;
  48458. this._vertexData[arrayOffset + 15] = sprite.color.a;
  48459. };
  48460. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  48461. var count = Math.min(this._capacity, this.sprites.length);
  48462. var min = BABYLON.Vector3.Zero();
  48463. var max = BABYLON.Vector3.Zero();
  48464. var distance = Number.MAX_VALUE;
  48465. var currentSprite = null;
  48466. var cameraSpacePosition = BABYLON.Vector3.Zero();
  48467. var cameraView = camera.getViewMatrix();
  48468. for (var index = 0; index < count; index++) {
  48469. var sprite = this.sprites[index];
  48470. if (!sprite) {
  48471. continue;
  48472. }
  48473. if (predicate) {
  48474. if (!predicate(sprite)) {
  48475. continue;
  48476. }
  48477. }
  48478. else if (!sprite.isPickable) {
  48479. continue;
  48480. }
  48481. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  48482. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  48483. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  48484. if (ray.intersectsBoxMinMax(min, max)) {
  48485. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  48486. if (distance > currentDistance) {
  48487. distance = currentDistance;
  48488. currentSprite = sprite;
  48489. if (fastCheck) {
  48490. break;
  48491. }
  48492. }
  48493. }
  48494. }
  48495. if (currentSprite) {
  48496. var result = new BABYLON.PickingInfo();
  48497. result.hit = true;
  48498. result.pickedSprite = currentSprite;
  48499. result.distance = distance;
  48500. return result;
  48501. }
  48502. return null;
  48503. };
  48504. SpriteManager.prototype.render = function () {
  48505. // Check
  48506. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  48507. return;
  48508. var engine = this._scene.getEngine();
  48509. var baseSize = this._spriteTexture.getBaseSize();
  48510. // Sprites
  48511. var deltaTime = engine.getDeltaTime();
  48512. var max = Math.min(this._capacity, this.sprites.length);
  48513. var rowSize = baseSize.width / this.cellWidth;
  48514. var offset = 0;
  48515. for (var index = 0; index < max; index++) {
  48516. var sprite = this.sprites[index];
  48517. if (!sprite) {
  48518. continue;
  48519. }
  48520. sprite._animate(deltaTime);
  48521. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  48522. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  48523. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  48524. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  48525. }
  48526. this._buffer.update(this._vertexData);
  48527. // Render
  48528. var effect = this._effectBase;
  48529. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  48530. effect = this._effectFog;
  48531. }
  48532. engine.enableEffect(effect);
  48533. var viewMatrix = this._scene.getViewMatrix();
  48534. effect.setTexture("diffuseSampler", this._spriteTexture);
  48535. effect.setMatrix("view", viewMatrix);
  48536. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  48537. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  48538. // Fog
  48539. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  48540. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  48541. effect.setColor3("vFogColor", this._scene.fogColor);
  48542. }
  48543. // VBOs
  48544. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  48545. // Draw order
  48546. engine.setDepthFunctionToLessOrEqual();
  48547. effect.setBool("alphaTest", true);
  48548. engine.setColorWrite(false);
  48549. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  48550. engine.setColorWrite(true);
  48551. effect.setBool("alphaTest", false);
  48552. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  48553. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  48554. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  48555. };
  48556. SpriteManager.prototype.dispose = function () {
  48557. if (this._buffer) {
  48558. this._buffer.dispose();
  48559. this._buffer = null;
  48560. }
  48561. if (this._indexBuffer) {
  48562. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  48563. this._indexBuffer = null;
  48564. }
  48565. if (this._spriteTexture) {
  48566. this._spriteTexture.dispose();
  48567. this._spriteTexture = null;
  48568. }
  48569. // Remove from scene
  48570. var index = this._scene.spriteManagers.indexOf(this);
  48571. this._scene.spriteManagers.splice(index, 1);
  48572. // Callback
  48573. this.onDisposeObservable.notifyObservers(this);
  48574. this.onDisposeObservable.clear();
  48575. };
  48576. return SpriteManager;
  48577. }());
  48578. BABYLON.SpriteManager = SpriteManager;
  48579. })(BABYLON || (BABYLON = {}));
  48580. //# sourceMappingURL=babylon.spriteManager.js.map
  48581. var BABYLON;
  48582. (function (BABYLON) {
  48583. var Sprite = /** @class */ (function () {
  48584. function Sprite(name, manager) {
  48585. this.name = name;
  48586. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  48587. this.width = 1.0;
  48588. this.height = 1.0;
  48589. this.angle = 0;
  48590. this.cellIndex = 0;
  48591. this.invertU = 0;
  48592. this.invertV = 0;
  48593. this.animations = new Array();
  48594. this.isPickable = false;
  48595. this._animationStarted = false;
  48596. this._loopAnimation = false;
  48597. this._fromIndex = 0;
  48598. this._toIndex = 0;
  48599. this._delay = 0;
  48600. this._direction = 1;
  48601. this._time = 0;
  48602. this._manager = manager;
  48603. this._manager.sprites.push(this);
  48604. this.position = BABYLON.Vector3.Zero();
  48605. }
  48606. Object.defineProperty(Sprite.prototype, "size", {
  48607. get: function () {
  48608. return this.width;
  48609. },
  48610. set: function (value) {
  48611. this.width = value;
  48612. this.height = value;
  48613. },
  48614. enumerable: true,
  48615. configurable: true
  48616. });
  48617. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  48618. this._fromIndex = from;
  48619. this._toIndex = to;
  48620. this._loopAnimation = loop;
  48621. this._delay = delay;
  48622. this._animationStarted = true;
  48623. this._direction = from < to ? 1 : -1;
  48624. this.cellIndex = from;
  48625. this._time = 0;
  48626. this._onAnimationEnd = onAnimationEnd;
  48627. };
  48628. Sprite.prototype.stopAnimation = function () {
  48629. this._animationStarted = false;
  48630. };
  48631. Sprite.prototype._animate = function (deltaTime) {
  48632. if (!this._animationStarted)
  48633. return;
  48634. this._time += deltaTime;
  48635. if (this._time > this._delay) {
  48636. this._time = this._time % this._delay;
  48637. this.cellIndex += this._direction;
  48638. if (this.cellIndex > this._toIndex) {
  48639. if (this._loopAnimation) {
  48640. this.cellIndex = this._fromIndex;
  48641. }
  48642. else {
  48643. this.cellIndex = this._toIndex;
  48644. this._animationStarted = false;
  48645. if (this._onAnimationEnd) {
  48646. this._onAnimationEnd();
  48647. }
  48648. if (this.disposeWhenFinishedAnimating) {
  48649. this.dispose();
  48650. }
  48651. }
  48652. }
  48653. }
  48654. };
  48655. Sprite.prototype.dispose = function () {
  48656. for (var i = 0; i < this._manager.sprites.length; i++) {
  48657. if (this._manager.sprites[i] == this) {
  48658. this._manager.sprites.splice(i, 1);
  48659. }
  48660. }
  48661. };
  48662. return Sprite;
  48663. }());
  48664. BABYLON.Sprite = Sprite;
  48665. })(BABYLON || (BABYLON = {}));
  48666. //# sourceMappingURL=babylon.sprite.js.map
  48667. var BABYLON;
  48668. (function (BABYLON) {
  48669. var IntersectionInfo = /** @class */ (function () {
  48670. function IntersectionInfo(bu, bv, distance) {
  48671. this.bu = bu;
  48672. this.bv = bv;
  48673. this.distance = distance;
  48674. this.faceId = 0;
  48675. this.subMeshId = 0;
  48676. }
  48677. return IntersectionInfo;
  48678. }());
  48679. BABYLON.IntersectionInfo = IntersectionInfo;
  48680. var PickingInfo = /** @class */ (function () {
  48681. function PickingInfo() {
  48682. this.hit = false;
  48683. this.distance = 0;
  48684. this.pickedPoint = null;
  48685. this.pickedMesh = null;
  48686. this.bu = 0;
  48687. this.bv = 0;
  48688. this.faceId = -1;
  48689. this.subMeshId = 0;
  48690. this.pickedSprite = null;
  48691. }
  48692. // Methods
  48693. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  48694. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  48695. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  48696. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  48697. return null;
  48698. }
  48699. var indices = this.pickedMesh.getIndices();
  48700. if (!indices) {
  48701. return null;
  48702. }
  48703. var result;
  48704. if (useVerticesNormals) {
  48705. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  48706. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  48707. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  48708. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  48709. normal0 = normal0.scale(this.bu);
  48710. normal1 = normal1.scale(this.bv);
  48711. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  48712. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  48713. }
  48714. else {
  48715. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  48716. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  48717. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  48718. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  48719. var p1p2 = vertex1.subtract(vertex2);
  48720. var p3p2 = vertex3.subtract(vertex2);
  48721. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  48722. }
  48723. if (useWorldCoordinates) {
  48724. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  48725. }
  48726. return BABYLON.Vector3.Normalize(result);
  48727. };
  48728. PickingInfo.prototype.getTextureCoordinates = function () {
  48729. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  48730. return null;
  48731. }
  48732. var indices = this.pickedMesh.getIndices();
  48733. if (!indices) {
  48734. return null;
  48735. }
  48736. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  48737. if (!uvs) {
  48738. return null;
  48739. }
  48740. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  48741. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  48742. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  48743. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  48744. uv1 = uv1.scale(this.bu);
  48745. uv2 = uv2.scale(this.bv);
  48746. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  48747. };
  48748. return PickingInfo;
  48749. }());
  48750. BABYLON.PickingInfo = PickingInfo;
  48751. })(BABYLON || (BABYLON = {}));
  48752. //# sourceMappingURL=babylon.pickingInfo.js.map
  48753. var BABYLON;
  48754. (function (BABYLON) {
  48755. var Ray = /** @class */ (function () {
  48756. function Ray(origin, direction, length) {
  48757. if (length === void 0) { length = Number.MAX_VALUE; }
  48758. this.origin = origin;
  48759. this.direction = direction;
  48760. this.length = length;
  48761. }
  48762. // Methods
  48763. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  48764. var d = 0.0;
  48765. var maxValue = Number.MAX_VALUE;
  48766. var inv;
  48767. var min;
  48768. var max;
  48769. var temp;
  48770. if (Math.abs(this.direction.x) < 0.0000001) {
  48771. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  48772. return false;
  48773. }
  48774. }
  48775. else {
  48776. inv = 1.0 / this.direction.x;
  48777. min = (minimum.x - this.origin.x) * inv;
  48778. max = (maximum.x - this.origin.x) * inv;
  48779. if (max === -Infinity) {
  48780. max = Infinity;
  48781. }
  48782. if (min > max) {
  48783. temp = min;
  48784. min = max;
  48785. max = temp;
  48786. }
  48787. d = Math.max(min, d);
  48788. maxValue = Math.min(max, maxValue);
  48789. if (d > maxValue) {
  48790. return false;
  48791. }
  48792. }
  48793. if (Math.abs(this.direction.y) < 0.0000001) {
  48794. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  48795. return false;
  48796. }
  48797. }
  48798. else {
  48799. inv = 1.0 / this.direction.y;
  48800. min = (minimum.y - this.origin.y) * inv;
  48801. max = (maximum.y - this.origin.y) * inv;
  48802. if (max === -Infinity) {
  48803. max = Infinity;
  48804. }
  48805. if (min > max) {
  48806. temp = min;
  48807. min = max;
  48808. max = temp;
  48809. }
  48810. d = Math.max(min, d);
  48811. maxValue = Math.min(max, maxValue);
  48812. if (d > maxValue) {
  48813. return false;
  48814. }
  48815. }
  48816. if (Math.abs(this.direction.z) < 0.0000001) {
  48817. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  48818. return false;
  48819. }
  48820. }
  48821. else {
  48822. inv = 1.0 / this.direction.z;
  48823. min = (minimum.z - this.origin.z) * inv;
  48824. max = (maximum.z - this.origin.z) * inv;
  48825. if (max === -Infinity) {
  48826. max = Infinity;
  48827. }
  48828. if (min > max) {
  48829. temp = min;
  48830. min = max;
  48831. max = temp;
  48832. }
  48833. d = Math.max(min, d);
  48834. maxValue = Math.min(max, maxValue);
  48835. if (d > maxValue) {
  48836. return false;
  48837. }
  48838. }
  48839. return true;
  48840. };
  48841. Ray.prototype.intersectsBox = function (box) {
  48842. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  48843. };
  48844. Ray.prototype.intersectsSphere = function (sphere) {
  48845. var x = sphere.center.x - this.origin.x;
  48846. var y = sphere.center.y - this.origin.y;
  48847. var z = sphere.center.z - this.origin.z;
  48848. var pyth = (x * x) + (y * y) + (z * z);
  48849. var rr = sphere.radius * sphere.radius;
  48850. if (pyth <= rr) {
  48851. return true;
  48852. }
  48853. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  48854. if (dot < 0.0) {
  48855. return false;
  48856. }
  48857. var temp = pyth - (dot * dot);
  48858. return temp <= rr;
  48859. };
  48860. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  48861. if (!this._edge1) {
  48862. this._edge1 = BABYLON.Vector3.Zero();
  48863. this._edge2 = BABYLON.Vector3.Zero();
  48864. this._pvec = BABYLON.Vector3.Zero();
  48865. this._tvec = BABYLON.Vector3.Zero();
  48866. this._qvec = BABYLON.Vector3.Zero();
  48867. }
  48868. vertex1.subtractToRef(vertex0, this._edge1);
  48869. vertex2.subtractToRef(vertex0, this._edge2);
  48870. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  48871. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  48872. if (det === 0) {
  48873. return null;
  48874. }
  48875. var invdet = 1 / det;
  48876. this.origin.subtractToRef(vertex0, this._tvec);
  48877. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  48878. if (bu < 0 || bu > 1.0) {
  48879. return null;
  48880. }
  48881. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  48882. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  48883. if (bv < 0 || bu + bv > 1.0) {
  48884. return null;
  48885. }
  48886. //check if the distance is longer than the predefined length.
  48887. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  48888. if (distance > this.length) {
  48889. return null;
  48890. }
  48891. return new BABYLON.IntersectionInfo(bu, bv, distance);
  48892. };
  48893. Ray.prototype.intersectsPlane = function (plane) {
  48894. var distance;
  48895. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  48896. if (Math.abs(result1) < 9.99999997475243E-07) {
  48897. return null;
  48898. }
  48899. else {
  48900. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  48901. distance = (-plane.d - result2) / result1;
  48902. if (distance < 0.0) {
  48903. if (distance < -9.99999997475243E-07) {
  48904. return null;
  48905. }
  48906. else {
  48907. return 0;
  48908. }
  48909. }
  48910. return distance;
  48911. }
  48912. };
  48913. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  48914. var tm = BABYLON.Tmp.Matrix[0];
  48915. mesh.getWorldMatrix().invertToRef(tm);
  48916. if (this._tmpRay) {
  48917. Ray.TransformToRef(this, tm, this._tmpRay);
  48918. }
  48919. else {
  48920. this._tmpRay = Ray.Transform(this, tm);
  48921. }
  48922. return mesh.intersects(this._tmpRay, fastCheck);
  48923. };
  48924. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  48925. if (results) {
  48926. results.length = 0;
  48927. }
  48928. else {
  48929. results = [];
  48930. }
  48931. for (var i = 0; i < meshes.length; i++) {
  48932. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  48933. if (pickInfo.hit) {
  48934. results.push(pickInfo);
  48935. }
  48936. }
  48937. results.sort(this._comparePickingInfo);
  48938. return results;
  48939. };
  48940. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  48941. if (pickingInfoA.distance < pickingInfoB.distance) {
  48942. return -1;
  48943. }
  48944. else if (pickingInfoA.distance > pickingInfoB.distance) {
  48945. return 1;
  48946. }
  48947. else {
  48948. return 0;
  48949. }
  48950. };
  48951. /**
  48952. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  48953. * @param sega the first point of the segment to test the intersection against
  48954. * @param segb the second point of the segment to test the intersection against
  48955. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  48956. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  48957. */
  48958. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  48959. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  48960. var u = segb.subtract(sega);
  48961. var v = rsegb.subtract(this.origin);
  48962. var w = sega.subtract(this.origin);
  48963. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  48964. var b = BABYLON.Vector3.Dot(u, v);
  48965. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  48966. var d = BABYLON.Vector3.Dot(u, w);
  48967. var e = BABYLON.Vector3.Dot(v, w);
  48968. var D = a * c - b * b; // always >= 0
  48969. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  48970. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  48971. // compute the line parameters of the two closest points
  48972. if (D < Ray.smallnum) {
  48973. sN = 0.0; // force using point P0 on segment S1
  48974. sD = 1.0; // to prevent possible division by 0.0 later
  48975. tN = e;
  48976. tD = c;
  48977. }
  48978. else {
  48979. sN = (b * e - c * d);
  48980. tN = (a * e - b * d);
  48981. if (sN < 0.0) {
  48982. sN = 0.0;
  48983. tN = e;
  48984. tD = c;
  48985. }
  48986. else if (sN > sD) {
  48987. sN = sD;
  48988. tN = e + b;
  48989. tD = c;
  48990. }
  48991. }
  48992. if (tN < 0.0) {
  48993. tN = 0.0;
  48994. // recompute sc for this edge
  48995. if (-d < 0.0) {
  48996. sN = 0.0;
  48997. }
  48998. else if (-d > a)
  48999. sN = sD;
  49000. else {
  49001. sN = -d;
  49002. sD = a;
  49003. }
  49004. }
  49005. else if (tN > tD) {
  49006. tN = tD;
  49007. // recompute sc for this edge
  49008. if ((-d + b) < 0.0) {
  49009. sN = 0;
  49010. }
  49011. else if ((-d + b) > a) {
  49012. sN = sD;
  49013. }
  49014. else {
  49015. sN = (-d + b);
  49016. sD = a;
  49017. }
  49018. }
  49019. // finally do the division to get sc and tc
  49020. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  49021. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  49022. // get the difference of the two closest points
  49023. var qtc = v.multiplyByFloats(tc, tc, tc);
  49024. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  49025. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  49026. if (isIntersected) {
  49027. return qtc.length();
  49028. }
  49029. return -1;
  49030. };
  49031. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  49032. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  49033. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  49034. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  49035. this.direction.normalize();
  49036. return this;
  49037. };
  49038. // Statics
  49039. Ray.Zero = function () {
  49040. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  49041. };
  49042. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  49043. var result = Ray.Zero();
  49044. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  49045. };
  49046. /**
  49047. * 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
  49048. * transformed to the given world matrix.
  49049. * @param origin The origin point
  49050. * @param end The end point
  49051. * @param world a matrix to transform the ray to. Default is the identity matrix.
  49052. */
  49053. Ray.CreateNewFromTo = function (origin, end, world) {
  49054. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  49055. var direction = end.subtract(origin);
  49056. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  49057. direction.normalize();
  49058. return Ray.Transform(new Ray(origin, direction, length), world);
  49059. };
  49060. Ray.Transform = function (ray, matrix) {
  49061. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  49062. Ray.TransformToRef(ray, matrix, result);
  49063. return result;
  49064. };
  49065. Ray.TransformToRef = function (ray, matrix, result) {
  49066. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  49067. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  49068. result.length = ray.length;
  49069. var dir = result.direction;
  49070. var len = dir.length();
  49071. if (!(len === 0 || len === 1)) {
  49072. var num = 1.0 / len;
  49073. dir.x *= num;
  49074. dir.y *= num;
  49075. dir.z *= num;
  49076. result.length *= len;
  49077. }
  49078. };
  49079. Ray.smallnum = 0.00000001;
  49080. Ray.rayl = 10e8;
  49081. return Ray;
  49082. }());
  49083. BABYLON.Ray = Ray;
  49084. })(BABYLON || (BABYLON = {}));
  49085. //# sourceMappingURL=babylon.ray.js.map
  49086. var BABYLON;
  49087. (function (BABYLON) {
  49088. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  49089. if (boxMin.x > sphereCenter.x + sphereRadius)
  49090. return false;
  49091. if (sphereCenter.x - sphereRadius > boxMax.x)
  49092. return false;
  49093. if (boxMin.y > sphereCenter.y + sphereRadius)
  49094. return false;
  49095. if (sphereCenter.y - sphereRadius > boxMax.y)
  49096. return false;
  49097. if (boxMin.z > sphereCenter.z + sphereRadius)
  49098. return false;
  49099. if (sphereCenter.z - sphereRadius > boxMax.z)
  49100. return false;
  49101. return true;
  49102. };
  49103. var getLowestRoot = (function () {
  49104. var result = { root: 0, found: false };
  49105. return function (a, b, c, maxR) {
  49106. result.root = 0;
  49107. result.found = false;
  49108. var determinant = b * b - 4.0 * a * c;
  49109. if (determinant < 0)
  49110. return result;
  49111. var sqrtD = Math.sqrt(determinant);
  49112. var r1 = (-b - sqrtD) / (2.0 * a);
  49113. var r2 = (-b + sqrtD) / (2.0 * a);
  49114. if (r1 > r2) {
  49115. var temp = r2;
  49116. r2 = r1;
  49117. r1 = temp;
  49118. }
  49119. if (r1 > 0 && r1 < maxR) {
  49120. result.root = r1;
  49121. result.found = true;
  49122. return result;
  49123. }
  49124. if (r2 > 0 && r2 < maxR) {
  49125. result.root = r2;
  49126. result.found = true;
  49127. return result;
  49128. }
  49129. return result;
  49130. };
  49131. })();
  49132. var Collider = /** @class */ (function () {
  49133. function Collider() {
  49134. this._collisionPoint = BABYLON.Vector3.Zero();
  49135. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  49136. this._tempVector = BABYLON.Vector3.Zero();
  49137. this._tempVector2 = BABYLON.Vector3.Zero();
  49138. this._tempVector3 = BABYLON.Vector3.Zero();
  49139. this._tempVector4 = BABYLON.Vector3.Zero();
  49140. this._edge = BABYLON.Vector3.Zero();
  49141. this._baseToVertex = BABYLON.Vector3.Zero();
  49142. this._destinationPoint = BABYLON.Vector3.Zero();
  49143. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  49144. this._displacementVector = BABYLON.Vector3.Zero();
  49145. this._radius = BABYLON.Vector3.One();
  49146. this._retry = 0;
  49147. this._basePointWorld = BABYLON.Vector3.Zero();
  49148. this._velocityWorld = BABYLON.Vector3.Zero();
  49149. this._normalizedVelocity = BABYLON.Vector3.Zero();
  49150. this._collisionMask = -1;
  49151. }
  49152. Object.defineProperty(Collider.prototype, "collisionMask", {
  49153. get: function () {
  49154. return this._collisionMask;
  49155. },
  49156. set: function (mask) {
  49157. this._collisionMask = !isNaN(mask) ? mask : -1;
  49158. },
  49159. enumerable: true,
  49160. configurable: true
  49161. });
  49162. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  49163. /**
  49164. * Gets the plane normal used to compute the sliding response (in local space)
  49165. */
  49166. get: function () {
  49167. return this._slidePlaneNormal;
  49168. },
  49169. enumerable: true,
  49170. configurable: true
  49171. });
  49172. // Methods
  49173. Collider.prototype._initialize = function (source, dir, e) {
  49174. this._velocity = dir;
  49175. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  49176. this._basePoint = source;
  49177. source.multiplyToRef(this._radius, this._basePointWorld);
  49178. dir.multiplyToRef(this._radius, this._velocityWorld);
  49179. this._velocityWorldLength = this._velocityWorld.length();
  49180. this._epsilon = e;
  49181. this.collisionFound = false;
  49182. };
  49183. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  49184. pa.subtractToRef(point, this._tempVector);
  49185. pb.subtractToRef(point, this._tempVector2);
  49186. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  49187. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  49188. if (d < 0)
  49189. return false;
  49190. pc.subtractToRef(point, this._tempVector3);
  49191. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  49192. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  49193. if (d < 0)
  49194. return false;
  49195. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  49196. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  49197. return d >= 0;
  49198. };
  49199. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  49200. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  49201. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  49202. if (distance > this._velocityWorldLength + max + sphereRadius) {
  49203. return false;
  49204. }
  49205. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  49206. return false;
  49207. return true;
  49208. };
  49209. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  49210. var t0;
  49211. var embeddedInPlane = false;
  49212. //defensive programming, actually not needed.
  49213. if (!trianglePlaneArray) {
  49214. trianglePlaneArray = [];
  49215. }
  49216. if (!trianglePlaneArray[faceIndex]) {
  49217. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  49218. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  49219. }
  49220. var trianglePlane = trianglePlaneArray[faceIndex];
  49221. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  49222. return;
  49223. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  49224. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  49225. if (normalDotVelocity == 0) {
  49226. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  49227. return;
  49228. embeddedInPlane = true;
  49229. t0 = 0;
  49230. }
  49231. else {
  49232. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  49233. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  49234. if (t0 > t1) {
  49235. var temp = t1;
  49236. t1 = t0;
  49237. t0 = temp;
  49238. }
  49239. if (t0 > 1.0 || t1 < 0.0)
  49240. return;
  49241. if (t0 < 0)
  49242. t0 = 0;
  49243. if (t0 > 1.0)
  49244. t0 = 1.0;
  49245. }
  49246. this._collisionPoint.copyFromFloats(0, 0, 0);
  49247. var found = false;
  49248. var t = 1.0;
  49249. if (!embeddedInPlane) {
  49250. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  49251. this._velocity.scaleToRef(t0, this._tempVector);
  49252. this._planeIntersectionPoint.addInPlace(this._tempVector);
  49253. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  49254. found = true;
  49255. t = t0;
  49256. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  49257. }
  49258. }
  49259. if (!found) {
  49260. var velocitySquaredLength = this._velocity.lengthSquared();
  49261. var a = velocitySquaredLength;
  49262. this._basePoint.subtractToRef(p1, this._tempVector);
  49263. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  49264. var c = this._tempVector.lengthSquared() - 1.0;
  49265. var lowestRoot = getLowestRoot(a, b, c, t);
  49266. if (lowestRoot.found) {
  49267. t = lowestRoot.root;
  49268. found = true;
  49269. this._collisionPoint.copyFrom(p1);
  49270. }
  49271. this._basePoint.subtractToRef(p2, this._tempVector);
  49272. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  49273. c = this._tempVector.lengthSquared() - 1.0;
  49274. lowestRoot = getLowestRoot(a, b, c, t);
  49275. if (lowestRoot.found) {
  49276. t = lowestRoot.root;
  49277. found = true;
  49278. this._collisionPoint.copyFrom(p2);
  49279. }
  49280. this._basePoint.subtractToRef(p3, this._tempVector);
  49281. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  49282. c = this._tempVector.lengthSquared() - 1.0;
  49283. lowestRoot = getLowestRoot(a, b, c, t);
  49284. if (lowestRoot.found) {
  49285. t = lowestRoot.root;
  49286. found = true;
  49287. this._collisionPoint.copyFrom(p3);
  49288. }
  49289. p2.subtractToRef(p1, this._edge);
  49290. p1.subtractToRef(this._basePoint, this._baseToVertex);
  49291. var edgeSquaredLength = this._edge.lengthSquared();
  49292. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  49293. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  49294. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  49295. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  49296. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  49297. lowestRoot = getLowestRoot(a, b, c, t);
  49298. if (lowestRoot.found) {
  49299. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  49300. if (f >= 0.0 && f <= 1.0) {
  49301. t = lowestRoot.root;
  49302. found = true;
  49303. this._edge.scaleInPlace(f);
  49304. p1.addToRef(this._edge, this._collisionPoint);
  49305. }
  49306. }
  49307. p3.subtractToRef(p2, this._edge);
  49308. p2.subtractToRef(this._basePoint, this._baseToVertex);
  49309. edgeSquaredLength = this._edge.lengthSquared();
  49310. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  49311. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  49312. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  49313. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  49314. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  49315. lowestRoot = getLowestRoot(a, b, c, t);
  49316. if (lowestRoot.found) {
  49317. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  49318. if (f >= 0.0 && f <= 1.0) {
  49319. t = lowestRoot.root;
  49320. found = true;
  49321. this._edge.scaleInPlace(f);
  49322. p2.addToRef(this._edge, this._collisionPoint);
  49323. }
  49324. }
  49325. p1.subtractToRef(p3, this._edge);
  49326. p3.subtractToRef(this._basePoint, this._baseToVertex);
  49327. edgeSquaredLength = this._edge.lengthSquared();
  49328. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  49329. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  49330. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  49331. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  49332. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  49333. lowestRoot = getLowestRoot(a, b, c, t);
  49334. if (lowestRoot.found) {
  49335. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  49336. if (f >= 0.0 && f <= 1.0) {
  49337. t = lowestRoot.root;
  49338. found = true;
  49339. this._edge.scaleInPlace(f);
  49340. p3.addToRef(this._edge, this._collisionPoint);
  49341. }
  49342. }
  49343. }
  49344. if (found) {
  49345. var distToCollision = t * this._velocity.length();
  49346. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  49347. if (!this.intersectionPoint) {
  49348. this.intersectionPoint = this._collisionPoint.clone();
  49349. }
  49350. else {
  49351. this.intersectionPoint.copyFrom(this._collisionPoint);
  49352. }
  49353. this._nearestDistance = distToCollision;
  49354. this.collisionFound = true;
  49355. }
  49356. }
  49357. };
  49358. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  49359. for (var i = indexStart; i < indexEnd; i += 3) {
  49360. var p1 = pts[indices[i] - decal];
  49361. var p2 = pts[indices[i + 1] - decal];
  49362. var p3 = pts[indices[i + 2] - decal];
  49363. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  49364. }
  49365. };
  49366. Collider.prototype._getResponse = function (pos, vel) {
  49367. pos.addToRef(vel, this._destinationPoint);
  49368. vel.scaleInPlace((this._nearestDistance / vel.length()));
  49369. this._basePoint.addToRef(vel, pos);
  49370. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  49371. this._slidePlaneNormal.normalize();
  49372. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  49373. pos.addInPlace(this._displacementVector);
  49374. this.intersectionPoint.addInPlace(this._displacementVector);
  49375. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  49376. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  49377. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  49378. };
  49379. return Collider;
  49380. }());
  49381. BABYLON.Collider = Collider;
  49382. })(BABYLON || (BABYLON = {}));
  49383. //# sourceMappingURL=babylon.collider.js.map
  49384. var BABYLON;
  49385. (function (BABYLON) {
  49386. //WebWorker code will be inserted to this variable.
  49387. BABYLON.CollisionWorker = "";
  49388. var WorkerTaskType;
  49389. (function (WorkerTaskType) {
  49390. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  49391. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  49392. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  49393. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  49394. var WorkerReplyType;
  49395. (function (WorkerReplyType) {
  49396. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  49397. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  49398. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  49399. var CollisionCoordinatorWorker = /** @class */ (function () {
  49400. function CollisionCoordinatorWorker() {
  49401. var _this = this;
  49402. this._scaledPosition = BABYLON.Vector3.Zero();
  49403. this._scaledVelocity = BABYLON.Vector3.Zero();
  49404. this.onMeshUpdated = function (transformNode) {
  49405. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  49406. };
  49407. this.onGeometryUpdated = function (geometry) {
  49408. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  49409. };
  49410. this._afterRender = function () {
  49411. if (!_this._init)
  49412. return;
  49413. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  49414. return;
  49415. }
  49416. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  49417. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  49418. if (_this._runningUpdated > 4) {
  49419. return;
  49420. }
  49421. ++_this._runningUpdated;
  49422. var payload = {
  49423. updatedMeshes: _this._addUpdateMeshesList,
  49424. updatedGeometries: _this._addUpdateGeometriesList,
  49425. removedGeometries: _this._toRemoveGeometryArray,
  49426. removedMeshes: _this._toRemoveMeshesArray
  49427. };
  49428. var message = {
  49429. payload: payload,
  49430. taskType: WorkerTaskType.UPDATE
  49431. };
  49432. var serializable = [];
  49433. for (var id in payload.updatedGeometries) {
  49434. if (payload.updatedGeometries.hasOwnProperty(id)) {
  49435. //prepare transferables
  49436. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  49437. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  49438. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  49439. }
  49440. }
  49441. _this._worker.postMessage(message, serializable);
  49442. _this._addUpdateMeshesList = {};
  49443. _this._addUpdateGeometriesList = {};
  49444. _this._toRemoveGeometryArray = [];
  49445. _this._toRemoveMeshesArray = [];
  49446. };
  49447. this._onMessageFromWorker = function (e) {
  49448. var returnData = e.data;
  49449. if (returnData.error != WorkerReplyType.SUCCESS) {
  49450. //TODO what errors can be returned from the worker?
  49451. BABYLON.Tools.Warn("error returned from worker!");
  49452. return;
  49453. }
  49454. switch (returnData.taskType) {
  49455. case WorkerTaskType.INIT:
  49456. _this._init = true;
  49457. //Update the worked with ALL of the scene's current state
  49458. _this._scene.meshes.forEach(function (mesh) {
  49459. _this.onMeshAdded(mesh);
  49460. });
  49461. _this._scene.getGeometries().forEach(function (geometry) {
  49462. _this.onGeometryAdded(geometry);
  49463. });
  49464. break;
  49465. case WorkerTaskType.UPDATE:
  49466. _this._runningUpdated--;
  49467. break;
  49468. case WorkerTaskType.COLLIDE:
  49469. var returnPayload = returnData.payload;
  49470. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  49471. return;
  49472. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  49473. if (callback) {
  49474. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  49475. if (mesh) {
  49476. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  49477. }
  49478. }
  49479. //cleanup
  49480. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  49481. break;
  49482. }
  49483. };
  49484. this._collisionsCallbackArray = [];
  49485. this._init = false;
  49486. this._runningUpdated = 0;
  49487. this._addUpdateMeshesList = {};
  49488. this._addUpdateGeometriesList = {};
  49489. this._toRemoveGeometryArray = [];
  49490. this._toRemoveMeshesArray = [];
  49491. }
  49492. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  49493. if (!this._init)
  49494. return;
  49495. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  49496. return;
  49497. position.divideToRef(collider._radius, this._scaledPosition);
  49498. displacement.divideToRef(collider._radius, this._scaledVelocity);
  49499. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  49500. var payload = {
  49501. collider: {
  49502. position: this._scaledPosition.asArray(),
  49503. velocity: this._scaledVelocity.asArray(),
  49504. radius: collider._radius.asArray()
  49505. },
  49506. collisionId: collisionIndex,
  49507. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  49508. maximumRetry: maximumRetry
  49509. };
  49510. var message = {
  49511. payload: payload,
  49512. taskType: WorkerTaskType.COLLIDE
  49513. };
  49514. this._worker.postMessage(message);
  49515. };
  49516. CollisionCoordinatorWorker.prototype.init = function (scene) {
  49517. this._scene = scene;
  49518. this._scene.registerAfterRender(this._afterRender);
  49519. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  49520. this._worker = new Worker(workerUrl);
  49521. this._worker.onmessage = this._onMessageFromWorker;
  49522. var message = {
  49523. payload: {},
  49524. taskType: WorkerTaskType.INIT
  49525. };
  49526. this._worker.postMessage(message);
  49527. };
  49528. CollisionCoordinatorWorker.prototype.destroy = function () {
  49529. this._scene.unregisterAfterRender(this._afterRender);
  49530. this._worker.terminate();
  49531. };
  49532. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  49533. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  49534. this.onMeshUpdated(mesh);
  49535. };
  49536. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  49537. this._toRemoveMeshesArray.push(mesh.uniqueId);
  49538. };
  49539. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  49540. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  49541. geometry.onGeometryUpdated = this.onGeometryUpdated;
  49542. this.onGeometryUpdated(geometry);
  49543. };
  49544. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  49545. this._toRemoveGeometryArray.push(geometry.id);
  49546. };
  49547. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  49548. var submeshes = [];
  49549. if (mesh.subMeshes) {
  49550. submeshes = mesh.subMeshes.map(function (sm, idx) {
  49551. var boundingInfo = sm.getBoundingInfo();
  49552. return {
  49553. position: idx,
  49554. verticesStart: sm.verticesStart,
  49555. verticesCount: sm.verticesCount,
  49556. indexStart: sm.indexStart,
  49557. indexCount: sm.indexCount,
  49558. hasMaterial: !!sm.getMaterial(),
  49559. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  49560. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  49561. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  49562. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  49563. };
  49564. });
  49565. }
  49566. var geometryId = null;
  49567. if (mesh instanceof BABYLON.Mesh) {
  49568. var geometry = mesh.geometry;
  49569. geometryId = geometry ? geometry.id : null;
  49570. }
  49571. else if (mesh instanceof BABYLON.InstancedMesh) {
  49572. var geometry = mesh.sourceMesh.geometry;
  49573. geometryId = geometry ? geometry.id : null;
  49574. }
  49575. var boundingInfo = mesh.getBoundingInfo();
  49576. return {
  49577. uniqueId: mesh.uniqueId,
  49578. id: mesh.id,
  49579. name: mesh.name,
  49580. geometryId: geometryId,
  49581. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  49582. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  49583. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  49584. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  49585. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  49586. subMeshes: submeshes,
  49587. checkCollisions: mesh.checkCollisions
  49588. };
  49589. };
  49590. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  49591. return {
  49592. id: geometry.id,
  49593. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  49594. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  49595. indices: new Uint32Array(geometry.getIndices() || []),
  49596. };
  49597. };
  49598. return CollisionCoordinatorWorker;
  49599. }());
  49600. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  49601. var CollisionCoordinatorLegacy = /** @class */ (function () {
  49602. function CollisionCoordinatorLegacy() {
  49603. this._scaledPosition = BABYLON.Vector3.Zero();
  49604. this._scaledVelocity = BABYLON.Vector3.Zero();
  49605. this._finalPosition = BABYLON.Vector3.Zero();
  49606. }
  49607. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  49608. position.divideToRef(collider._radius, this._scaledPosition);
  49609. displacement.divideToRef(collider._radius, this._scaledVelocity);
  49610. collider.collidedMesh = null;
  49611. collider._retry = 0;
  49612. collider._initialVelocity = this._scaledVelocity;
  49613. collider._initialPosition = this._scaledPosition;
  49614. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  49615. this._finalPosition.multiplyInPlace(collider._radius);
  49616. //run the callback
  49617. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  49618. };
  49619. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  49620. this._scene = scene;
  49621. };
  49622. CollisionCoordinatorLegacy.prototype.destroy = function () {
  49623. //Legacy need no destruction method.
  49624. };
  49625. //No update in legacy mode
  49626. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  49627. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  49628. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  49629. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  49630. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  49631. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  49632. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  49633. if (excludedMesh === void 0) { excludedMesh = null; }
  49634. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  49635. if (collider._retry >= maximumRetry) {
  49636. finalPosition.copyFrom(position);
  49637. return;
  49638. }
  49639. // Check if this is a mesh else camera or -1
  49640. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  49641. collider._initialize(position, velocity, closeDistance);
  49642. // Check all meshes
  49643. for (var index = 0; index < this._scene.meshes.length; index++) {
  49644. var mesh = this._scene.meshes[index];
  49645. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  49646. mesh._checkCollision(collider);
  49647. }
  49648. }
  49649. if (!collider.collisionFound) {
  49650. position.addToRef(velocity, finalPosition);
  49651. return;
  49652. }
  49653. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  49654. collider._getResponse(position, velocity);
  49655. }
  49656. if (velocity.length() <= closeDistance) {
  49657. finalPosition.copyFrom(position);
  49658. return;
  49659. }
  49660. collider._retry++;
  49661. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  49662. };
  49663. return CollisionCoordinatorLegacy;
  49664. }());
  49665. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  49666. })(BABYLON || (BABYLON = {}));
  49667. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  49668. var BABYLON;
  49669. (function (BABYLON) {
  49670. /**
  49671. * A particle represents one of the element emitted by a particle system.
  49672. * This is mainly define by its coordinates, direction, velocity and age.
  49673. */
  49674. var Particle = /** @class */ (function () {
  49675. /**
  49676. * Creates a new instance of @see Particle
  49677. * @param particleSystem the particle system the particle belongs to
  49678. */
  49679. function Particle(particleSystem) {
  49680. this.particleSystem = particleSystem;
  49681. /**
  49682. * The world position of the particle in the scene.
  49683. */
  49684. this.position = BABYLON.Vector3.Zero();
  49685. /**
  49686. * The world direction of the particle in the scene.
  49687. */
  49688. this.direction = BABYLON.Vector3.Zero();
  49689. /**
  49690. * The color of the particle.
  49691. */
  49692. this.color = new BABYLON.Color4(0, 0, 0, 0);
  49693. /**
  49694. * The color change of the particle per step.
  49695. */
  49696. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  49697. /**
  49698. * Defines how long will the life of the particle be.
  49699. */
  49700. this.lifeTime = 1.0;
  49701. /**
  49702. * The current age of the particle.
  49703. */
  49704. this.age = 0;
  49705. /**
  49706. * The current size of the particle.
  49707. */
  49708. this.size = 0;
  49709. /**
  49710. * The current angle of the particle.
  49711. */
  49712. this.angle = 0;
  49713. /**
  49714. * Defines how fast is the angle changing.
  49715. */
  49716. this.angularSpeed = 0;
  49717. /**
  49718. * Defines the cell index used by the particle to be rendered from a sprite.
  49719. */
  49720. this.cellIndex = 0;
  49721. this._currentFrameCounter = 0;
  49722. if (!this.particleSystem.isAnimationSheetEnabled) {
  49723. return;
  49724. }
  49725. this.cellIndex = this.particleSystem.startSpriteCellID;
  49726. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  49727. this.updateCellIndex = this.updateCellIndexWithSpeedCalculated;
  49728. }
  49729. else {
  49730. this.updateCellIndex = this.updateCellIndexWithCustomSpeed;
  49731. }
  49732. }
  49733. Particle.prototype.updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  49734. // (ageOffset / scaledUpdateSpeed) / available cells
  49735. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  49736. this._currentFrameCounter += scaledUpdateSpeed;
  49737. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  49738. this._currentFrameCounter = 0;
  49739. this.cellIndex++;
  49740. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  49741. this.cellIndex = this.particleSystem.endSpriteCellID;
  49742. }
  49743. }
  49744. };
  49745. Particle.prototype.updateCellIndexWithCustomSpeed = function () {
  49746. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  49747. this.cellIndex++;
  49748. this._currentFrameCounter = 0;
  49749. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  49750. if (this.particleSystem.spriteCellLoop) {
  49751. this.cellIndex = this.particleSystem.startSpriteCellID;
  49752. }
  49753. else {
  49754. this.cellIndex = this.particleSystem.endSpriteCellID;
  49755. }
  49756. }
  49757. }
  49758. else {
  49759. this._currentFrameCounter++;
  49760. }
  49761. };
  49762. /**
  49763. * Copy the properties of particle to another one.
  49764. * @param other the particle to copy the information to.
  49765. */
  49766. Particle.prototype.copyTo = function (other) {
  49767. other.position.copyFrom(this.position);
  49768. other.direction.copyFrom(this.direction);
  49769. other.color.copyFrom(this.color);
  49770. other.colorStep.copyFrom(this.colorStep);
  49771. other.lifeTime = this.lifeTime;
  49772. other.age = this.age;
  49773. other.size = this.size;
  49774. other.angle = this.angle;
  49775. other.angularSpeed = this.angularSpeed;
  49776. other.particleSystem = this.particleSystem;
  49777. other.cellIndex = this.cellIndex;
  49778. };
  49779. return Particle;
  49780. }());
  49781. BABYLON.Particle = Particle;
  49782. })(BABYLON || (BABYLON = {}));
  49783. //# sourceMappingURL=babylon.particle.js.map
  49784. var BABYLON;
  49785. (function (BABYLON) {
  49786. /**
  49787. * This represents a particle system in Babylon.
  49788. * 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.
  49789. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  49790. * @example https://doc.babylonjs.com/babylon101/particles
  49791. */
  49792. var ParticleSystem = /** @class */ (function () {
  49793. /**
  49794. * Instantiates a particle system.
  49795. * 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.
  49796. * @param name The name of the particle system
  49797. * @param capacity The max number of particles alive at the same time
  49798. * @param scene The scene the particle system belongs to
  49799. * @param customEffect a custom effect used to change the way particles are rendered by default
  49800. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  49801. * @param epsilon Offset used to render the particles
  49802. */
  49803. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  49804. if (customEffect === void 0) { customEffect = null; }
  49805. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  49806. if (epsilon === void 0) { epsilon = 0.01; }
  49807. var _this = this;
  49808. /**
  49809. * List of animations used by the particle system.
  49810. */
  49811. this.animations = [];
  49812. /**
  49813. * The rendering group used by the Particle system to chose when to render.
  49814. */
  49815. this.renderingGroupId = 0;
  49816. /**
  49817. * The emitter represents the Mesh or position we are attaching the particle system to.
  49818. */
  49819. this.emitter = null;
  49820. /**
  49821. * The density of particles, the rate of particle flow
  49822. */
  49823. this.emitRate = 10;
  49824. /**
  49825. * If you want to launch only a few particles at once, that can be done, as well.
  49826. */
  49827. this.manualEmitCount = -1;
  49828. /**
  49829. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  49830. */
  49831. this.updateSpeed = 0.01;
  49832. /**
  49833. * The amount of time the particle system is running (depends of the overall speed above).
  49834. */
  49835. this.targetStopDuration = 0;
  49836. /**
  49837. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  49838. */
  49839. this.disposeOnStop = false;
  49840. /**
  49841. * Minimum power of emitting particles.
  49842. */
  49843. this.minEmitPower = 1;
  49844. /**
  49845. * Maximum power of emitting particles.
  49846. */
  49847. this.maxEmitPower = 1;
  49848. /**
  49849. * Minimum life time of emitting particles.
  49850. */
  49851. this.minLifeTime = 1;
  49852. /**
  49853. * Maximum life time of emitting particles.
  49854. */
  49855. this.maxLifeTime = 1;
  49856. /**
  49857. * Minimum Size of emitting particles.
  49858. */
  49859. this.minSize = 1;
  49860. /**
  49861. * Maximum Size of emitting particles.
  49862. */
  49863. this.maxSize = 1;
  49864. /**
  49865. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  49866. */
  49867. this.minAngularSpeed = 0;
  49868. /**
  49869. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  49870. */
  49871. this.maxAngularSpeed = 0;
  49872. /**
  49873. * The layer mask we are rendering the particles through.
  49874. */
  49875. this.layerMask = 0x0FFFFFFF;
  49876. /**
  49877. * This can help using your own shader to render the particle system.
  49878. * The according effect will be created
  49879. */
  49880. this.customShader = null;
  49881. /**
  49882. * By default particle system starts as soon as they are created. This prevents the
  49883. * automatic start to happen and let you decide when to start emitting particles.
  49884. */
  49885. this.preventAutoStart = false;
  49886. /**
  49887. * Callback triggered when the particle animation is ending.
  49888. */
  49889. this.onAnimationEnd = null;
  49890. /**
  49891. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  49892. */
  49893. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  49894. /**
  49895. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  49896. * to override the particles.
  49897. */
  49898. this.forceDepthWrite = false;
  49899. /**
  49900. * You can use gravity if you want to give an orientation to your particles.
  49901. */
  49902. this.gravity = BABYLON.Vector3.Zero();
  49903. /**
  49904. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  49905. */
  49906. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  49907. /**
  49908. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  49909. */
  49910. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  49911. /**
  49912. * 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.
  49913. */
  49914. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  49915. /**
  49916. * 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.
  49917. */
  49918. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  49919. /**
  49920. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  49921. */
  49922. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  49923. /**
  49924. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  49925. */
  49926. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  49927. /**
  49928. * Color the particle will have at the end of its lifetime.
  49929. */
  49930. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  49931. /**
  49932. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel.
  49933. */
  49934. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  49935. /**
  49936. * If using a spritesheet (isAnimationSheetEnabled), defines if the sprite animation should loop between startSpriteCellID and endSpriteCellID or not.
  49937. */
  49938. this.spriteCellLoop = true;
  49939. /**
  49940. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the speed of the sprite loop.
  49941. */
  49942. this.spriteCellChangeSpeed = 0;
  49943. /**
  49944. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the first sprite cell to display.
  49945. */
  49946. this.startSpriteCellID = 0;
  49947. /**
  49948. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the last sprite cell to display.
  49949. */
  49950. this.endSpriteCellID = 0;
  49951. /**
  49952. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use.
  49953. */
  49954. this.spriteCellWidth = 0;
  49955. /**
  49956. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use.
  49957. */
  49958. this.spriteCellHeight = 0;
  49959. /**
  49960. * An event triggered when the system is disposed.
  49961. */
  49962. this.onDisposeObservable = new BABYLON.Observable();
  49963. this._particles = new Array();
  49964. this._stockParticles = new Array();
  49965. this._newPartsExcess = 0;
  49966. this._vertexBuffers = {};
  49967. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  49968. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  49969. this._scaledDirection = BABYLON.Vector3.Zero();
  49970. this._scaledGravity = BABYLON.Vector3.Zero();
  49971. this._currentRenderId = -1;
  49972. this._started = false;
  49973. this._stopped = false;
  49974. this._actualFrame = 0;
  49975. this._vertexBufferSize = 11;
  49976. this._appendParticleVertexes = null;
  49977. this.id = name;
  49978. this.name = name;
  49979. this._capacity = capacity;
  49980. this._epsilon = epsilon;
  49981. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  49982. if (isAnimationSheetEnabled) {
  49983. this._vertexBufferSize = 12;
  49984. }
  49985. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  49986. this._customEffect = customEffect;
  49987. scene.particleSystems.push(this);
  49988. this._createIndexBuffer();
  49989. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  49990. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  49991. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  49992. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  49993. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  49994. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  49995. if (this._isAnimationSheetEnabled) {
  49996. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  49997. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  49998. }
  49999. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  50000. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  50001. this._vertexBuffers["options"] = options;
  50002. // Default behaviors
  50003. this.particleEmitterType = new BABYLON.BoxParticleEmitter(this);
  50004. this.updateFunction = function (particles) {
  50005. for (var index = 0; index < particles.length; index++) {
  50006. var particle = particles[index];
  50007. particle.age += _this._scaledUpdateSpeed;
  50008. if (particle.age >= particle.lifeTime) {
  50009. _this.recycleParticle(particle);
  50010. index--;
  50011. continue;
  50012. }
  50013. else {
  50014. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  50015. particle.color.addInPlace(_this._scaledColorStep);
  50016. if (particle.color.a < 0)
  50017. particle.color.a = 0;
  50018. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  50019. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  50020. particle.position.addInPlace(_this._scaledDirection);
  50021. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  50022. particle.direction.addInPlace(_this._scaledGravity);
  50023. if (_this._isAnimationSheetEnabled) {
  50024. particle.updateCellIndex(_this._scaledUpdateSpeed);
  50025. }
  50026. }
  50027. }
  50028. };
  50029. }
  50030. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  50031. /**
  50032. * Sets a callback that will be triggered when the system is disposed.
  50033. */
  50034. set: function (callback) {
  50035. if (this._onDisposeObserver) {
  50036. this.onDisposeObservable.remove(this._onDisposeObserver);
  50037. }
  50038. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  50039. },
  50040. enumerable: true,
  50041. configurable: true
  50042. });
  50043. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  50044. /**
  50045. * Gets wether an animation sprite sheet is enabled or not on the particle system.
  50046. */
  50047. get: function () {
  50048. return this._isAnimationSheetEnabled;
  50049. },
  50050. enumerable: true,
  50051. configurable: true
  50052. });
  50053. ParticleSystem.prototype._createIndexBuffer = function () {
  50054. var indices = [];
  50055. var index = 0;
  50056. for (var count = 0; count < this._capacity; count++) {
  50057. indices.push(index);
  50058. indices.push(index + 1);
  50059. indices.push(index + 2);
  50060. indices.push(index);
  50061. indices.push(index + 2);
  50062. indices.push(index + 3);
  50063. index += 4;
  50064. }
  50065. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  50066. };
  50067. /**
  50068. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  50069. * Its lifetime will start back at 0.
  50070. * @param particle The particle to recycle
  50071. */
  50072. ParticleSystem.prototype.recycleParticle = function (particle) {
  50073. var lastParticle = this._particles.pop();
  50074. if (lastParticle !== particle) {
  50075. lastParticle.copyTo(particle);
  50076. this._stockParticles.push(lastParticle);
  50077. }
  50078. };
  50079. /**
  50080. * Gets the maximum number of particles active at the same time.
  50081. * @returns The max number of active particles.
  50082. */
  50083. ParticleSystem.prototype.getCapacity = function () {
  50084. return this._capacity;
  50085. };
  50086. /**
  50087. * Gets Wether there are still active particles in the system.
  50088. * @returns True if it is alive, otherwise false.
  50089. */
  50090. ParticleSystem.prototype.isAlive = function () {
  50091. return this._alive;
  50092. };
  50093. /**
  50094. * Gets Wether the system has been started.
  50095. * @returns True if it has been started, otherwise false.
  50096. */
  50097. ParticleSystem.prototype.isStarted = function () {
  50098. return this._started;
  50099. };
  50100. /**
  50101. * Starts the particle system and begins to emit.
  50102. */
  50103. ParticleSystem.prototype.start = function () {
  50104. this._started = true;
  50105. this._stopped = false;
  50106. this._actualFrame = 0;
  50107. };
  50108. /**
  50109. * Stops the particle system.
  50110. */
  50111. ParticleSystem.prototype.stop = function () {
  50112. this._stopped = true;
  50113. };
  50114. /**
  50115. * @ignore (for internal use only)
  50116. */
  50117. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  50118. var offset = index * this._vertexBufferSize;
  50119. this._vertexData[offset] = particle.position.x;
  50120. this._vertexData[offset + 1] = particle.position.y;
  50121. this._vertexData[offset + 2] = particle.position.z;
  50122. this._vertexData[offset + 3] = particle.color.r;
  50123. this._vertexData[offset + 4] = particle.color.g;
  50124. this._vertexData[offset + 5] = particle.color.b;
  50125. this._vertexData[offset + 6] = particle.color.a;
  50126. this._vertexData[offset + 7] = particle.angle;
  50127. this._vertexData[offset + 8] = particle.size;
  50128. this._vertexData[offset + 9] = offsetX;
  50129. this._vertexData[offset + 10] = offsetY;
  50130. };
  50131. /**
  50132. * @ignore (for internal use only)
  50133. */
  50134. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  50135. if (offsetX === 0)
  50136. offsetX = this._epsilon;
  50137. else if (offsetX === 1)
  50138. offsetX = 1 - this._epsilon;
  50139. if (offsetY === 0)
  50140. offsetY = this._epsilon;
  50141. else if (offsetY === 1)
  50142. offsetY = 1 - this._epsilon;
  50143. var offset = index * this._vertexBufferSize;
  50144. this._vertexData[offset] = particle.position.x;
  50145. this._vertexData[offset + 1] = particle.position.y;
  50146. this._vertexData[offset + 2] = particle.position.z;
  50147. this._vertexData[offset + 3] = particle.color.r;
  50148. this._vertexData[offset + 4] = particle.color.g;
  50149. this._vertexData[offset + 5] = particle.color.b;
  50150. this._vertexData[offset + 6] = particle.color.a;
  50151. this._vertexData[offset + 7] = particle.angle;
  50152. this._vertexData[offset + 8] = particle.size;
  50153. this._vertexData[offset + 9] = offsetX;
  50154. this._vertexData[offset + 10] = offsetY;
  50155. this._vertexData[offset + 11] = particle.cellIndex;
  50156. };
  50157. ParticleSystem.prototype._update = function (newParticles) {
  50158. // Update current
  50159. this._alive = this._particles.length > 0;
  50160. this.updateFunction(this._particles);
  50161. // Add new ones
  50162. var worldMatrix;
  50163. if (this.emitter.position) {
  50164. var emitterMesh = this.emitter;
  50165. worldMatrix = emitterMesh.getWorldMatrix();
  50166. }
  50167. else {
  50168. var emitterPosition = this.emitter;
  50169. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  50170. }
  50171. var particle;
  50172. for (var index = 0; index < newParticles; index++) {
  50173. if (this._particles.length === this._capacity) {
  50174. break;
  50175. }
  50176. if (this._stockParticles.length !== 0) {
  50177. particle = this._stockParticles.pop();
  50178. particle.age = 0;
  50179. particle.cellIndex = this.startSpriteCellID;
  50180. }
  50181. else {
  50182. particle = new BABYLON.Particle(this);
  50183. }
  50184. this._particles.push(particle);
  50185. var emitPower = BABYLON.Scalar.RandomRange(this.minEmitPower, this.maxEmitPower);
  50186. if (this.startPositionFunction) {
  50187. this.startPositionFunction(worldMatrix, particle.position, particle);
  50188. }
  50189. else {
  50190. this.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  50191. }
  50192. if (this.startDirectionFunction) {
  50193. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  50194. }
  50195. else {
  50196. this.particleEmitterType.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  50197. }
  50198. particle.lifeTime = BABYLON.Scalar.RandomRange(this.minLifeTime, this.maxLifeTime);
  50199. particle.size = BABYLON.Scalar.RandomRange(this.minSize, this.maxSize);
  50200. particle.angularSpeed = BABYLON.Scalar.RandomRange(this.minAngularSpeed, this.maxAngularSpeed);
  50201. var step = BABYLON.Scalar.RandomRange(0, 1.0);
  50202. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  50203. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  50204. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  50205. }
  50206. };
  50207. ParticleSystem.prototype._getEffect = function () {
  50208. if (this._customEffect) {
  50209. return this._customEffect;
  50210. }
  50211. ;
  50212. var defines = [];
  50213. if (this._scene.clipPlane) {
  50214. defines.push("#define CLIPPLANE");
  50215. }
  50216. if (this._isAnimationSheetEnabled) {
  50217. defines.push("#define ANIMATESHEET");
  50218. }
  50219. // Effect
  50220. var join = defines.join("\n");
  50221. if (this._cachedDefines !== join) {
  50222. this._cachedDefines = join;
  50223. var attributesNamesOrOptions;
  50224. var effectCreationOption;
  50225. if (this._isAnimationSheetEnabled) {
  50226. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"];
  50227. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  50228. }
  50229. else {
  50230. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  50231. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  50232. }
  50233. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  50234. }
  50235. return this._effect;
  50236. };
  50237. /**
  50238. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  50239. */
  50240. ParticleSystem.prototype.animate = function () {
  50241. if (!this._started)
  50242. return;
  50243. var effect = this._getEffect();
  50244. // Check
  50245. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  50246. return;
  50247. if (this._currentRenderId === this._scene.getRenderId()) {
  50248. return;
  50249. }
  50250. this._currentRenderId = this._scene.getRenderId();
  50251. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  50252. // determine the number of particles we need to create
  50253. var newParticles;
  50254. if (this.manualEmitCount > -1) {
  50255. newParticles = this.manualEmitCount;
  50256. this._newPartsExcess = 0;
  50257. this.manualEmitCount = 0;
  50258. }
  50259. else {
  50260. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  50261. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  50262. }
  50263. if (this._newPartsExcess > 1.0) {
  50264. newParticles += this._newPartsExcess >> 0;
  50265. this._newPartsExcess -= this._newPartsExcess >> 0;
  50266. }
  50267. this._alive = false;
  50268. if (!this._stopped) {
  50269. this._actualFrame += this._scaledUpdateSpeed;
  50270. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  50271. this.stop();
  50272. }
  50273. else {
  50274. newParticles = 0;
  50275. }
  50276. this._update(newParticles);
  50277. // Stopped?
  50278. if (this._stopped) {
  50279. if (!this._alive) {
  50280. this._started = false;
  50281. if (this.onAnimationEnd) {
  50282. this.onAnimationEnd();
  50283. }
  50284. if (this.disposeOnStop) {
  50285. this._scene._toBeDisposed.push(this);
  50286. }
  50287. }
  50288. }
  50289. // Animation sheet
  50290. if (this._isAnimationSheetEnabled) {
  50291. this._appendParticleVertexes = this._appenedParticleVertexesWithSheet;
  50292. }
  50293. else {
  50294. this._appendParticleVertexes = this._appenedParticleVertexesNoSheet;
  50295. }
  50296. // Update VBO
  50297. var offset = 0;
  50298. for (var index = 0; index < this._particles.length; index++) {
  50299. var particle = this._particles[index];
  50300. this._appendParticleVertexes(offset, particle);
  50301. offset += 4;
  50302. }
  50303. if (this._vertexBuffer) {
  50304. this._vertexBuffer.update(this._vertexData);
  50305. }
  50306. };
  50307. ParticleSystem.prototype._appenedParticleVertexesWithSheet = function (offset, particle) {
  50308. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  50309. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  50310. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  50311. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  50312. };
  50313. ParticleSystem.prototype._appenedParticleVertexesNoSheet = function (offset, particle) {
  50314. this._appendParticleVertex(offset++, particle, 0, 0);
  50315. this._appendParticleVertex(offset++, particle, 1, 0);
  50316. this._appendParticleVertex(offset++, particle, 1, 1);
  50317. this._appendParticleVertex(offset++, particle, 0, 1);
  50318. };
  50319. /**
  50320. * Rebuilds the particle system.
  50321. */
  50322. ParticleSystem.prototype.rebuild = function () {
  50323. this._createIndexBuffer();
  50324. if (this._vertexBuffer) {
  50325. this._vertexBuffer._rebuild();
  50326. }
  50327. };
  50328. /**
  50329. * Renders the particle system in its current state.
  50330. * @returns the current number of particles.
  50331. */
  50332. ParticleSystem.prototype.render = function () {
  50333. var effect = this._getEffect();
  50334. // Check
  50335. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this._particles.length)
  50336. return 0;
  50337. var engine = this._scene.getEngine();
  50338. // Render
  50339. engine.enableEffect(effect);
  50340. engine.setState(false);
  50341. var viewMatrix = this._scene.getViewMatrix();
  50342. effect.setTexture("diffuseSampler", this.particleTexture);
  50343. effect.setMatrix("view", viewMatrix);
  50344. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  50345. if (this._isAnimationSheetEnabled) {
  50346. var baseSize = this.particleTexture.getBaseSize();
  50347. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  50348. }
  50349. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  50350. if (this._scene.clipPlane) {
  50351. var clipPlane = this._scene.clipPlane;
  50352. var invView = viewMatrix.clone();
  50353. invView.invert();
  50354. effect.setMatrix("invView", invView);
  50355. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  50356. }
  50357. // VBOs
  50358. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  50359. // Draw order
  50360. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  50361. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  50362. }
  50363. else {
  50364. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  50365. }
  50366. if (this.forceDepthWrite) {
  50367. engine.setDepthWrite(true);
  50368. }
  50369. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  50370. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  50371. return this._particles.length;
  50372. };
  50373. /**
  50374. * Disposes the particle system and free the associated resources.
  50375. */
  50376. ParticleSystem.prototype.dispose = function () {
  50377. if (this._vertexBuffer) {
  50378. this._vertexBuffer.dispose();
  50379. this._vertexBuffer = null;
  50380. }
  50381. if (this._indexBuffer) {
  50382. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  50383. this._indexBuffer = null;
  50384. }
  50385. if (this.particleTexture) {
  50386. this.particleTexture.dispose();
  50387. this.particleTexture = null;
  50388. }
  50389. // Remove from scene
  50390. var index = this._scene.particleSystems.indexOf(this);
  50391. if (index > -1) {
  50392. this._scene.particleSystems.splice(index, 1);
  50393. }
  50394. // Callback
  50395. this.onDisposeObservable.notifyObservers(this);
  50396. this.onDisposeObservable.clear();
  50397. };
  50398. /**
  50399. * Creates a Sphere Emitter for the particle system. (emits along the sphere radius)
  50400. * @param radius The radius of the sphere to emit from
  50401. * @returns the emitter
  50402. */
  50403. ParticleSystem.prototype.createSphereEmitter = function (radius) {
  50404. if (radius === void 0) { radius = 1; }
  50405. var particleEmitter = new BABYLON.SphereParticleEmitter(radius);
  50406. this.particleEmitterType = particleEmitter;
  50407. return particleEmitter;
  50408. };
  50409. /**
  50410. * Creates a Directed Sphere Emitter for the particle system. (emits between direction1 and direction2)
  50411. * @param radius The radius of the sphere to emit from
  50412. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  50413. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  50414. * @returns the emitter
  50415. */
  50416. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  50417. if (radius === void 0) { radius = 1; }
  50418. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  50419. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  50420. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  50421. this.particleEmitterType = particleEmitter;
  50422. return particleEmitter;
  50423. };
  50424. /**
  50425. * Creates a Cone Emitter for the particle system. (emits from the cone to the particle position)
  50426. * @param radius The radius of the cone to emit from
  50427. * @param angle The base angle of the cone
  50428. * @returns the emitter
  50429. */
  50430. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  50431. if (radius === void 0) { radius = 1; }
  50432. if (angle === void 0) { angle = Math.PI / 4; }
  50433. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  50434. this.particleEmitterType = particleEmitter;
  50435. return particleEmitter;
  50436. };
  50437. // 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.
  50438. /**
  50439. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  50440. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  50441. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  50442. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  50443. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  50444. * @returns the emitter
  50445. */
  50446. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  50447. var particleEmitter = new BABYLON.BoxParticleEmitter(this);
  50448. this.direction1 = direction1;
  50449. this.direction2 = direction2;
  50450. this.minEmitBox = minEmitBox;
  50451. this.maxEmitBox = maxEmitBox;
  50452. this.particleEmitterType = particleEmitter;
  50453. return particleEmitter;
  50454. };
  50455. /**
  50456. * Clones the particle system.
  50457. * @param name The name of the cloned object
  50458. * @param newEmitter The new emitter to use
  50459. * @returns the cloned particle system
  50460. */
  50461. ParticleSystem.prototype.clone = function (name, newEmitter) {
  50462. var custom = null;
  50463. var program = null;
  50464. if (this.customShader != null) {
  50465. program = this.customShader;
  50466. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  50467. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  50468. }
  50469. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  50470. result.customShader = program;
  50471. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  50472. if (newEmitter === undefined) {
  50473. newEmitter = this.emitter;
  50474. }
  50475. result.emitter = newEmitter;
  50476. if (this.particleTexture) {
  50477. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  50478. }
  50479. if (!this.preventAutoStart) {
  50480. result.start();
  50481. }
  50482. return result;
  50483. };
  50484. /**
  50485. * Serializes the particle system to a JSON object.
  50486. * @returns the JSON object
  50487. */
  50488. ParticleSystem.prototype.serialize = function () {
  50489. var serializationObject = {};
  50490. serializationObject.name = this.name;
  50491. serializationObject.id = this.id;
  50492. // Emitter
  50493. if (this.emitter.position) {
  50494. var emitterMesh = this.emitter;
  50495. serializationObject.emitterId = emitterMesh.id;
  50496. }
  50497. else {
  50498. var emitterPosition = this.emitter;
  50499. serializationObject.emitter = emitterPosition.asArray();
  50500. }
  50501. serializationObject.capacity = this.getCapacity();
  50502. if (this.particleTexture) {
  50503. serializationObject.textureName = this.particleTexture.name;
  50504. }
  50505. // Animations
  50506. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  50507. // Particle system
  50508. serializationObject.minAngularSpeed = this.minAngularSpeed;
  50509. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  50510. serializationObject.minSize = this.minSize;
  50511. serializationObject.maxSize = this.maxSize;
  50512. serializationObject.minEmitPower = this.minEmitPower;
  50513. serializationObject.maxEmitPower = this.maxEmitPower;
  50514. serializationObject.minLifeTime = this.minLifeTime;
  50515. serializationObject.maxLifeTime = this.maxLifeTime;
  50516. serializationObject.emitRate = this.emitRate;
  50517. serializationObject.minEmitBox = this.minEmitBox.asArray();
  50518. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  50519. serializationObject.gravity = this.gravity.asArray();
  50520. serializationObject.direction1 = this.direction1.asArray();
  50521. serializationObject.direction2 = this.direction2.asArray();
  50522. serializationObject.color1 = this.color1.asArray();
  50523. serializationObject.color2 = this.color2.asArray();
  50524. serializationObject.colorDead = this.colorDead.asArray();
  50525. serializationObject.updateSpeed = this.updateSpeed;
  50526. serializationObject.targetStopDuration = this.targetStopDuration;
  50527. serializationObject.textureMask = this.textureMask.asArray();
  50528. serializationObject.blendMode = this.blendMode;
  50529. serializationObject.customShader = this.customShader;
  50530. serializationObject.preventAutoStart = this.preventAutoStart;
  50531. serializationObject.startSpriteCellID = this.startSpriteCellID;
  50532. serializationObject.endSpriteCellID = this.endSpriteCellID;
  50533. serializationObject.spriteCellLoop = this.spriteCellLoop;
  50534. serializationObject.spriteCellChangeSpeed = this.spriteCellChangeSpeed;
  50535. serializationObject.spriteCellWidth = this.spriteCellWidth;
  50536. serializationObject.spriteCellHeight = this.spriteCellHeight;
  50537. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  50538. return serializationObject;
  50539. };
  50540. /**
  50541. * Parses a JSON object to create a particle system.
  50542. * @param parsedParticleSystem The JSON object to parse
  50543. * @param scene The scene to create the particle system in
  50544. * @param rootUrl The root url to use to load external dependencies like texture
  50545. * @returns the Parsed particle system
  50546. */
  50547. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  50548. var name = parsedParticleSystem.name;
  50549. var custom = null;
  50550. var program = null;
  50551. if (parsedParticleSystem.customShader) {
  50552. program = parsedParticleSystem.customShader;
  50553. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  50554. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  50555. }
  50556. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  50557. particleSystem.customShader = program;
  50558. if (parsedParticleSystem.id) {
  50559. particleSystem.id = parsedParticleSystem.id;
  50560. }
  50561. // Auto start
  50562. if (parsedParticleSystem.preventAutoStart) {
  50563. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  50564. }
  50565. // Texture
  50566. if (parsedParticleSystem.textureName) {
  50567. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  50568. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  50569. }
  50570. // Emitter
  50571. if (parsedParticleSystem.emitterId) {
  50572. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  50573. }
  50574. else {
  50575. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  50576. }
  50577. // Animations
  50578. if (parsedParticleSystem.animations) {
  50579. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  50580. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  50581. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  50582. }
  50583. }
  50584. if (parsedParticleSystem.autoAnimate) {
  50585. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  50586. }
  50587. // Particle system
  50588. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  50589. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  50590. particleSystem.minSize = parsedParticleSystem.minSize;
  50591. particleSystem.maxSize = parsedParticleSystem.maxSize;
  50592. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  50593. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  50594. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  50595. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  50596. particleSystem.emitRate = parsedParticleSystem.emitRate;
  50597. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  50598. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  50599. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  50600. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  50601. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  50602. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  50603. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  50604. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  50605. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  50606. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  50607. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  50608. particleSystem.blendMode = parsedParticleSystem.blendMode;
  50609. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  50610. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  50611. particleSystem.spriteCellLoop = parsedParticleSystem.spriteCellLoop;
  50612. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  50613. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  50614. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  50615. if (!particleSystem.preventAutoStart) {
  50616. particleSystem.start();
  50617. }
  50618. return particleSystem;
  50619. };
  50620. /**
  50621. * Source color is added to the destination color without alpha affecting the result.
  50622. */
  50623. ParticleSystem.BLENDMODE_ONEONE = 0;
  50624. /**
  50625. * Blend current color and particle color using particle’s alpha.
  50626. */
  50627. ParticleSystem.BLENDMODE_STANDARD = 1;
  50628. return ParticleSystem;
  50629. }());
  50630. BABYLON.ParticleSystem = ParticleSystem;
  50631. })(BABYLON || (BABYLON = {}));
  50632. //# sourceMappingURL=babylon.particleSystem.js.map
  50633. var BABYLON;
  50634. (function (BABYLON) {
  50635. /**
  50636. * Particle emitter emitting particles from the inside of a box.
  50637. * It emits the particles randomly between 2 given directions.
  50638. */
  50639. var BoxParticleEmitter = /** @class */ (function () {
  50640. // to be updated like the rest of emitters when breaking changes.
  50641. // all property should be come public variables and passed through constructor.
  50642. /**
  50643. * Creates a new instance of @see BoxParticleEmitter
  50644. * @param _particleSystem the particle system associated with the emitter
  50645. */
  50646. function BoxParticleEmitter(_particleSystem) {
  50647. this._particleSystem = _particleSystem;
  50648. }
  50649. Object.defineProperty(BoxParticleEmitter.prototype, "direction1", {
  50650. /**
  50651. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  50652. */
  50653. get: function () {
  50654. return this._particleSystem.direction1;
  50655. },
  50656. /**
  50657. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  50658. */
  50659. set: function (value) {
  50660. this._particleSystem.direction1 = value;
  50661. },
  50662. enumerable: true,
  50663. configurable: true
  50664. });
  50665. Object.defineProperty(BoxParticleEmitter.prototype, "direction2", {
  50666. /**
  50667. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  50668. */
  50669. get: function () {
  50670. return this._particleSystem.direction2;
  50671. },
  50672. /**
  50673. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  50674. */
  50675. set: function (value) {
  50676. this._particleSystem.direction2 = value;
  50677. },
  50678. enumerable: true,
  50679. configurable: true
  50680. });
  50681. Object.defineProperty(BoxParticleEmitter.prototype, "minEmitBox", {
  50682. /**
  50683. * 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.
  50684. */
  50685. get: function () {
  50686. return this._particleSystem.minEmitBox;
  50687. },
  50688. /**
  50689. * 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.
  50690. */
  50691. set: function (value) {
  50692. this._particleSystem.minEmitBox = value;
  50693. },
  50694. enumerable: true,
  50695. configurable: true
  50696. });
  50697. Object.defineProperty(BoxParticleEmitter.prototype, "maxEmitBox", {
  50698. /**
  50699. * 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.
  50700. */
  50701. get: function () {
  50702. return this._particleSystem.maxEmitBox;
  50703. },
  50704. /**
  50705. * 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.
  50706. */
  50707. set: function (value) {
  50708. this._particleSystem.maxEmitBox = value;
  50709. },
  50710. enumerable: true,
  50711. configurable: true
  50712. });
  50713. /**
  50714. * Called by the particle System when the direction is computed for the created particle.
  50715. * @param emitPower is the power of the particle (speed)
  50716. * @param worldMatrix is the world matrix of the particle system
  50717. * @param directionToUpdate is the direction vector to update with the result
  50718. * @param particle is the particle we are computed the direction for
  50719. */
  50720. BoxParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  50721. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  50722. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  50723. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  50724. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  50725. };
  50726. /**
  50727. * Called by the particle System when the position is computed for the created particle.
  50728. * @param worldMatrix is the world matrix of the particle system
  50729. * @param positionToUpdate is the position vector to update with the result
  50730. * @param particle is the particle we are computed the position for
  50731. */
  50732. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  50733. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  50734. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  50735. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  50736. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  50737. };
  50738. /**
  50739. * Clones the current emitter and returns a copy of it
  50740. * @returns the new emitter
  50741. */
  50742. BoxParticleEmitter.prototype.clone = function () {
  50743. var newOne = new BoxParticleEmitter(this._particleSystem);
  50744. BABYLON.Tools.DeepCopy(this, newOne);
  50745. return newOne;
  50746. };
  50747. return BoxParticleEmitter;
  50748. }());
  50749. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  50750. })(BABYLON || (BABYLON = {}));
  50751. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  50752. var BABYLON;
  50753. (function (BABYLON) {
  50754. /**
  50755. * Particle emitter emitting particles from the inside of a cone.
  50756. * It emits the particles alongside the cone volume from the base to the particle.
  50757. * The emission direction might be randomized.
  50758. */
  50759. var ConeParticleEmitter = /** @class */ (function () {
  50760. /**
  50761. * Creates a new instance of @see ConeParticleEmitter
  50762. * @param radius the radius of the emission cone
  50763. * @param angles the cone base angle
  50764. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  50765. */
  50766. function ConeParticleEmitter(radius,
  50767. /**
  50768. * The radius of the emission cone.
  50769. */
  50770. angle,
  50771. /**
  50772. * The cone base angle.
  50773. */
  50774. directionRandomizer) {
  50775. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  50776. this.angle = angle;
  50777. this.directionRandomizer = directionRandomizer;
  50778. this.radius = radius;
  50779. }
  50780. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  50781. /**
  50782. * Gets the radius of the emission cone.
  50783. */
  50784. get: function () {
  50785. return this._radius;
  50786. },
  50787. /**
  50788. * Sets the radius of the emission cone.
  50789. */
  50790. set: function (value) {
  50791. this._radius = value;
  50792. if (this.angle !== 0) {
  50793. this._height = value / Math.tan(this.angle / 2);
  50794. }
  50795. else {
  50796. this._height = 1;
  50797. }
  50798. },
  50799. enumerable: true,
  50800. configurable: true
  50801. });
  50802. /**
  50803. * Called by the particle System when the direction is computed for the created particle.
  50804. * @param emitPower is the power of the particle (speed)
  50805. * @param worldMatrix is the world matrix of the particle system
  50806. * @param directionToUpdate is the direction vector to update with the result
  50807. * @param particle is the particle we are computed the direction for
  50808. */
  50809. ConeParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  50810. if (this.angle === 0) {
  50811. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, emitPower, 0, worldMatrix, directionToUpdate);
  50812. }
  50813. else {
  50814. // measure the direction Vector from the emitter to the particle.
  50815. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  50816. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  50817. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  50818. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  50819. direction.x += randX;
  50820. direction.y += randY;
  50821. direction.z += randZ;
  50822. direction.normalize();
  50823. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  50824. }
  50825. };
  50826. /**
  50827. * Called by the particle System when the position is computed for the created particle.
  50828. * @param worldMatrix is the world matrix of the particle system
  50829. * @param positionToUpdate is the position vector to update with the result
  50830. * @param particle is the particle we are computed the position for
  50831. */
  50832. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  50833. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  50834. var h = BABYLON.Scalar.RandomRange(0, 1);
  50835. // Better distribution in a cone at normal angles.
  50836. h = 1 - h * h;
  50837. var radius = BABYLON.Scalar.RandomRange(0, this._radius);
  50838. radius = radius * h / this._height;
  50839. var randX = radius * Math.sin(s);
  50840. var randZ = radius * Math.cos(s);
  50841. var randY = h;
  50842. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  50843. };
  50844. /**
  50845. * Clones the current emitter and returns a copy of it
  50846. * @returns the new emitter
  50847. */
  50848. ConeParticleEmitter.prototype.clone = function () {
  50849. var newOne = new ConeParticleEmitter(this.radius, this.angle, this.directionRandomizer);
  50850. BABYLON.Tools.DeepCopy(this, newOne);
  50851. return newOne;
  50852. };
  50853. return ConeParticleEmitter;
  50854. }());
  50855. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  50856. })(BABYLON || (BABYLON = {}));
  50857. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  50858. var BABYLON;
  50859. (function (BABYLON) {
  50860. /**
  50861. * Particle emitter emitting particles from the inside of a sphere.
  50862. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  50863. */
  50864. var SphereParticleEmitter = /** @class */ (function () {
  50865. /**
  50866. * Creates a new instance of @see SphereParticleEmitter
  50867. * @param radius the radius of the emission sphere
  50868. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  50869. */
  50870. function SphereParticleEmitter(
  50871. /**
  50872. * The radius of the emission sphere.
  50873. */
  50874. radius,
  50875. /**
  50876. * How much to randomize the particle direction [0-1].
  50877. */
  50878. directionRandomizer) {
  50879. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  50880. this.radius = radius;
  50881. this.directionRandomizer = directionRandomizer;
  50882. }
  50883. /**
  50884. * Called by the particle System when the direction is computed for the created particle.
  50885. * @param emitPower is the power of the particle (speed)
  50886. * @param worldMatrix is the world matrix of the particle system
  50887. * @param directionToUpdate is the direction vector to update with the result
  50888. * @param particle is the particle we are computed the direction for
  50889. */
  50890. SphereParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  50891. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  50892. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  50893. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  50894. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  50895. direction.x += randX;
  50896. direction.y += randY;
  50897. direction.z += randZ;
  50898. direction.normalize();
  50899. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  50900. };
  50901. /**
  50902. * Called by the particle System when the position is computed for the created particle.
  50903. * @param worldMatrix is the world matrix of the particle system
  50904. * @param positionToUpdate is the position vector to update with the result
  50905. * @param particle is the particle we are computed the position for
  50906. */
  50907. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  50908. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  50909. var theta = BABYLON.Scalar.RandomRange(0, Math.PI);
  50910. var randX = this.radius * Math.cos(phi) * Math.sin(theta);
  50911. var randY = this.radius * Math.cos(theta);
  50912. var randZ = this.radius * Math.sin(phi) * Math.sin(theta);
  50913. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  50914. };
  50915. /**
  50916. * Clones the current emitter and returns a copy of it
  50917. * @returns the new emitter
  50918. */
  50919. SphereParticleEmitter.prototype.clone = function () {
  50920. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  50921. BABYLON.Tools.DeepCopy(this, newOne);
  50922. return newOne;
  50923. };
  50924. return SphereParticleEmitter;
  50925. }());
  50926. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  50927. /**
  50928. * Particle emitter emitting particles from the inside of a sphere.
  50929. * It emits the particles randomly between two vectors.
  50930. */
  50931. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  50932. __extends(SphereDirectedParticleEmitter, _super);
  50933. /**
  50934. * Creates a new instance of @see SphereDirectedParticleEmitter
  50935. * @param radius the radius of the emission sphere
  50936. * @param direction1 the min limit of the emission direction
  50937. * @param direction2 the max limit of the emission direction
  50938. */
  50939. function SphereDirectedParticleEmitter(radius,
  50940. /**
  50941. * The min limit of the emission direction.
  50942. */
  50943. direction1,
  50944. /**
  50945. * The max limit of the emission direction.
  50946. */
  50947. direction2) {
  50948. var _this = _super.call(this, radius) || this;
  50949. _this.direction1 = direction1;
  50950. _this.direction2 = direction2;
  50951. return _this;
  50952. }
  50953. /**
  50954. * Called by the particle System when the direction is computed for the created particle.
  50955. * @param emitPower is the power of the particle (speed)
  50956. * @param worldMatrix is the world matrix of the particle system
  50957. * @param directionToUpdate is the direction vector to update with the result
  50958. * @param particle is the particle we are computed the direction for
  50959. */
  50960. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  50961. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  50962. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  50963. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  50964. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  50965. };
  50966. /**
  50967. * Clones the current emitter and returns a copy of it
  50968. * @returns the new emitter
  50969. */
  50970. SphereDirectedParticleEmitter.prototype.clone = function () {
  50971. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  50972. BABYLON.Tools.DeepCopy(this, newOne);
  50973. return newOne;
  50974. };
  50975. return SphereDirectedParticleEmitter;
  50976. }(SphereParticleEmitter));
  50977. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  50978. })(BABYLON || (BABYLON = {}));
  50979. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  50980. //# sourceMappingURL=babylon.iParticleEmitterType.js.map
  50981. var BABYLON;
  50982. (function (BABYLON) {
  50983. /**
  50984. * Represents one particle of a solid particle system.
  50985. * @see SolidParticleSystem
  50986. */
  50987. var SolidParticle = /** @class */ (function () {
  50988. /**
  50989. * Creates a Solid Particle object.
  50990. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  50991. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  50992. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  50993. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  50994. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  50995. * @param shapeId (integer) is the model shape identifier in the SPS.
  50996. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  50997. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  50998. */
  50999. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  51000. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  51001. /**
  51002. * particle global index
  51003. */
  51004. this.idx = 0;
  51005. /**
  51006. * The color of the particle
  51007. */
  51008. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  51009. /**
  51010. * The world space position of the particle.
  51011. */
  51012. this.position = BABYLON.Vector3.Zero();
  51013. /**
  51014. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  51015. */
  51016. this.rotation = BABYLON.Vector3.Zero();
  51017. /**
  51018. * The scaling of the particle.
  51019. */
  51020. this.scaling = BABYLON.Vector3.One();
  51021. /**
  51022. * The uvs of the particle.
  51023. */
  51024. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  51025. /**
  51026. * The current speed of the particle.
  51027. */
  51028. this.velocity = BABYLON.Vector3.Zero();
  51029. /**
  51030. * The pivot point in the particle local space.
  51031. */
  51032. this.pivot = BABYLON.Vector3.Zero();
  51033. /**
  51034. * Must the particle be translated from its pivot point in its local space ?
  51035. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  51036. * Default : false
  51037. */
  51038. this.translateFromPivot = false;
  51039. /**
  51040. * Is the particle active or not ?
  51041. */
  51042. this.alive = true;
  51043. /**
  51044. * Is the particle visible or not ?
  51045. */
  51046. this.isVisible = true;
  51047. /**
  51048. * Index of this particle in the global "positions" array (Internal use)
  51049. */
  51050. this._pos = 0;
  51051. /**
  51052. * Index of this particle in the global "indices" array (Internal use)
  51053. */
  51054. this._ind = 0;
  51055. /**
  51056. * ModelShape id of this particle
  51057. */
  51058. this.shapeId = 0;
  51059. /**
  51060. * Index of the particle in its shape id (Internal use)
  51061. */
  51062. this.idxInShape = 0;
  51063. /**
  51064. * Still set as invisible in order to skip useless computations (Internal use)
  51065. */
  51066. this._stillInvisible = false;
  51067. /**
  51068. * Last computed particle rotation matrix
  51069. */
  51070. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  51071. this.idx = particleIndex;
  51072. this._pos = positionIndex;
  51073. this._ind = indiceIndex;
  51074. this._model = model;
  51075. this.shapeId = shapeId;
  51076. this.idxInShape = idxInShape;
  51077. this._sps = sps;
  51078. if (modelBoundingInfo) {
  51079. this._modelBoundingInfo = modelBoundingInfo;
  51080. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  51081. }
  51082. }
  51083. Object.defineProperty(SolidParticle.prototype, "scale", {
  51084. /**
  51085. * Legacy support, changed scale to scaling
  51086. */
  51087. get: function () {
  51088. return this.scaling;
  51089. },
  51090. /**
  51091. * Legacy support, changed scale to scaling
  51092. */
  51093. set: function (scale) {
  51094. this.scaling = scale;
  51095. },
  51096. enumerable: true,
  51097. configurable: true
  51098. });
  51099. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  51100. /**
  51101. * Legacy support, changed quaternion to rotationQuaternion
  51102. */
  51103. get: function () {
  51104. return this.rotationQuaternion;
  51105. },
  51106. /**
  51107. * Legacy support, changed quaternion to rotationQuaternion
  51108. */
  51109. set: function (q) {
  51110. this.rotationQuaternion = q;
  51111. },
  51112. enumerable: true,
  51113. configurable: true
  51114. });
  51115. /**
  51116. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  51117. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  51118. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  51119. * @returns true if it intersects
  51120. */
  51121. SolidParticle.prototype.intersectsMesh = function (target) {
  51122. if (!this._boundingInfo || !target._boundingInfo) {
  51123. return false;
  51124. }
  51125. if (this._sps._bSphereOnly) {
  51126. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  51127. }
  51128. return this._boundingInfo.intersects(target._boundingInfo, false);
  51129. };
  51130. return SolidParticle;
  51131. }());
  51132. BABYLON.SolidParticle = SolidParticle;
  51133. /**
  51134. * Represents the shape of the model used by one particle of a solid particle system.
  51135. * SPS internal tool, don't use it manually.
  51136. * @see SolidParticleSystem
  51137. */
  51138. var ModelShape = /** @class */ (function () {
  51139. /**
  51140. * 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.
  51141. * SPS internal tool, don't use it manually.
  51142. * @ignore
  51143. */
  51144. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  51145. /**
  51146. * length of the shape in the model indices array (internal use)
  51147. */
  51148. this._indicesLength = 0;
  51149. this.shapeID = id;
  51150. this._shape = shape;
  51151. this._indicesLength = indicesLength;
  51152. this._shapeUV = shapeUV;
  51153. this._positionFunction = posFunction;
  51154. this._vertexFunction = vtxFunction;
  51155. }
  51156. return ModelShape;
  51157. }());
  51158. BABYLON.ModelShape = ModelShape;
  51159. /**
  51160. * Represents a Depth Sorted Particle in the solid particle system.
  51161. * @see SolidParticleSystem
  51162. */
  51163. var DepthSortedParticle = /** @class */ (function () {
  51164. function DepthSortedParticle() {
  51165. /**
  51166. * Index of the particle in the "indices" array
  51167. */
  51168. this.ind = 0;
  51169. /**
  51170. * Length of the particle shape in the "indices" array
  51171. */
  51172. this.indicesLength = 0;
  51173. /**
  51174. * Squared distance from the particle to the camera
  51175. */
  51176. this.sqDistance = 0.0;
  51177. }
  51178. return DepthSortedParticle;
  51179. }());
  51180. BABYLON.DepthSortedParticle = DepthSortedParticle;
  51181. })(BABYLON || (BABYLON = {}));
  51182. //# sourceMappingURL=babylon.solidParticle.js.map
  51183. var BABYLON;
  51184. (function (BABYLON) {
  51185. /**
  51186. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  51187. *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.
  51188. * The SPS is also a particle system. It provides some methods to manage the particles.
  51189. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  51190. *
  51191. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  51192. */
  51193. var SolidParticleSystem = /** @class */ (function () {
  51194. /**
  51195. * Creates a SPS (Solid Particle System) object.
  51196. * @param name (String) is the SPS name, this will be the underlying mesh name.
  51197. * @param scene (Scene) is the scene in which the SPS is added.
  51198. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  51199. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  51200. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  51201. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  51202. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  51203. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  51204. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  51205. */
  51206. function SolidParticleSystem(name, scene, options) {
  51207. /**
  51208. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  51209. * Example : var p = SPS.particles[i];
  51210. */
  51211. this.particles = new Array();
  51212. /**
  51213. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  51214. */
  51215. this.nbParticles = 0;
  51216. /**
  51217. * If the particles must ever face the camera (default false). Useful for planar particles.
  51218. */
  51219. this.billboard = false;
  51220. /**
  51221. * Recompute normals when adding a shape
  51222. */
  51223. this.recomputeNormals = true;
  51224. /**
  51225. * This a counter ofr your own usage. It's not set by any SPS functions.
  51226. */
  51227. this.counter = 0;
  51228. /**
  51229. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  51230. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  51231. */
  51232. this.vars = {};
  51233. /**
  51234. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  51235. */
  51236. this._bSphereOnly = false;
  51237. /**
  51238. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  51239. */
  51240. this._bSphereRadiusFactor = 1.0;
  51241. this._positions = new Array();
  51242. this._indices = new Array();
  51243. this._normals = new Array();
  51244. this._colors = new Array();
  51245. this._uvs = new Array();
  51246. this._index = 0; // indices index
  51247. this._updatable = true;
  51248. this._pickable = false;
  51249. this._isVisibilityBoxLocked = false;
  51250. this._alwaysVisible = false;
  51251. this._depthSort = false;
  51252. this._shapeCounter = 0;
  51253. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  51254. this._color = new BABYLON.Color4(0, 0, 0, 0);
  51255. this._computeParticleColor = true;
  51256. this._computeParticleTexture = true;
  51257. this._computeParticleRotation = true;
  51258. this._computeParticleVertex = false;
  51259. this._computeBoundingBox = false;
  51260. this._depthSortParticles = true;
  51261. this._cam_axisZ = BABYLON.Vector3.Zero();
  51262. this._cam_axisY = BABYLON.Vector3.Zero();
  51263. this._cam_axisX = BABYLON.Vector3.Zero();
  51264. this._axisZ = BABYLON.Axis.Z;
  51265. this._camDir = BABYLON.Vector3.Zero();
  51266. this._camInvertedPosition = BABYLON.Vector3.Zero();
  51267. this._rotMatrix = new BABYLON.Matrix();
  51268. this._invertMatrix = new BABYLON.Matrix();
  51269. this._rotated = BABYLON.Vector3.Zero();
  51270. this._quaternion = new BABYLON.Quaternion();
  51271. this._vertex = BABYLON.Vector3.Zero();
  51272. this._normal = BABYLON.Vector3.Zero();
  51273. this._yaw = 0.0;
  51274. this._pitch = 0.0;
  51275. this._roll = 0.0;
  51276. this._halfroll = 0.0;
  51277. this._halfpitch = 0.0;
  51278. this._halfyaw = 0.0;
  51279. this._sinRoll = 0.0;
  51280. this._cosRoll = 0.0;
  51281. this._sinPitch = 0.0;
  51282. this._cosPitch = 0.0;
  51283. this._sinYaw = 0.0;
  51284. this._cosYaw = 0.0;
  51285. this._mustUnrotateFixedNormals = false;
  51286. this._minimum = BABYLON.Vector3.Zero();
  51287. this._maximum = BABYLON.Vector3.Zero();
  51288. this._minBbox = BABYLON.Vector3.Zero();
  51289. this._maxBbox = BABYLON.Vector3.Zero();
  51290. this._particlesIntersect = false;
  51291. this._depthSortFunction = function (p1, p2) {
  51292. return (p2.sqDistance - p1.sqDistance);
  51293. };
  51294. this._needs32Bits = false;
  51295. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  51296. this.name = name;
  51297. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  51298. this._camera = scene.activeCamera;
  51299. this._pickable = options ? options.isPickable : false;
  51300. this._depthSort = options ? options.enableDepthSort : false;
  51301. this._particlesIntersect = options ? options.particleIntersection : false;
  51302. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  51303. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  51304. if (options && options.updatable) {
  51305. this._updatable = options.updatable;
  51306. }
  51307. else {
  51308. this._updatable = true;
  51309. }
  51310. if (this._pickable) {
  51311. this.pickedParticles = [];
  51312. }
  51313. if (this._depthSort) {
  51314. this.depthSortedParticles = [];
  51315. }
  51316. }
  51317. /**
  51318. * Builds the SPS underlying mesh. Returns a standard Mesh.
  51319. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  51320. * @returns the created mesh
  51321. */
  51322. SolidParticleSystem.prototype.buildMesh = function () {
  51323. if (this.nbParticles === 0) {
  51324. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  51325. this.addShape(triangle, 1);
  51326. triangle.dispose();
  51327. }
  51328. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  51329. this._positions32 = new Float32Array(this._positions);
  51330. this._uvs32 = new Float32Array(this._uvs);
  51331. this._colors32 = new Float32Array(this._colors);
  51332. if (this.recomputeNormals) {
  51333. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  51334. }
  51335. this._normals32 = new Float32Array(this._normals);
  51336. this._fixedNormal32 = new Float32Array(this._normals);
  51337. if (this._mustUnrotateFixedNormals) {
  51338. this._unrotateFixedNormals();
  51339. }
  51340. var vertexData = new BABYLON.VertexData();
  51341. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  51342. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  51343. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  51344. if (this._uvs32) {
  51345. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  51346. ;
  51347. }
  51348. if (this._colors32) {
  51349. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  51350. }
  51351. var mesh = new BABYLON.Mesh(this.name, this._scene);
  51352. vertexData.applyToMesh(mesh, this._updatable);
  51353. this.mesh = mesh;
  51354. this.mesh.isPickable = this._pickable;
  51355. // free memory
  51356. if (!this._depthSort) {
  51357. this._indices = null;
  51358. }
  51359. this._positions = null;
  51360. this._normals = null;
  51361. this._uvs = null;
  51362. this._colors = null;
  51363. if (!this._updatable) {
  51364. this.particles.length = 0;
  51365. }
  51366. return mesh;
  51367. };
  51368. /**
  51369. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  51370. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  51371. * Thus the particles generated from `digest()` have their property `position` set yet.
  51372. * @param mesh ( Mesh ) is the mesh to be digested
  51373. * @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
  51374. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  51375. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  51376. * @returns the current SPS
  51377. */
  51378. SolidParticleSystem.prototype.digest = function (mesh, options) {
  51379. var size = (options && options.facetNb) || 1;
  51380. var number = (options && options.number) || 0;
  51381. var delta = (options && options.delta) || 0;
  51382. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  51383. var meshInd = mesh.getIndices();
  51384. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  51385. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  51386. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  51387. var f = 0; // facet counter
  51388. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  51389. // compute size from number
  51390. if (number) {
  51391. number = (number > totalFacets) ? totalFacets : number;
  51392. size = Math.round(totalFacets / number);
  51393. delta = 0;
  51394. }
  51395. else {
  51396. size = (size > totalFacets) ? totalFacets : size;
  51397. }
  51398. var facetPos = []; // submesh positions
  51399. var facetInd = []; // submesh indices
  51400. var facetUV = []; // submesh UV
  51401. var facetCol = []; // submesh colors
  51402. var barycenter = BABYLON.Vector3.Zero();
  51403. var sizeO = size;
  51404. while (f < totalFacets) {
  51405. size = sizeO + Math.floor((1 + delta) * Math.random());
  51406. if (f > totalFacets - size) {
  51407. size = totalFacets - f;
  51408. }
  51409. // reset temp arrays
  51410. facetPos.length = 0;
  51411. facetInd.length = 0;
  51412. facetUV.length = 0;
  51413. facetCol.length = 0;
  51414. // iterate over "size" facets
  51415. var fi = 0;
  51416. for (var j = f * 3; j < (f + size) * 3; j++) {
  51417. facetInd.push(fi);
  51418. var i = meshInd[j];
  51419. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  51420. if (meshUV) {
  51421. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  51422. }
  51423. if (meshCol) {
  51424. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  51425. }
  51426. fi++;
  51427. }
  51428. // create a model shape for each single particle
  51429. var idx = this.nbParticles;
  51430. var shape = this._posToShape(facetPos);
  51431. var shapeUV = this._uvsToShapeUV(facetUV);
  51432. // compute the barycenter of the shape
  51433. var v;
  51434. for (v = 0; v < shape.length; v++) {
  51435. barycenter.addInPlace(shape[v]);
  51436. }
  51437. barycenter.scaleInPlace(1 / shape.length);
  51438. // shift the shape from its barycenter to the origin
  51439. for (v = 0; v < shape.length; v++) {
  51440. shape[v].subtractInPlace(barycenter);
  51441. }
  51442. var bInfo;
  51443. if (this._particlesIntersect) {
  51444. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  51445. }
  51446. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  51447. // add the particle in the SPS
  51448. var currentPos = this._positions.length;
  51449. var currentInd = this._indices.length;
  51450. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  51451. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  51452. // initialize the particle position
  51453. this.particles[this.nbParticles].position.addInPlace(barycenter);
  51454. this._index += shape.length;
  51455. idx++;
  51456. this.nbParticles++;
  51457. this._shapeCounter++;
  51458. f += size;
  51459. }
  51460. return this;
  51461. };
  51462. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  51463. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  51464. var index = 0;
  51465. var idx = 0;
  51466. for (var p = 0; p < this.particles.length; p++) {
  51467. this._particle = this.particles[p];
  51468. this._shape = this._particle._model._shape;
  51469. if (this._particle.rotationQuaternion) {
  51470. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  51471. }
  51472. else {
  51473. this._yaw = this._particle.rotation.y;
  51474. this._pitch = this._particle.rotation.x;
  51475. this._roll = this._particle.rotation.z;
  51476. this._quaternionRotationYPR();
  51477. }
  51478. this._quaternionToRotationMatrix();
  51479. this._rotMatrix.invertToRef(this._invertMatrix);
  51480. for (var pt = 0; pt < this._shape.length; pt++) {
  51481. idx = index + pt * 3;
  51482. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  51483. this._fixedNormal32[idx] = this._normal.x;
  51484. this._fixedNormal32[idx + 1] = this._normal.y;
  51485. this._fixedNormal32[idx + 2] = this._normal.z;
  51486. }
  51487. index = idx + 3;
  51488. }
  51489. };
  51490. //reset copy
  51491. SolidParticleSystem.prototype._resetCopy = function () {
  51492. this._copy.position.x = 0;
  51493. this._copy.position.y = 0;
  51494. this._copy.position.z = 0;
  51495. this._copy.rotation.x = 0;
  51496. this._copy.rotation.y = 0;
  51497. this._copy.rotation.z = 0;
  51498. this._copy.rotationQuaternion = null;
  51499. this._copy.scaling.x = 1.0;
  51500. this._copy.scaling.y = 1.0;
  51501. this._copy.scaling.z = 1.0;
  51502. this._copy.uvs.x = 0;
  51503. this._copy.uvs.y = 0;
  51504. this._copy.uvs.z = 1.0;
  51505. this._copy.uvs.w = 1.0;
  51506. this._copy.color = null;
  51507. this._copy.translateFromPivot = false;
  51508. };
  51509. // _meshBuilder : inserts the shape model in the global SPS mesh
  51510. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  51511. var i;
  51512. var u = 0;
  51513. var c = 0;
  51514. var n = 0;
  51515. this._resetCopy();
  51516. if (options && options.positionFunction) {
  51517. options.positionFunction(this._copy, idx, idxInShape);
  51518. this._mustUnrotateFixedNormals = true;
  51519. }
  51520. if (this._copy.rotationQuaternion) {
  51521. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  51522. }
  51523. else {
  51524. this._yaw = this._copy.rotation.y;
  51525. this._pitch = this._copy.rotation.x;
  51526. this._roll = this._copy.rotation.z;
  51527. this._quaternionRotationYPR();
  51528. }
  51529. this._quaternionToRotationMatrix();
  51530. if (this._copy.translateFromPivot) {
  51531. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  51532. }
  51533. else {
  51534. this._pivotBackTranslation.copyFrom(this._copy.pivot);
  51535. }
  51536. for (i = 0; i < shape.length; i++) {
  51537. this._vertex.x = shape[i].x;
  51538. this._vertex.y = shape[i].y;
  51539. this._vertex.z = shape[i].z;
  51540. if (options && options.vertexFunction) {
  51541. options.vertexFunction(this._copy, this._vertex, i);
  51542. }
  51543. this._vertex.x *= this._copy.scaling.x;
  51544. this._vertex.y *= this._copy.scaling.y;
  51545. this._vertex.z *= this._copy.scaling.z;
  51546. this._vertex.x -= this._copy.pivot.x;
  51547. this._vertex.y -= this._copy.pivot.y;
  51548. this._vertex.z -= this._copy.pivot.z;
  51549. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  51550. this._rotated.addInPlace(this._pivotBackTranslation);
  51551. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  51552. if (meshUV) {
  51553. 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);
  51554. u += 2;
  51555. }
  51556. if (this._copy.color) {
  51557. this._color = this._copy.color;
  51558. }
  51559. else if (meshCol && meshCol[c] !== undefined) {
  51560. this._color.r = meshCol[c];
  51561. this._color.g = meshCol[c + 1];
  51562. this._color.b = meshCol[c + 2];
  51563. this._color.a = meshCol[c + 3];
  51564. }
  51565. else {
  51566. this._color.r = 1.0;
  51567. this._color.g = 1.0;
  51568. this._color.b = 1.0;
  51569. this._color.a = 1.0;
  51570. }
  51571. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  51572. c += 4;
  51573. if (!this.recomputeNormals && meshNor) {
  51574. this._normal.x = meshNor[n];
  51575. this._normal.y = meshNor[n + 1];
  51576. this._normal.z = meshNor[n + 2];
  51577. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  51578. normals.push(this._normal.x, this._normal.y, this._normal.z);
  51579. n += 3;
  51580. }
  51581. }
  51582. for (i = 0; i < meshInd.length; i++) {
  51583. var current_ind = p + meshInd[i];
  51584. indices.push(current_ind);
  51585. if (current_ind > 65535) {
  51586. this._needs32Bits = true;
  51587. }
  51588. }
  51589. if (this._pickable) {
  51590. var nbfaces = meshInd.length / 3;
  51591. for (i = 0; i < nbfaces; i++) {
  51592. this.pickedParticles.push({ idx: idx, faceId: i });
  51593. }
  51594. }
  51595. if (this._depthSort) {
  51596. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  51597. }
  51598. return this._copy;
  51599. };
  51600. // returns a shape array from positions array
  51601. SolidParticleSystem.prototype._posToShape = function (positions) {
  51602. var shape = [];
  51603. for (var i = 0; i < positions.length; i += 3) {
  51604. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  51605. }
  51606. return shape;
  51607. };
  51608. // returns a shapeUV array from a Vector4 uvs
  51609. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  51610. var shapeUV = [];
  51611. if (uvs) {
  51612. for (var i = 0; i < uvs.length; i++)
  51613. shapeUV.push(uvs[i]);
  51614. }
  51615. return shapeUV;
  51616. };
  51617. // adds a new particle object in the particles array
  51618. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  51619. if (bInfo === void 0) { bInfo = null; }
  51620. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  51621. this.particles.push(sp);
  51622. return sp;
  51623. };
  51624. /**
  51625. * Adds some particles to the SPS from the model shape. Returns the shape id.
  51626. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  51627. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  51628. * @param nb (positive integer) the number of particles to be created from this model
  51629. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  51630. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  51631. * @returns the number of shapes in the system
  51632. */
  51633. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  51634. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  51635. var meshInd = mesh.getIndices();
  51636. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  51637. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  51638. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  51639. var bbInfo;
  51640. if (this._particlesIntersect) {
  51641. bbInfo = mesh.getBoundingInfo();
  51642. }
  51643. var shape = this._posToShape(meshPos);
  51644. var shapeUV = this._uvsToShapeUV(meshUV);
  51645. var posfunc = options ? options.positionFunction : null;
  51646. var vtxfunc = options ? options.vertexFunction : null;
  51647. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  51648. // particles
  51649. var sp;
  51650. var currentCopy;
  51651. var idx = this.nbParticles;
  51652. for (var i = 0; i < nb; i++) {
  51653. var currentPos = this._positions.length;
  51654. var currentInd = this._indices.length;
  51655. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  51656. if (this._updatable) {
  51657. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  51658. sp.position.copyFrom(currentCopy.position);
  51659. sp.rotation.copyFrom(currentCopy.rotation);
  51660. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  51661. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  51662. }
  51663. if (currentCopy.color && sp.color) {
  51664. sp.color.copyFrom(currentCopy.color);
  51665. }
  51666. sp.scaling.copyFrom(currentCopy.scaling);
  51667. sp.uvs.copyFrom(currentCopy.uvs);
  51668. }
  51669. this._index += shape.length;
  51670. idx++;
  51671. }
  51672. this.nbParticles += nb;
  51673. this._shapeCounter++;
  51674. return this._shapeCounter - 1;
  51675. };
  51676. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  51677. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  51678. this._resetCopy();
  51679. if (particle._model._positionFunction) {
  51680. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  51681. }
  51682. if (this._copy.rotationQuaternion) {
  51683. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  51684. }
  51685. else {
  51686. this._yaw = this._copy.rotation.y;
  51687. this._pitch = this._copy.rotation.x;
  51688. this._roll = this._copy.rotation.z;
  51689. this._quaternionRotationYPR();
  51690. }
  51691. this._quaternionToRotationMatrix();
  51692. if (this._copy.translateFromPivot) {
  51693. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  51694. }
  51695. else {
  51696. this._pivotBackTranslation.copyFrom(this._copy.pivot);
  51697. }
  51698. this._shape = particle._model._shape;
  51699. for (var pt = 0; pt < this._shape.length; pt++) {
  51700. this._vertex.x = this._shape[pt].x;
  51701. this._vertex.y = this._shape[pt].y;
  51702. this._vertex.z = this._shape[pt].z;
  51703. if (particle._model._vertexFunction) {
  51704. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  51705. }
  51706. this._vertex.x *= this._copy.scaling.x;
  51707. this._vertex.y *= this._copy.scaling.y;
  51708. this._vertex.z *= this._copy.scaling.z;
  51709. this._vertex.x -= this._copy.pivot.x;
  51710. this._vertex.y -= this._copy.pivot.y;
  51711. this._vertex.z -= this._copy.pivot.z;
  51712. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  51713. this._rotated.addInPlace(this._pivotBackTranslation);
  51714. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  51715. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  51716. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  51717. }
  51718. particle.position.x = 0.0;
  51719. particle.position.y = 0.0;
  51720. particle.position.z = 0.0;
  51721. particle.rotation.x = 0.0;
  51722. particle.rotation.y = 0.0;
  51723. particle.rotation.z = 0.0;
  51724. particle.rotationQuaternion = null;
  51725. particle.scaling.x = 1.0;
  51726. particle.scaling.y = 1.0;
  51727. particle.scaling.z = 1.0;
  51728. };
  51729. /**
  51730. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  51731. * @returns the SPS.
  51732. */
  51733. SolidParticleSystem.prototype.rebuildMesh = function () {
  51734. for (var p = 0; p < this.particles.length; p++) {
  51735. this._rebuildParticle(this.particles[p]);
  51736. }
  51737. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  51738. return this;
  51739. };
  51740. /**
  51741. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  51742. * This method calls `updateParticle()` for each particle of the SPS.
  51743. * For an animated SPS, it is usually called within the render loop.
  51744. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  51745. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  51746. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  51747. * @returns the SPS.
  51748. */
  51749. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  51750. if (start === void 0) { start = 0; }
  51751. if (end === void 0) { end = this.nbParticles - 1; }
  51752. if (update === void 0) { update = true; }
  51753. if (!this._updatable) {
  51754. return this;
  51755. }
  51756. // custom beforeUpdate
  51757. this.beforeUpdateParticles(start, end, update);
  51758. this._cam_axisX.x = 1.0;
  51759. this._cam_axisX.y = 0.0;
  51760. this._cam_axisX.z = 0.0;
  51761. this._cam_axisY.x = 0.0;
  51762. this._cam_axisY.y = 1.0;
  51763. this._cam_axisY.z = 0.0;
  51764. this._cam_axisZ.x = 0.0;
  51765. this._cam_axisZ.y = 0.0;
  51766. this._cam_axisZ.z = 1.0;
  51767. // cases when the World Matrix is to be computed first
  51768. if (this.billboard || this._depthSort) {
  51769. this.mesh.computeWorldMatrix(true);
  51770. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  51771. }
  51772. // if the particles will always face the camera
  51773. if (this.billboard) {
  51774. // compute the camera position and un-rotate it by the current mesh rotation
  51775. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  51776. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  51777. this._cam_axisZ.normalize();
  51778. // same for camera up vector extracted from the cam view matrix
  51779. var view = this._camera.getViewMatrix(true);
  51780. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  51781. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  51782. this._cam_axisY.normalize();
  51783. this._cam_axisX.normalize();
  51784. }
  51785. // if depthSort, compute the camera global position in the mesh local system
  51786. if (this._depthSort) {
  51787. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  51788. }
  51789. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  51790. var idx = 0; // current position index in the global array positions32
  51791. var index = 0; // position start index in the global array positions32 of the current particle
  51792. var colidx = 0; // current color index in the global array colors32
  51793. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  51794. var uvidx = 0; // current uv index in the global array uvs32
  51795. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  51796. var pt = 0; // current index in the particle model shape
  51797. if (this.mesh.isFacetDataEnabled) {
  51798. this._computeBoundingBox = true;
  51799. }
  51800. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  51801. if (this._computeBoundingBox) {
  51802. if (start == 0 && end == this.nbParticles - 1) {
  51803. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  51804. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  51805. }
  51806. else {
  51807. if (this.mesh._boundingInfo) {
  51808. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  51809. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  51810. }
  51811. }
  51812. }
  51813. // particle loop
  51814. index = this.particles[start]._pos;
  51815. var vpos = (index / 3) | 0;
  51816. colorIndex = vpos * 4;
  51817. uvIndex = vpos * 2;
  51818. for (var p = start; p <= end; p++) {
  51819. this._particle = this.particles[p];
  51820. this._shape = this._particle._model._shape;
  51821. this._shapeUV = this._particle._model._shapeUV;
  51822. // call to custom user function to update the particle properties
  51823. this.updateParticle(this._particle);
  51824. // camera-particle distance for depth sorting
  51825. if (this._depthSort && this._depthSortParticles) {
  51826. var dsp = this.depthSortedParticles[p];
  51827. dsp.ind = this._particle._ind;
  51828. dsp.indicesLength = this._particle._model._indicesLength;
  51829. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  51830. }
  51831. // skip the computations for inactive or already invisible particles
  51832. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  51833. // increment indexes for the next particle
  51834. pt = this._shape.length;
  51835. index += pt * 3;
  51836. colorIndex += pt * 4;
  51837. uvIndex += pt * 2;
  51838. continue;
  51839. }
  51840. if (this._particle.isVisible) {
  51841. this._particle._stillInvisible = false; // un-mark permanent invisibility
  51842. // particle rotation matrix
  51843. if (this.billboard) {
  51844. this._particle.rotation.x = 0.0;
  51845. this._particle.rotation.y = 0.0;
  51846. }
  51847. if (this._computeParticleRotation || this.billboard) {
  51848. if (this._particle.rotationQuaternion) {
  51849. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  51850. }
  51851. else {
  51852. this._yaw = this._particle.rotation.y;
  51853. this._pitch = this._particle.rotation.x;
  51854. this._roll = this._particle.rotation.z;
  51855. this._quaternionRotationYPR();
  51856. }
  51857. this._quaternionToRotationMatrix();
  51858. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  51859. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  51860. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  51861. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  51862. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  51863. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  51864. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  51865. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  51866. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  51867. }
  51868. if (this._particle.translateFromPivot) {
  51869. this._pivotBackTranslation.x = 0.0;
  51870. this._pivotBackTranslation.y = 0.0;
  51871. this._pivotBackTranslation.z = 0.0;
  51872. }
  51873. else {
  51874. this._pivotBackTranslation.x = this._particle.pivot.x;
  51875. this._pivotBackTranslation.y = this._particle.pivot.y;
  51876. this._pivotBackTranslation.z = this._particle.pivot.z;
  51877. }
  51878. // particle vertex loop
  51879. for (pt = 0; pt < this._shape.length; pt++) {
  51880. idx = index + pt * 3;
  51881. colidx = colorIndex + pt * 4;
  51882. uvidx = uvIndex + pt * 2;
  51883. this._vertex.x = this._shape[pt].x;
  51884. this._vertex.y = this._shape[pt].y;
  51885. this._vertex.z = this._shape[pt].z;
  51886. if (this._computeParticleVertex) {
  51887. this.updateParticleVertex(this._particle, this._vertex, pt);
  51888. }
  51889. // positions
  51890. this._vertex.x *= this._particle.scaling.x;
  51891. this._vertex.y *= this._particle.scaling.y;
  51892. this._vertex.z *= this._particle.scaling.z;
  51893. this._vertex.x -= this._particle.pivot.x;
  51894. this._vertex.y -= this._particle.pivot.y;
  51895. this._vertex.z -= this._particle.pivot.z;
  51896. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  51897. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  51898. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  51899. this._rotated.x += this._pivotBackTranslation.x;
  51900. this._rotated.y += this._pivotBackTranslation.y;
  51901. this._rotated.z += this._pivotBackTranslation.z;
  51902. this._positions32[idx] = 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;
  51903. this._positions32[idx + 1] = 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;
  51904. this._positions32[idx + 2] = 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;
  51905. if (this._computeBoundingBox) {
  51906. if (this._positions32[idx] < this._minimum.x) {
  51907. this._minimum.x = this._positions32[idx];
  51908. }
  51909. if (this._positions32[idx] > this._maximum.x) {
  51910. this._maximum.x = this._positions32[idx];
  51911. }
  51912. if (this._positions32[idx + 1] < this._minimum.y) {
  51913. this._minimum.y = this._positions32[idx + 1];
  51914. }
  51915. if (this._positions32[idx + 1] > this._maximum.y) {
  51916. this._maximum.y = this._positions32[idx + 1];
  51917. }
  51918. if (this._positions32[idx + 2] < this._minimum.z) {
  51919. this._minimum.z = this._positions32[idx + 2];
  51920. }
  51921. if (this._positions32[idx + 2] > this._maximum.z) {
  51922. this._maximum.z = this._positions32[idx + 2];
  51923. }
  51924. }
  51925. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  51926. if (!this._computeParticleVertex) {
  51927. this._normal.x = this._fixedNormal32[idx];
  51928. this._normal.y = this._fixedNormal32[idx + 1];
  51929. this._normal.z = this._fixedNormal32[idx + 2];
  51930. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  51931. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  51932. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  51933. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  51934. 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;
  51935. 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;
  51936. }
  51937. if (this._computeParticleColor && this._particle.color) {
  51938. this._colors32[colidx] = this._particle.color.r;
  51939. this._colors32[colidx + 1] = this._particle.color.g;
  51940. this._colors32[colidx + 2] = this._particle.color.b;
  51941. this._colors32[colidx + 3] = this._particle.color.a;
  51942. }
  51943. if (this._computeParticleTexture) {
  51944. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  51945. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  51946. }
  51947. }
  51948. }
  51949. else {
  51950. this._particle._stillInvisible = true; // mark the particle as invisible
  51951. for (pt = 0; pt < this._shape.length; pt++) {
  51952. idx = index + pt * 3;
  51953. colidx = colorIndex + pt * 4;
  51954. uvidx = uvIndex + pt * 2;
  51955. this._positions32[idx] = 0.0;
  51956. this._positions32[idx + 1] = 0.0;
  51957. this._positions32[idx + 2] = 0.0;
  51958. this._normals32[idx] = 0.0;
  51959. this._normals32[idx + 1] = 0.0;
  51960. this._normals32[idx + 2] = 0.0;
  51961. if (this._computeParticleColor && this._particle.color) {
  51962. this._colors32[colidx] = this._particle.color.r;
  51963. this._colors32[colidx + 1] = this._particle.color.g;
  51964. this._colors32[colidx + 2] = this._particle.color.b;
  51965. this._colors32[colidx + 3] = this._particle.color.a;
  51966. }
  51967. if (this._computeParticleTexture) {
  51968. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  51969. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  51970. }
  51971. }
  51972. }
  51973. // if the particle intersections must be computed : update the bbInfo
  51974. if (this._particlesIntersect) {
  51975. var bInfo = this._particle._boundingInfo;
  51976. var bBox = bInfo.boundingBox;
  51977. var bSphere = bInfo.boundingSphere;
  51978. if (!this._bSphereOnly) {
  51979. // place, scale and rotate the particle bbox within the SPS local system, then update it
  51980. for (var b = 0; b < bBox.vectors.length; b++) {
  51981. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  51982. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  51983. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  51984. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  51985. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  51986. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  51987. 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;
  51988. 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;
  51989. 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;
  51990. }
  51991. bBox._update(this.mesh._worldMatrix);
  51992. }
  51993. // place and scale the particle bouding sphere in the SPS local system, then update it
  51994. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  51995. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  51996. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  51997. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  51998. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  51999. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  52000. bSphere.center.x = this._particle.position.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  52001. bSphere.center.y = this._particle.position.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  52002. bSphere.center.z = this._particle.position.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  52003. 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));
  52004. bSphere._update(this.mesh._worldMatrix);
  52005. }
  52006. // increment indexes for the next particle
  52007. index = idx + 3;
  52008. colorIndex = colidx + 4;
  52009. uvIndex = uvidx + 2;
  52010. }
  52011. // if the VBO must be updated
  52012. if (update) {
  52013. if (this._computeParticleColor) {
  52014. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  52015. }
  52016. if (this._computeParticleTexture) {
  52017. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  52018. }
  52019. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  52020. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  52021. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  52022. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  52023. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  52024. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  52025. for (var i = 0; i < this._normals32.length; i++) {
  52026. this._fixedNormal32[i] = this._normals32[i];
  52027. }
  52028. }
  52029. if (!this.mesh.areNormalsFrozen) {
  52030. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  52031. }
  52032. }
  52033. if (this._depthSort && this._depthSortParticles) {
  52034. this.depthSortedParticles.sort(this._depthSortFunction);
  52035. var dspl = this.depthSortedParticles.length;
  52036. var sorted = 0;
  52037. var lind = 0;
  52038. var sind = 0;
  52039. var sid = 0;
  52040. for (sorted = 0; sorted < dspl; sorted++) {
  52041. lind = this.depthSortedParticles[sorted].indicesLength;
  52042. sind = this.depthSortedParticles[sorted].ind;
  52043. for (var i = 0; i < lind; i++) {
  52044. this._indices32[sid] = this._indices[sind + i];
  52045. sid++;
  52046. }
  52047. }
  52048. this.mesh.updateIndices(this._indices32);
  52049. }
  52050. }
  52051. if (this._computeBoundingBox) {
  52052. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  52053. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  52054. }
  52055. this.afterUpdateParticles(start, end, update);
  52056. return this;
  52057. };
  52058. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  52059. this._halfroll = this._roll * 0.5;
  52060. this._halfpitch = this._pitch * 0.5;
  52061. this._halfyaw = this._yaw * 0.5;
  52062. this._sinRoll = Math.sin(this._halfroll);
  52063. this._cosRoll = Math.cos(this._halfroll);
  52064. this._sinPitch = Math.sin(this._halfpitch);
  52065. this._cosPitch = Math.cos(this._halfpitch);
  52066. this._sinYaw = Math.sin(this._halfyaw);
  52067. this._cosYaw = Math.cos(this._halfyaw);
  52068. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  52069. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  52070. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  52071. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  52072. };
  52073. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  52074. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  52075. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  52076. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  52077. this._rotMatrix.m[3] = 0;
  52078. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  52079. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  52080. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  52081. this._rotMatrix.m[7] = 0;
  52082. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  52083. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  52084. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  52085. this._rotMatrix.m[11] = 0;
  52086. this._rotMatrix.m[12] = 0;
  52087. this._rotMatrix.m[13] = 0;
  52088. this._rotMatrix.m[14] = 0;
  52089. this._rotMatrix.m[15] = 1.0;
  52090. };
  52091. /**
  52092. * Disposes the SPS.
  52093. */
  52094. SolidParticleSystem.prototype.dispose = function () {
  52095. this.mesh.dispose();
  52096. this.vars = null;
  52097. // drop references to internal big arrays for the GC
  52098. this._positions = null;
  52099. this._indices = null;
  52100. this._normals = null;
  52101. this._uvs = null;
  52102. this._colors = null;
  52103. this._indices32 = null;
  52104. this._positions32 = null;
  52105. this._normals32 = null;
  52106. this._fixedNormal32 = null;
  52107. this._uvs32 = null;
  52108. this._colors32 = null;
  52109. this.pickedParticles = null;
  52110. };
  52111. /**
  52112. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  52113. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  52114. * @returns the SPS.
  52115. */
  52116. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  52117. if (!this._isVisibilityBoxLocked) {
  52118. this.mesh.refreshBoundingInfo();
  52119. }
  52120. return this;
  52121. };
  52122. /**
  52123. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  52124. * @param size the size (float) of the visibility box
  52125. * note : this doesn't lock the SPS mesh bounding box.
  52126. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  52127. */
  52128. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  52129. var vis = size / 2;
  52130. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  52131. };
  52132. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  52133. /**
  52134. * Gets whether the SPS as always visible or not
  52135. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  52136. */
  52137. get: function () {
  52138. return this._alwaysVisible;
  52139. },
  52140. /**
  52141. * Sets the SPS as always visible or not
  52142. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  52143. */
  52144. set: function (val) {
  52145. this._alwaysVisible = val;
  52146. this.mesh.alwaysSelectAsActiveMesh = val;
  52147. },
  52148. enumerable: true,
  52149. configurable: true
  52150. });
  52151. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  52152. /**
  52153. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  52154. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  52155. */
  52156. get: function () {
  52157. return this._isVisibilityBoxLocked;
  52158. },
  52159. /**
  52160. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  52161. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  52162. */
  52163. set: function (val) {
  52164. this._isVisibilityBoxLocked = val;
  52165. var boundingInfo = this.mesh.getBoundingInfo();
  52166. boundingInfo.isLocked = val;
  52167. },
  52168. enumerable: true,
  52169. configurable: true
  52170. });
  52171. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  52172. /**
  52173. * Gets if `setParticles()` computes the particle rotations or not.
  52174. * Default value : true. The SPS is faster when it's set to false.
  52175. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  52176. */
  52177. get: function () {
  52178. return this._computeParticleRotation;
  52179. },
  52180. /**
  52181. * Tells to `setParticles()` to compute the particle rotations or not.
  52182. * Default value : true. The SPS is faster when it's set to false.
  52183. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  52184. */
  52185. set: function (val) {
  52186. this._computeParticleRotation = val;
  52187. },
  52188. enumerable: true,
  52189. configurable: true
  52190. });
  52191. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  52192. /**
  52193. * Gets if `setParticles()` computes the particle colors or not.
  52194. * Default value : true. The SPS is faster when it's set to false.
  52195. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  52196. */
  52197. get: function () {
  52198. return this._computeParticleColor;
  52199. },
  52200. /**
  52201. * Tells to `setParticles()` to compute the particle colors or not.
  52202. * Default value : true. The SPS is faster when it's set to false.
  52203. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  52204. */
  52205. set: function (val) {
  52206. this._computeParticleColor = val;
  52207. },
  52208. enumerable: true,
  52209. configurable: true
  52210. });
  52211. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  52212. /**
  52213. * Gets if `setParticles()` computes the particle textures or not.
  52214. * Default value : true. The SPS is faster when it's set to false.
  52215. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  52216. */
  52217. get: function () {
  52218. return this._computeParticleTexture;
  52219. },
  52220. set: function (val) {
  52221. this._computeParticleTexture = val;
  52222. },
  52223. enumerable: true,
  52224. configurable: true
  52225. });
  52226. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  52227. /**
  52228. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  52229. * Default value : false. The SPS is faster when it's set to false.
  52230. * Note : the particle custom vertex positions aren't stored values.
  52231. */
  52232. get: function () {
  52233. return this._computeParticleVertex;
  52234. },
  52235. /**
  52236. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  52237. * Default value : false. The SPS is faster when it's set to false.
  52238. * Note : the particle custom vertex positions aren't stored values.
  52239. */
  52240. set: function (val) {
  52241. this._computeParticleVertex = val;
  52242. },
  52243. enumerable: true,
  52244. configurable: true
  52245. });
  52246. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  52247. /**
  52248. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  52249. */
  52250. get: function () {
  52251. return this._computeBoundingBox;
  52252. },
  52253. /**
  52254. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  52255. */
  52256. set: function (val) {
  52257. this._computeBoundingBox = val;
  52258. },
  52259. enumerable: true,
  52260. configurable: true
  52261. });
  52262. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  52263. /**
  52264. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  52265. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  52266. * Default : `true`
  52267. */
  52268. get: function () {
  52269. return this._depthSortParticles;
  52270. },
  52271. /**
  52272. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  52273. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  52274. * Default : `true`
  52275. */
  52276. set: function (val) {
  52277. this._depthSortParticles = val;
  52278. },
  52279. enumerable: true,
  52280. configurable: true
  52281. });
  52282. // =======================================================================
  52283. // Particle behavior logic
  52284. // these following methods may be overwritten by the user to fit his needs
  52285. /**
  52286. * This function does nothing. It may be overwritten to set all the particle first values.
  52287. * The SPS doesn't call this function, you may have to call it by your own.
  52288. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  52289. */
  52290. SolidParticleSystem.prototype.initParticles = function () {
  52291. };
  52292. /**
  52293. * This function does nothing. It may be overwritten to recycle a particle.
  52294. * The SPS doesn't call this function, you may have to call it by your own.
  52295. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  52296. * @param particle The particle to recycle
  52297. * @returns the recycled particle
  52298. */
  52299. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  52300. return particle;
  52301. };
  52302. /**
  52303. * Updates a particle : this function should be overwritten by the user.
  52304. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  52305. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  52306. * @example : just set a particle position or velocity and recycle conditions
  52307. * @param particle The particle to update
  52308. * @returns the updated particle
  52309. */
  52310. SolidParticleSystem.prototype.updateParticle = function (particle) {
  52311. return particle;
  52312. };
  52313. /**
  52314. * Updates a vertex of a particle : it can be overwritten by the user.
  52315. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  52316. * @param particle the current particle
  52317. * @param vertex the current index of the current particle
  52318. * @param pt the index of the current vertex in the particle shape
  52319. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  52320. * @example : just set a vertex particle position
  52321. * @returns the updated vertex
  52322. */
  52323. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  52324. return vertex;
  52325. };
  52326. /**
  52327. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  52328. * This does nothing and may be overwritten by the user.
  52329. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  52330. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  52331. * @param update the boolean update value actually passed to setParticles()
  52332. */
  52333. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  52334. };
  52335. /**
  52336. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  52337. * This will be passed three parameters.
  52338. * This does nothing and may be overwritten by the user.
  52339. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  52340. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  52341. * @param update the boolean update value actually passed to setParticles()
  52342. */
  52343. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  52344. };
  52345. return SolidParticleSystem;
  52346. }());
  52347. BABYLON.SolidParticleSystem = SolidParticleSystem;
  52348. })(BABYLON || (BABYLON = {}));
  52349. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  52350. var BABYLON;
  52351. (function (BABYLON) {
  52352. var ShaderMaterial = /** @class */ (function (_super) {
  52353. __extends(ShaderMaterial, _super);
  52354. function ShaderMaterial(name, scene, shaderPath, options) {
  52355. var _this = _super.call(this, name, scene) || this;
  52356. _this._textures = {};
  52357. _this._textureArrays = {};
  52358. _this._floats = {};
  52359. _this._ints = {};
  52360. _this._floatsArrays = {};
  52361. _this._colors3 = {};
  52362. _this._colors3Arrays = {};
  52363. _this._colors4 = {};
  52364. _this._vectors2 = {};
  52365. _this._vectors3 = {};
  52366. _this._vectors4 = {};
  52367. _this._matrices = {};
  52368. _this._matrices3x3 = {};
  52369. _this._matrices2x2 = {};
  52370. _this._vectors2Arrays = {};
  52371. _this._vectors3Arrays = {};
  52372. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  52373. _this._shaderPath = shaderPath;
  52374. options.needAlphaBlending = options.needAlphaBlending || false;
  52375. options.needAlphaTesting = options.needAlphaTesting || false;
  52376. options.attributes = options.attributes || ["position", "normal", "uv"];
  52377. options.uniforms = options.uniforms || ["worldViewProjection"];
  52378. options.uniformBuffers = options.uniformBuffers || [];
  52379. options.samplers = options.samplers || [];
  52380. options.defines = options.defines || [];
  52381. _this._options = options;
  52382. return _this;
  52383. }
  52384. ShaderMaterial.prototype.getClassName = function () {
  52385. return "ShaderMaterial";
  52386. };
  52387. ShaderMaterial.prototype.needAlphaBlending = function () {
  52388. return this._options.needAlphaBlending;
  52389. };
  52390. ShaderMaterial.prototype.needAlphaTesting = function () {
  52391. return this._options.needAlphaTesting;
  52392. };
  52393. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  52394. if (this._options.uniforms.indexOf(uniformName) === -1) {
  52395. this._options.uniforms.push(uniformName);
  52396. }
  52397. };
  52398. ShaderMaterial.prototype.setTexture = function (name, texture) {
  52399. if (this._options.samplers.indexOf(name) === -1) {
  52400. this._options.samplers.push(name);
  52401. }
  52402. this._textures[name] = texture;
  52403. return this;
  52404. };
  52405. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  52406. if (this._options.samplers.indexOf(name) === -1) {
  52407. this._options.samplers.push(name);
  52408. }
  52409. this._checkUniform(name);
  52410. this._textureArrays[name] = textures;
  52411. return this;
  52412. };
  52413. ShaderMaterial.prototype.setFloat = function (name, value) {
  52414. this._checkUniform(name);
  52415. this._floats[name] = value;
  52416. return this;
  52417. };
  52418. ShaderMaterial.prototype.setInt = function (name, value) {
  52419. this._checkUniform(name);
  52420. this._ints[name] = value;
  52421. return this;
  52422. };
  52423. ShaderMaterial.prototype.setFloats = function (name, value) {
  52424. this._checkUniform(name);
  52425. this._floatsArrays[name] = value;
  52426. return this;
  52427. };
  52428. ShaderMaterial.prototype.setColor3 = function (name, value) {
  52429. this._checkUniform(name);
  52430. this._colors3[name] = value;
  52431. return this;
  52432. };
  52433. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  52434. this._checkUniform(name);
  52435. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  52436. color.toArray(arr, arr.length);
  52437. return arr;
  52438. }, []);
  52439. return this;
  52440. };
  52441. ShaderMaterial.prototype.setColor4 = function (name, value) {
  52442. this._checkUniform(name);
  52443. this._colors4[name] = value;
  52444. return this;
  52445. };
  52446. ShaderMaterial.prototype.setVector2 = function (name, value) {
  52447. this._checkUniform(name);
  52448. this._vectors2[name] = value;
  52449. return this;
  52450. };
  52451. ShaderMaterial.prototype.setVector3 = function (name, value) {
  52452. this._checkUniform(name);
  52453. this._vectors3[name] = value;
  52454. return this;
  52455. };
  52456. ShaderMaterial.prototype.setVector4 = function (name, value) {
  52457. this._checkUniform(name);
  52458. this._vectors4[name] = value;
  52459. return this;
  52460. };
  52461. ShaderMaterial.prototype.setMatrix = function (name, value) {
  52462. this._checkUniform(name);
  52463. this._matrices[name] = value;
  52464. return this;
  52465. };
  52466. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  52467. this._checkUniform(name);
  52468. this._matrices3x3[name] = value;
  52469. return this;
  52470. };
  52471. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  52472. this._checkUniform(name);
  52473. this._matrices2x2[name] = value;
  52474. return this;
  52475. };
  52476. ShaderMaterial.prototype.setArray2 = function (name, value) {
  52477. this._checkUniform(name);
  52478. this._vectors2Arrays[name] = value;
  52479. return this;
  52480. };
  52481. ShaderMaterial.prototype.setArray3 = function (name, value) {
  52482. this._checkUniform(name);
  52483. this._vectors3Arrays[name] = value;
  52484. return this;
  52485. };
  52486. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  52487. if (!mesh) {
  52488. return true;
  52489. }
  52490. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  52491. return false;
  52492. }
  52493. return false;
  52494. };
  52495. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  52496. var scene = this.getScene();
  52497. var engine = scene.getEngine();
  52498. if (!this.checkReadyOnEveryCall) {
  52499. if (this._renderId === scene.getRenderId()) {
  52500. if (this._checkCache(scene, mesh, useInstances)) {
  52501. return true;
  52502. }
  52503. }
  52504. }
  52505. // Instances
  52506. var defines = [];
  52507. var attribs = [];
  52508. var fallbacks = new BABYLON.EffectFallbacks();
  52509. if (useInstances) {
  52510. defines.push("#define INSTANCES");
  52511. }
  52512. for (var index = 0; index < this._options.defines.length; index++) {
  52513. defines.push(this._options.defines[index]);
  52514. }
  52515. for (var index = 0; index < this._options.attributes.length; index++) {
  52516. attribs.push(this._options.attributes[index]);
  52517. }
  52518. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  52519. attribs.push(BABYLON.VertexBuffer.ColorKind);
  52520. defines.push("#define VERTEXCOLOR");
  52521. }
  52522. // Bones
  52523. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  52524. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  52525. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  52526. if (mesh.numBoneInfluencers > 4) {
  52527. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  52528. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  52529. }
  52530. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  52531. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  52532. fallbacks.addCPUSkinningFallback(0, mesh);
  52533. if (this._options.uniforms.indexOf("mBones") === -1) {
  52534. this._options.uniforms.push("mBones");
  52535. }
  52536. }
  52537. else {
  52538. defines.push("#define NUM_BONE_INFLUENCERS 0");
  52539. }
  52540. // Textures
  52541. for (var name in this._textures) {
  52542. if (!this._textures[name].isReady()) {
  52543. return false;
  52544. }
  52545. }
  52546. // Alpha test
  52547. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  52548. defines.push("#define ALPHATEST");
  52549. }
  52550. var previousEffect = this._effect;
  52551. var join = defines.join("\n");
  52552. this._effect = engine.createEffect(this._shaderPath, {
  52553. attributes: attribs,
  52554. uniformsNames: this._options.uniforms,
  52555. uniformBuffersNames: this._options.uniformBuffers,
  52556. samplers: this._options.samplers,
  52557. defines: join,
  52558. fallbacks: fallbacks,
  52559. onCompiled: this.onCompiled,
  52560. onError: this.onError
  52561. }, engine);
  52562. if (!this._effect.isReady()) {
  52563. return false;
  52564. }
  52565. if (previousEffect !== this._effect) {
  52566. scene.resetCachedMaterial();
  52567. }
  52568. this._renderId = scene.getRenderId();
  52569. return true;
  52570. };
  52571. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  52572. var scene = this.getScene();
  52573. if (!this._effect) {
  52574. return;
  52575. }
  52576. if (this._options.uniforms.indexOf("world") !== -1) {
  52577. this._effect.setMatrix("world", world);
  52578. }
  52579. if (this._options.uniforms.indexOf("worldView") !== -1) {
  52580. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  52581. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  52582. }
  52583. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  52584. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  52585. }
  52586. };
  52587. ShaderMaterial.prototype.bind = function (world, mesh) {
  52588. // Std values
  52589. this.bindOnlyWorldMatrix(world);
  52590. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  52591. if (this._options.uniforms.indexOf("view") !== -1) {
  52592. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  52593. }
  52594. if (this._options.uniforms.indexOf("projection") !== -1) {
  52595. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  52596. }
  52597. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  52598. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  52599. }
  52600. // Bones
  52601. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  52602. var name;
  52603. // Texture
  52604. for (name in this._textures) {
  52605. this._effect.setTexture(name, this._textures[name]);
  52606. }
  52607. // Texture arrays
  52608. for (name in this._textureArrays) {
  52609. this._effect.setTextureArray(name, this._textureArrays[name]);
  52610. }
  52611. // Int
  52612. for (name in this._ints) {
  52613. this._effect.setInt(name, this._ints[name]);
  52614. }
  52615. // Float
  52616. for (name in this._floats) {
  52617. this._effect.setFloat(name, this._floats[name]);
  52618. }
  52619. // Floats
  52620. for (name in this._floatsArrays) {
  52621. this._effect.setArray(name, this._floatsArrays[name]);
  52622. }
  52623. // Color3
  52624. for (name in this._colors3) {
  52625. this._effect.setColor3(name, this._colors3[name]);
  52626. }
  52627. for (name in this._colors3Arrays) {
  52628. this._effect.setArray3(name, this._colors3Arrays[name]);
  52629. }
  52630. // Color4
  52631. for (name in this._colors4) {
  52632. var color = this._colors4[name];
  52633. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  52634. }
  52635. // Vector2
  52636. for (name in this._vectors2) {
  52637. this._effect.setVector2(name, this._vectors2[name]);
  52638. }
  52639. // Vector3
  52640. for (name in this._vectors3) {
  52641. this._effect.setVector3(name, this._vectors3[name]);
  52642. }
  52643. // Vector4
  52644. for (name in this._vectors4) {
  52645. this._effect.setVector4(name, this._vectors4[name]);
  52646. }
  52647. // Matrix
  52648. for (name in this._matrices) {
  52649. this._effect.setMatrix(name, this._matrices[name]);
  52650. }
  52651. // Matrix 3x3
  52652. for (name in this._matrices3x3) {
  52653. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  52654. }
  52655. // Matrix 2x2
  52656. for (name in this._matrices2x2) {
  52657. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  52658. }
  52659. // Vector2Array
  52660. for (name in this._vectors2Arrays) {
  52661. this._effect.setArray2(name, this._vectors2Arrays[name]);
  52662. }
  52663. // Vector3Array
  52664. for (name in this._vectors3Arrays) {
  52665. this._effect.setArray3(name, this._vectors3Arrays[name]);
  52666. }
  52667. }
  52668. this._afterBind(mesh);
  52669. };
  52670. ShaderMaterial.prototype.getActiveTextures = function () {
  52671. var activeTextures = _super.prototype.getActiveTextures.call(this);
  52672. for (var name in this._textures) {
  52673. activeTextures.push(this._textures[name]);
  52674. }
  52675. for (var name in this._textureArrays) {
  52676. var array = this._textureArrays[name];
  52677. for (var index = 0; index < array.length; index++) {
  52678. activeTextures.push(array[index]);
  52679. }
  52680. }
  52681. return activeTextures;
  52682. };
  52683. ShaderMaterial.prototype.hasTexture = function (texture) {
  52684. if (_super.prototype.hasTexture.call(this, texture)) {
  52685. return true;
  52686. }
  52687. for (var name in this._textures) {
  52688. if (this._textures[name] === texture) {
  52689. return true;
  52690. }
  52691. }
  52692. for (var name in this._textureArrays) {
  52693. var array = this._textureArrays[name];
  52694. for (var index = 0; index < array.length; index++) {
  52695. if (array[index] === texture) {
  52696. return true;
  52697. }
  52698. }
  52699. }
  52700. return false;
  52701. };
  52702. ShaderMaterial.prototype.clone = function (name) {
  52703. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  52704. return newShaderMaterial;
  52705. };
  52706. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  52707. if (forceDisposeTextures) {
  52708. var name;
  52709. for (name in this._textures) {
  52710. this._textures[name].dispose();
  52711. }
  52712. for (name in this._textureArrays) {
  52713. var array = this._textureArrays[name];
  52714. for (var index = 0; index < array.length; index++) {
  52715. array[index].dispose();
  52716. }
  52717. }
  52718. }
  52719. this._textures = {};
  52720. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  52721. };
  52722. ShaderMaterial.prototype.serialize = function () {
  52723. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  52724. serializationObject.customType = "BABYLON.ShaderMaterial";
  52725. serializationObject.options = this._options;
  52726. serializationObject.shaderPath = this._shaderPath;
  52727. var name;
  52728. // Texture
  52729. serializationObject.textures = {};
  52730. for (name in this._textures) {
  52731. serializationObject.textures[name] = this._textures[name].serialize();
  52732. }
  52733. // Texture arrays
  52734. serializationObject.textureArrays = {};
  52735. for (name in this._textureArrays) {
  52736. serializationObject.textureArrays[name] = [];
  52737. var array = this._textureArrays[name];
  52738. for (var index = 0; index < array.length; index++) {
  52739. serializationObject.textureArrays[name].push(array[index].serialize());
  52740. }
  52741. }
  52742. // Float
  52743. serializationObject.floats = {};
  52744. for (name in this._floats) {
  52745. serializationObject.floats[name] = this._floats[name];
  52746. }
  52747. // Float s
  52748. serializationObject.FloatArrays = {};
  52749. for (name in this._floatsArrays) {
  52750. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  52751. }
  52752. // Color3
  52753. serializationObject.colors3 = {};
  52754. for (name in this._colors3) {
  52755. serializationObject.colors3[name] = this._colors3[name].asArray();
  52756. }
  52757. // Color3 array
  52758. serializationObject.colors3Arrays = {};
  52759. for (name in this._colors3Arrays) {
  52760. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  52761. }
  52762. // Color4
  52763. serializationObject.colors4 = {};
  52764. for (name in this._colors4) {
  52765. serializationObject.colors4[name] = this._colors4[name].asArray();
  52766. }
  52767. // Vector2
  52768. serializationObject.vectors2 = {};
  52769. for (name in this._vectors2) {
  52770. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  52771. }
  52772. // Vector3
  52773. serializationObject.vectors3 = {};
  52774. for (name in this._vectors3) {
  52775. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  52776. }
  52777. // Vector4
  52778. serializationObject.vectors4 = {};
  52779. for (name in this._vectors4) {
  52780. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  52781. }
  52782. // Matrix
  52783. serializationObject.matrices = {};
  52784. for (name in this._matrices) {
  52785. serializationObject.matrices[name] = this._matrices[name].asArray();
  52786. }
  52787. // Matrix 3x3
  52788. serializationObject.matrices3x3 = {};
  52789. for (name in this._matrices3x3) {
  52790. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  52791. }
  52792. // Matrix 2x2
  52793. serializationObject.matrices2x2 = {};
  52794. for (name in this._matrices2x2) {
  52795. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  52796. }
  52797. // Vector2Array
  52798. serializationObject.vectors2Arrays = {};
  52799. for (name in this._vectors2Arrays) {
  52800. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  52801. }
  52802. // Vector3Array
  52803. serializationObject.vectors3Arrays = {};
  52804. for (name in this._vectors3Arrays) {
  52805. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  52806. }
  52807. return serializationObject;
  52808. };
  52809. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  52810. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  52811. var name;
  52812. // Texture
  52813. for (name in source.textures) {
  52814. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  52815. }
  52816. // Texture arrays
  52817. for (name in source.textureArrays) {
  52818. var array = source.textureArrays[name];
  52819. var textureArray = new Array();
  52820. for (var index = 0; index < array.length; index++) {
  52821. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  52822. }
  52823. material.setTextureArray(name, textureArray);
  52824. }
  52825. // Float
  52826. for (name in source.floats) {
  52827. material.setFloat(name, source.floats[name]);
  52828. }
  52829. // Float s
  52830. for (name in source.floatsArrays) {
  52831. material.setFloats(name, source.floatsArrays[name]);
  52832. }
  52833. // Color3
  52834. for (name in source.colors3) {
  52835. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  52836. }
  52837. // Color3 arrays
  52838. for (name in source.colors3Arrays) {
  52839. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  52840. if (i % 3 === 0) {
  52841. arr.push([num]);
  52842. }
  52843. else {
  52844. arr[arr.length - 1].push(num);
  52845. }
  52846. return arr;
  52847. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  52848. material.setColor3Array(name, colors);
  52849. }
  52850. // Color4
  52851. for (name in source.colors4) {
  52852. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  52853. }
  52854. // Vector2
  52855. for (name in source.vectors2) {
  52856. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  52857. }
  52858. // Vector3
  52859. for (name in source.vectors3) {
  52860. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  52861. }
  52862. // Vector4
  52863. for (name in source.vectors4) {
  52864. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  52865. }
  52866. // Matrix
  52867. for (name in source.matrices) {
  52868. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  52869. }
  52870. // Matrix 3x3
  52871. for (name in source.matrices3x3) {
  52872. material.setMatrix3x3(name, source.matrices3x3[name]);
  52873. }
  52874. // Matrix 2x2
  52875. for (name in source.matrices2x2) {
  52876. material.setMatrix2x2(name, source.matrices2x2[name]);
  52877. }
  52878. // Vector2Array
  52879. for (name in source.vectors2Arrays) {
  52880. material.setArray2(name, source.vectors2Arrays[name]);
  52881. }
  52882. // Vector3Array
  52883. for (name in source.vectors3Arrays) {
  52884. material.setArray3(name, source.vectors3Arrays[name]);
  52885. }
  52886. return material;
  52887. };
  52888. return ShaderMaterial;
  52889. }(BABYLON.Material));
  52890. BABYLON.ShaderMaterial = ShaderMaterial;
  52891. })(BABYLON || (BABYLON = {}));
  52892. //# sourceMappingURL=babylon.shaderMaterial.js.map
  52893. var BABYLON;
  52894. (function (BABYLON) {
  52895. var GroundMesh = /** @class */ (function (_super) {
  52896. __extends(GroundMesh, _super);
  52897. function GroundMesh(name, scene) {
  52898. var _this = _super.call(this, name, scene) || this;
  52899. _this.generateOctree = false;
  52900. return _this;
  52901. }
  52902. GroundMesh.prototype.getClassName = function () {
  52903. return "GroundMesh";
  52904. };
  52905. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  52906. get: function () {
  52907. return Math.min(this._subdivisionsX, this._subdivisionsY);
  52908. },
  52909. enumerable: true,
  52910. configurable: true
  52911. });
  52912. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  52913. get: function () {
  52914. return this._subdivisionsX;
  52915. },
  52916. enumerable: true,
  52917. configurable: true
  52918. });
  52919. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  52920. get: function () {
  52921. return this._subdivisionsY;
  52922. },
  52923. enumerable: true,
  52924. configurable: true
  52925. });
  52926. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  52927. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  52928. this._subdivisionsX = chunksCount;
  52929. this._subdivisionsY = chunksCount;
  52930. this.subdivide(chunksCount);
  52931. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  52932. };
  52933. /**
  52934. * Returns a height (y) value in the Worl system :
  52935. * the ground altitude at the coordinates (x, z) expressed in the World system.
  52936. * Returns the ground y position if (x, z) are outside the ground surface.
  52937. */
  52938. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  52939. var world = this.getWorldMatrix();
  52940. var invMat = BABYLON.Tmp.Matrix[5];
  52941. world.invertToRef(invMat);
  52942. var tmpVect = BABYLON.Tmp.Vector3[8];
  52943. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  52944. x = tmpVect.x;
  52945. z = tmpVect.z;
  52946. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  52947. return this.position.y;
  52948. }
  52949. if (!this._heightQuads || this._heightQuads.length == 0) {
  52950. this._initHeightQuads();
  52951. this._computeHeightQuads();
  52952. }
  52953. var facet = this._getFacetAt(x, z);
  52954. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  52955. // return y in the World system
  52956. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  52957. return tmpVect.y;
  52958. };
  52959. /**
  52960. * Returns a normalized vector (Vector3) orthogonal to the ground
  52961. * at the ground coordinates (x, z) expressed in the World system.
  52962. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  52963. */
  52964. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  52965. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  52966. this.getNormalAtCoordinatesToRef(x, z, normal);
  52967. return normal;
  52968. };
  52969. /**
  52970. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  52971. * at the ground coordinates (x, z) expressed in the World system.
  52972. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  52973. * Returns the GroundMesh.
  52974. */
  52975. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  52976. var world = this.getWorldMatrix();
  52977. var tmpMat = BABYLON.Tmp.Matrix[5];
  52978. world.invertToRef(tmpMat);
  52979. var tmpVect = BABYLON.Tmp.Vector3[8];
  52980. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  52981. x = tmpVect.x;
  52982. z = tmpVect.z;
  52983. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  52984. return this;
  52985. }
  52986. if (!this._heightQuads || this._heightQuads.length == 0) {
  52987. this._initHeightQuads();
  52988. this._computeHeightQuads();
  52989. }
  52990. var facet = this._getFacetAt(x, z);
  52991. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  52992. return this;
  52993. };
  52994. /**
  52995. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  52996. * if the ground has been updated.
  52997. * This can be used in the render loop.
  52998. * Returns the GroundMesh.
  52999. */
  53000. GroundMesh.prototype.updateCoordinateHeights = function () {
  53001. if (!this._heightQuads || this._heightQuads.length == 0) {
  53002. this._initHeightQuads();
  53003. }
  53004. this._computeHeightQuads();
  53005. return this;
  53006. };
  53007. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  53008. GroundMesh.prototype._getFacetAt = function (x, z) {
  53009. // retrieve col and row from x, z coordinates in the ground local system
  53010. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  53011. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  53012. var quad = this._heightQuads[row * this._subdivisionsX + col];
  53013. var facet;
  53014. if (z < quad.slope.x * x + quad.slope.y) {
  53015. facet = quad.facet1;
  53016. }
  53017. else {
  53018. facet = quad.facet2;
  53019. }
  53020. return facet;
  53021. };
  53022. // Creates and populates the heightMap array with "facet" elements :
  53023. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  53024. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  53025. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  53026. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  53027. // Returns the GroundMesh.
  53028. GroundMesh.prototype._initHeightQuads = function () {
  53029. var subdivisionsX = this._subdivisionsX;
  53030. var subdivisionsY = this._subdivisionsY;
  53031. this._heightQuads = new Array();
  53032. for (var row = 0; row < subdivisionsY; row++) {
  53033. for (var col = 0; col < subdivisionsX; col++) {
  53034. 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) };
  53035. this._heightQuads[row * subdivisionsX + col] = quad;
  53036. }
  53037. }
  53038. return this;
  53039. };
  53040. // Compute each quad element values and update the the heightMap array :
  53041. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  53042. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  53043. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  53044. // Returns the GroundMesh.
  53045. GroundMesh.prototype._computeHeightQuads = function () {
  53046. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  53047. if (!positions) {
  53048. return this;
  53049. }
  53050. var v1 = BABYLON.Tmp.Vector3[3];
  53051. var v2 = BABYLON.Tmp.Vector3[2];
  53052. var v3 = BABYLON.Tmp.Vector3[1];
  53053. var v4 = BABYLON.Tmp.Vector3[0];
  53054. var v1v2 = BABYLON.Tmp.Vector3[4];
  53055. var v1v3 = BABYLON.Tmp.Vector3[5];
  53056. var v1v4 = BABYLON.Tmp.Vector3[6];
  53057. var norm1 = BABYLON.Tmp.Vector3[7];
  53058. var norm2 = BABYLON.Tmp.Vector3[8];
  53059. var i = 0;
  53060. var j = 0;
  53061. var k = 0;
  53062. var cd = 0; // 2D slope coefficient : z = cd * x + h
  53063. var h = 0;
  53064. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  53065. var d2 = 0;
  53066. var subdivisionsX = this._subdivisionsX;
  53067. var subdivisionsY = this._subdivisionsY;
  53068. for (var row = 0; row < subdivisionsY; row++) {
  53069. for (var col = 0; col < subdivisionsX; col++) {
  53070. i = col * 3;
  53071. j = row * (subdivisionsX + 1) * 3;
  53072. k = (row + 1) * (subdivisionsX + 1) * 3;
  53073. v1.x = positions[j + i];
  53074. v1.y = positions[j + i + 1];
  53075. v1.z = positions[j + i + 2];
  53076. v2.x = positions[j + i + 3];
  53077. v2.y = positions[j + i + 4];
  53078. v2.z = positions[j + i + 5];
  53079. v3.x = positions[k + i];
  53080. v3.y = positions[k + i + 1];
  53081. v3.z = positions[k + i + 2];
  53082. v4.x = positions[k + i + 3];
  53083. v4.y = positions[k + i + 4];
  53084. v4.z = positions[k + i + 5];
  53085. // 2D slope V1V4
  53086. cd = (v4.z - v1.z) / (v4.x - v1.x);
  53087. h = v1.z - cd * v1.x; // v1 belongs to the slope
  53088. // facet equations :
  53089. // we compute each facet normal vector
  53090. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  53091. // we compute the value d by applying the equation to v1 which belongs to the plane
  53092. // then we store the facet equation in a Vector4
  53093. v2.subtractToRef(v1, v1v2);
  53094. v3.subtractToRef(v1, v1v3);
  53095. v4.subtractToRef(v1, v1v4);
  53096. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  53097. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  53098. norm1.normalize();
  53099. norm2.normalize();
  53100. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  53101. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  53102. var quad = this._heightQuads[row * subdivisionsX + col];
  53103. quad.slope.copyFromFloats(cd, h);
  53104. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  53105. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  53106. }
  53107. }
  53108. return this;
  53109. };
  53110. GroundMesh.prototype.serialize = function (serializationObject) {
  53111. _super.prototype.serialize.call(this, serializationObject);
  53112. serializationObject.subdivisionsX = this._subdivisionsX;
  53113. serializationObject.subdivisionsY = this._subdivisionsY;
  53114. serializationObject.minX = this._minX;
  53115. serializationObject.maxX = this._maxX;
  53116. serializationObject.minZ = this._minZ;
  53117. serializationObject.maxZ = this._maxZ;
  53118. serializationObject.width = this._width;
  53119. serializationObject.height = this._height;
  53120. };
  53121. GroundMesh.Parse = function (parsedMesh, scene) {
  53122. var result = new GroundMesh(parsedMesh.name, scene);
  53123. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  53124. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  53125. result._minX = parsedMesh.minX;
  53126. result._maxX = parsedMesh.maxX;
  53127. result._minZ = parsedMesh.minZ;
  53128. result._maxZ = parsedMesh.maxZ;
  53129. result._width = parsedMesh.width;
  53130. result._height = parsedMesh.height;
  53131. return result;
  53132. };
  53133. return GroundMesh;
  53134. }(BABYLON.Mesh));
  53135. BABYLON.GroundMesh = GroundMesh;
  53136. })(BABYLON || (BABYLON = {}));
  53137. //# sourceMappingURL=babylon.groundMesh.js.map
  53138. var BABYLON;
  53139. (function (BABYLON) {
  53140. /**
  53141. * Creates an instance based on a source mesh.
  53142. */
  53143. var InstancedMesh = /** @class */ (function (_super) {
  53144. __extends(InstancedMesh, _super);
  53145. function InstancedMesh(name, source) {
  53146. var _this = _super.call(this, name, source.getScene()) || this;
  53147. source.instances.push(_this);
  53148. _this._sourceMesh = source;
  53149. _this.position.copyFrom(source.position);
  53150. _this.rotation.copyFrom(source.rotation);
  53151. _this.scaling.copyFrom(source.scaling);
  53152. if (source.rotationQuaternion) {
  53153. _this.rotationQuaternion = source.rotationQuaternion.clone();
  53154. }
  53155. _this.infiniteDistance = source.infiniteDistance;
  53156. _this.setPivotMatrix(source.getPivotMatrix());
  53157. _this.refreshBoundingInfo();
  53158. _this._syncSubMeshes();
  53159. return _this;
  53160. }
  53161. /**
  53162. * Returns the string "InstancedMesh".
  53163. */
  53164. InstancedMesh.prototype.getClassName = function () {
  53165. return "InstancedMesh";
  53166. };
  53167. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  53168. // Methods
  53169. get: function () {
  53170. return this._sourceMesh.receiveShadows;
  53171. },
  53172. enumerable: true,
  53173. configurable: true
  53174. });
  53175. Object.defineProperty(InstancedMesh.prototype, "material", {
  53176. get: function () {
  53177. return this._sourceMesh.material;
  53178. },
  53179. enumerable: true,
  53180. configurable: true
  53181. });
  53182. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  53183. get: function () {
  53184. return this._sourceMesh.visibility;
  53185. },
  53186. enumerable: true,
  53187. configurable: true
  53188. });
  53189. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  53190. get: function () {
  53191. return this._sourceMesh.skeleton;
  53192. },
  53193. enumerable: true,
  53194. configurable: true
  53195. });
  53196. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  53197. get: function () {
  53198. return this._sourceMesh.renderingGroupId;
  53199. },
  53200. enumerable: true,
  53201. configurable: true
  53202. });
  53203. /**
  53204. * Returns the total number of vertices (integer).
  53205. */
  53206. InstancedMesh.prototype.getTotalVertices = function () {
  53207. return this._sourceMesh.getTotalVertices();
  53208. };
  53209. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  53210. get: function () {
  53211. return this._sourceMesh;
  53212. },
  53213. enumerable: true,
  53214. configurable: true
  53215. });
  53216. /**
  53217. * Is this node ready to be used/rendered
  53218. * @return {boolean} is it ready
  53219. */
  53220. InstancedMesh.prototype.isReady = function () {
  53221. return this._sourceMesh.isReady(true);
  53222. };
  53223. /**
  53224. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  53225. */
  53226. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  53227. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  53228. };
  53229. /**
  53230. * Sets the vertex data of the mesh geometry for the requested `kind`.
  53231. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  53232. * The `data` are either a numeric array either a Float32Array.
  53233. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  53234. * 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).
  53235. * Note that a new underlying VertexBuffer object is created each call.
  53236. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  53237. *
  53238. * Possible `kind` values :
  53239. * - BABYLON.VertexBuffer.PositionKind
  53240. * - BABYLON.VertexBuffer.UVKind
  53241. * - BABYLON.VertexBuffer.UV2Kind
  53242. * - BABYLON.VertexBuffer.UV3Kind
  53243. * - BABYLON.VertexBuffer.UV4Kind
  53244. * - BABYLON.VertexBuffer.UV5Kind
  53245. * - BABYLON.VertexBuffer.UV6Kind
  53246. * - BABYLON.VertexBuffer.ColorKind
  53247. * - BABYLON.VertexBuffer.MatricesIndicesKind
  53248. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  53249. * - BABYLON.VertexBuffer.MatricesWeightsKind
  53250. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  53251. *
  53252. * Returns the Mesh.
  53253. */
  53254. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  53255. if (this.sourceMesh) {
  53256. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  53257. }
  53258. return this.sourceMesh;
  53259. };
  53260. /**
  53261. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  53262. * If the mesh has no geometry, it is simply returned as it is.
  53263. * The `data` are either a numeric array either a Float32Array.
  53264. * No new underlying VertexBuffer object is created.
  53265. * 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.
  53266. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  53267. *
  53268. * Possible `kind` values :
  53269. * - BABYLON.VertexBuffer.PositionKind
  53270. * - BABYLON.VertexBuffer.UVKind
  53271. * - BABYLON.VertexBuffer.UV2Kind
  53272. * - BABYLON.VertexBuffer.UV3Kind
  53273. * - BABYLON.VertexBuffer.UV4Kind
  53274. * - BABYLON.VertexBuffer.UV5Kind
  53275. * - BABYLON.VertexBuffer.UV6Kind
  53276. * - BABYLON.VertexBuffer.ColorKind
  53277. * - BABYLON.VertexBuffer.MatricesIndicesKind
  53278. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  53279. * - BABYLON.VertexBuffer.MatricesWeightsKind
  53280. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  53281. *
  53282. * Returns the Mesh.
  53283. */
  53284. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  53285. if (this.sourceMesh) {
  53286. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  53287. }
  53288. return this.sourceMesh;
  53289. };
  53290. /**
  53291. * Sets the mesh indices.
  53292. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  53293. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  53294. * This method creates a new index buffer each call.
  53295. * Returns the Mesh.
  53296. */
  53297. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  53298. if (totalVertices === void 0) { totalVertices = null; }
  53299. if (this.sourceMesh) {
  53300. this.sourceMesh.setIndices(indices, totalVertices);
  53301. }
  53302. return this.sourceMesh;
  53303. };
  53304. /**
  53305. * Boolean : True if the mesh owns the requested kind of data.
  53306. */
  53307. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  53308. return this._sourceMesh.isVerticesDataPresent(kind);
  53309. };
  53310. /**
  53311. * Returns an array of indices (IndicesArray).
  53312. */
  53313. InstancedMesh.prototype.getIndices = function () {
  53314. return this._sourceMesh.getIndices();
  53315. };
  53316. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  53317. get: function () {
  53318. return this._sourceMesh._positions;
  53319. },
  53320. enumerable: true,
  53321. configurable: true
  53322. });
  53323. /**
  53324. * Sets a new updated BoundingInfo to the mesh.
  53325. * Returns the mesh.
  53326. */
  53327. InstancedMesh.prototype.refreshBoundingInfo = function () {
  53328. var meshBB = this._sourceMesh.getBoundingInfo();
  53329. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  53330. this._updateBoundingInfo();
  53331. return this;
  53332. };
  53333. InstancedMesh.prototype._preActivate = function () {
  53334. if (this._currentLOD) {
  53335. this._currentLOD._preActivate();
  53336. }
  53337. return this;
  53338. };
  53339. InstancedMesh.prototype._activate = function (renderId) {
  53340. if (this._currentLOD) {
  53341. this._currentLOD._registerInstanceForRenderId(this, renderId);
  53342. }
  53343. return this;
  53344. };
  53345. /**
  53346. * Returns the current associated LOD AbstractMesh.
  53347. */
  53348. InstancedMesh.prototype.getLOD = function (camera) {
  53349. if (!camera) {
  53350. return this;
  53351. }
  53352. var boundingInfo = this.getBoundingInfo();
  53353. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  53354. if (this._currentLOD === this.sourceMesh) {
  53355. return this;
  53356. }
  53357. return this._currentLOD;
  53358. };
  53359. InstancedMesh.prototype._syncSubMeshes = function () {
  53360. this.releaseSubMeshes();
  53361. if (this._sourceMesh.subMeshes) {
  53362. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  53363. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  53364. }
  53365. }
  53366. return this;
  53367. };
  53368. InstancedMesh.prototype._generatePointsArray = function () {
  53369. return this._sourceMesh._generatePointsArray();
  53370. };
  53371. /**
  53372. * Creates a new InstancedMesh from the current mesh.
  53373. * - name (string) : the cloned mesh name
  53374. * - newParent (optional Node) : the optional Node to parent the clone to.
  53375. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  53376. *
  53377. * Returns the clone.
  53378. */
  53379. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  53380. var result = this._sourceMesh.createInstance(name);
  53381. // Deep copy
  53382. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  53383. // Bounding info
  53384. this.refreshBoundingInfo();
  53385. // Parent
  53386. if (newParent) {
  53387. result.parent = newParent;
  53388. }
  53389. if (!doNotCloneChildren) {
  53390. // Children
  53391. for (var index = 0; index < this.getScene().meshes.length; index++) {
  53392. var mesh = this.getScene().meshes[index];
  53393. if (mesh.parent === this) {
  53394. mesh.clone(mesh.name, result);
  53395. }
  53396. }
  53397. }
  53398. result.computeWorldMatrix(true);
  53399. return result;
  53400. };
  53401. /**
  53402. * Disposes the InstancedMesh.
  53403. * Returns nothing.
  53404. */
  53405. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  53406. // Remove from mesh
  53407. var index = this._sourceMesh.instances.indexOf(this);
  53408. this._sourceMesh.instances.splice(index, 1);
  53409. _super.prototype.dispose.call(this, doNotRecurse);
  53410. };
  53411. return InstancedMesh;
  53412. }(BABYLON.AbstractMesh));
  53413. BABYLON.InstancedMesh = InstancedMesh;
  53414. })(BABYLON || (BABYLON = {}));
  53415. //# sourceMappingURL=babylon.instancedMesh.js.map
  53416. var BABYLON;
  53417. (function (BABYLON) {
  53418. var LinesMesh = /** @class */ (function (_super) {
  53419. __extends(LinesMesh, _super);
  53420. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  53421. if (scene === void 0) { scene = null; }
  53422. if (parent === void 0) { parent = null; }
  53423. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  53424. _this.useVertexColor = useVertexColor;
  53425. _this.useVertexAlpha = useVertexAlpha;
  53426. _this.color = new BABYLON.Color3(1, 1, 1);
  53427. _this.alpha = 1;
  53428. if (source) {
  53429. _this.color = source.color.clone();
  53430. _this.alpha = source.alpha;
  53431. _this.useVertexColor = source.useVertexColor;
  53432. _this.useVertexAlpha = source.useVertexAlpha;
  53433. }
  53434. _this._intersectionThreshold = 0.1;
  53435. var defines = [];
  53436. var options = {
  53437. attributes: [BABYLON.VertexBuffer.PositionKind],
  53438. uniforms: ["world", "viewProjection"],
  53439. needAlphaBlending: true,
  53440. defines: defines
  53441. };
  53442. if (useVertexAlpha === false) {
  53443. options.needAlphaBlending = false;
  53444. }
  53445. if (!useVertexColor) {
  53446. options.uniforms.push("color");
  53447. }
  53448. else {
  53449. options.defines.push("#define VERTEXCOLOR");
  53450. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  53451. }
  53452. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  53453. return _this;
  53454. }
  53455. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  53456. /**
  53457. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  53458. * This margin is expressed in world space coordinates, so its value may vary.
  53459. * Default value is 0.1
  53460. * @returns the intersection Threshold value.
  53461. */
  53462. get: function () {
  53463. return this._intersectionThreshold;
  53464. },
  53465. /**
  53466. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  53467. * This margin is expressed in world space coordinates, so its value may vary.
  53468. * @param value the new threshold to apply
  53469. */
  53470. set: function (value) {
  53471. if (this._intersectionThreshold === value) {
  53472. return;
  53473. }
  53474. this._intersectionThreshold = value;
  53475. if (this.geometry) {
  53476. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  53477. }
  53478. },
  53479. enumerable: true,
  53480. configurable: true
  53481. });
  53482. /**
  53483. * Returns the string "LineMesh"
  53484. */
  53485. LinesMesh.prototype.getClassName = function () {
  53486. return "LinesMesh";
  53487. };
  53488. Object.defineProperty(LinesMesh.prototype, "material", {
  53489. get: function () {
  53490. return this._colorShader;
  53491. },
  53492. set: function (value) {
  53493. // Do nothing
  53494. },
  53495. enumerable: true,
  53496. configurable: true
  53497. });
  53498. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  53499. get: function () {
  53500. return false;
  53501. },
  53502. enumerable: true,
  53503. configurable: true
  53504. });
  53505. LinesMesh.prototype.createInstance = function (name) {
  53506. throw new Error("LinesMeshes do not support createInstance.");
  53507. };
  53508. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  53509. if (!this._geometry) {
  53510. return this;
  53511. }
  53512. // VBOs
  53513. this._geometry._bind(this._colorShader.getEffect());
  53514. // Color
  53515. if (!this.useVertexColor) {
  53516. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  53517. }
  53518. return this;
  53519. };
  53520. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  53521. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  53522. return this;
  53523. }
  53524. var engine = this.getScene().getEngine();
  53525. // Draw order
  53526. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  53527. return this;
  53528. };
  53529. LinesMesh.prototype.dispose = function (doNotRecurse) {
  53530. this._colorShader.dispose();
  53531. _super.prototype.dispose.call(this, doNotRecurse);
  53532. };
  53533. /**
  53534. * Returns a new LineMesh object cloned from the current one.
  53535. */
  53536. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  53537. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  53538. };
  53539. return LinesMesh;
  53540. }(BABYLON.Mesh));
  53541. BABYLON.LinesMesh = LinesMesh;
  53542. })(BABYLON || (BABYLON = {}));
  53543. //# sourceMappingURL=babylon.linesMesh.js.map
  53544. var BABYLON;
  53545. (function (BABYLON) {
  53546. var MeshBuilder = /** @class */ (function () {
  53547. function MeshBuilder() {
  53548. }
  53549. MeshBuilder.updateSideOrientation = function (orientation) {
  53550. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  53551. return BABYLON.Mesh.DOUBLESIDE;
  53552. }
  53553. if (orientation === undefined || orientation === null) {
  53554. return BABYLON.Mesh.FRONTSIDE;
  53555. }
  53556. return orientation;
  53557. };
  53558. /**
  53559. * Creates a box mesh.
  53560. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  53561. * The parameter `size` sets the size (float) of each box side (default 1).
  53562. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  53563. * 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).
  53564. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  53565. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  53566. * 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).
  53567. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  53568. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  53569. */
  53570. MeshBuilder.CreateBox = function (name, options, scene) {
  53571. if (scene === void 0) { scene = null; }
  53572. var box = new BABYLON.Mesh(name, scene);
  53573. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  53574. box._originalBuilderSideOrientation = options.sideOrientation;
  53575. var vertexData = BABYLON.VertexData.CreateBox(options);
  53576. vertexData.applyToMesh(box, options.updatable);
  53577. return box;
  53578. };
  53579. /**
  53580. * Creates a sphere mesh.
  53581. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  53582. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  53583. * 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`).
  53584. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  53585. * 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
  53586. * 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).
  53587. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  53588. * 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).
  53589. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  53590. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  53591. */
  53592. MeshBuilder.CreateSphere = function (name, options, scene) {
  53593. var sphere = new BABYLON.Mesh(name, scene);
  53594. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  53595. sphere._originalBuilderSideOrientation = options.sideOrientation;
  53596. var vertexData = BABYLON.VertexData.CreateSphere(options);
  53597. vertexData.applyToMesh(sphere, options.updatable);
  53598. return sphere;
  53599. };
  53600. /**
  53601. * Creates a plane polygonal mesh. By default, this is a disc.
  53602. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  53603. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  53604. * 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.
  53605. * 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
  53606. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  53607. * 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).
  53608. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  53609. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  53610. */
  53611. MeshBuilder.CreateDisc = function (name, options, scene) {
  53612. if (scene === void 0) { scene = null; }
  53613. var disc = new BABYLON.Mesh(name, scene);
  53614. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  53615. disc._originalBuilderSideOrientation = options.sideOrientation;
  53616. var vertexData = BABYLON.VertexData.CreateDisc(options);
  53617. vertexData.applyToMesh(disc, options.updatable);
  53618. return disc;
  53619. };
  53620. /**
  53621. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  53622. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  53623. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  53624. * 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`).
  53625. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  53626. * 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.
  53627. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  53628. * 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).
  53629. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  53630. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  53631. */
  53632. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  53633. var sphere = new BABYLON.Mesh(name, scene);
  53634. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  53635. sphere._originalBuilderSideOrientation = options.sideOrientation;
  53636. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  53637. vertexData.applyToMesh(sphere, options.updatable);
  53638. return sphere;
  53639. };
  53640. ;
  53641. /**
  53642. * Creates a ribbon mesh.
  53643. * 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.
  53644. *
  53645. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  53646. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  53647. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  53648. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  53649. * 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.
  53650. * 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.
  53651. * 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
  53652. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  53653. * 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).
  53654. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  53655. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  53656. * 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.
  53657. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  53658. * 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
  53659. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  53660. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  53661. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  53662. */
  53663. MeshBuilder.CreateRibbon = function (name, options, scene) {
  53664. if (scene === void 0) { scene = null; }
  53665. var pathArray = options.pathArray;
  53666. var closeArray = options.closeArray;
  53667. var closePath = options.closePath;
  53668. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  53669. var instance = options.instance;
  53670. var updatable = options.updatable;
  53671. if (instance) {
  53672. // positionFunction : ribbon case
  53673. // only pathArray and sideOrientation parameters are taken into account for positions update
  53674. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  53675. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  53676. var positionFunction = function (positions) {
  53677. var minlg = pathArray[0].length;
  53678. var i = 0;
  53679. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  53680. for (var si = 1; si <= ns; si++) {
  53681. for (var p = 0; p < pathArray.length; p++) {
  53682. var path = pathArray[p];
  53683. var l = path.length;
  53684. minlg = (minlg < l) ? minlg : l;
  53685. var j = 0;
  53686. while (j < minlg) {
  53687. positions[i] = path[j].x;
  53688. positions[i + 1] = path[j].y;
  53689. positions[i + 2] = path[j].z;
  53690. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  53691. BABYLON.Tmp.Vector3[0].x = path[j].x;
  53692. }
  53693. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  53694. BABYLON.Tmp.Vector3[1].x = path[j].x;
  53695. }
  53696. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  53697. BABYLON.Tmp.Vector3[0].y = path[j].y;
  53698. }
  53699. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  53700. BABYLON.Tmp.Vector3[1].y = path[j].y;
  53701. }
  53702. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  53703. BABYLON.Tmp.Vector3[0].z = path[j].z;
  53704. }
  53705. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  53706. BABYLON.Tmp.Vector3[1].z = path[j].z;
  53707. }
  53708. j++;
  53709. i += 3;
  53710. }
  53711. if (instance._closePath) {
  53712. positions[i] = path[0].x;
  53713. positions[i + 1] = path[0].y;
  53714. positions[i + 2] = path[0].z;
  53715. i += 3;
  53716. }
  53717. }
  53718. }
  53719. };
  53720. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  53721. positionFunction(positions);
  53722. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  53723. instance._boundingInfo.update(instance._worldMatrix);
  53724. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  53725. if (options.colors) {
  53726. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  53727. for (var c = 0; c < options.colors.length; c++) {
  53728. colors[c * 4] = options.colors[c].r;
  53729. colors[c * 4 + 1] = options.colors[c].g;
  53730. colors[c * 4 + 2] = options.colors[c].b;
  53731. colors[c * 4 + 3] = options.colors[c].a;
  53732. }
  53733. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  53734. }
  53735. if (options.uvs) {
  53736. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  53737. for (var i = 0; i < options.uvs.length; i++) {
  53738. uvs[i * 2] = options.uvs[i].x;
  53739. uvs[i * 2 + 1] = options.uvs[i].y;
  53740. }
  53741. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  53742. }
  53743. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  53744. var indices = instance.getIndices();
  53745. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  53746. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  53747. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  53748. if (instance._closePath) {
  53749. var indexFirst = 0;
  53750. var indexLast = 0;
  53751. for (var p = 0; p < pathArray.length; p++) {
  53752. indexFirst = instance._idx[p] * 3;
  53753. if (p + 1 < pathArray.length) {
  53754. indexLast = (instance._idx[p + 1] - 1) * 3;
  53755. }
  53756. else {
  53757. indexLast = normals.length - 3;
  53758. }
  53759. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  53760. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  53761. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  53762. normals[indexLast] = normals[indexFirst];
  53763. normals[indexLast + 1] = normals[indexFirst + 1];
  53764. normals[indexLast + 2] = normals[indexFirst + 2];
  53765. }
  53766. }
  53767. if (!(instance.areNormalsFrozen)) {
  53768. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  53769. }
  53770. }
  53771. return instance;
  53772. }
  53773. else {
  53774. var ribbon = new BABYLON.Mesh(name, scene);
  53775. ribbon._originalBuilderSideOrientation = sideOrientation;
  53776. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  53777. if (closePath) {
  53778. ribbon._idx = vertexData._idx;
  53779. }
  53780. ribbon._closePath = closePath;
  53781. ribbon._closeArray = closeArray;
  53782. vertexData.applyToMesh(ribbon, updatable);
  53783. return ribbon;
  53784. }
  53785. };
  53786. /**
  53787. * Creates a cylinder or a cone mesh.
  53788. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  53789. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  53790. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  53791. * 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.
  53792. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  53793. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  53794. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  53795. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  53796. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  53797. * 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).
  53798. * 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
  53799. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  53800. * 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
  53801. * 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.
  53802. * If `enclose` is false, a ring surface is one element.
  53803. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  53804. * 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
  53805. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  53806. * 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).
  53807. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  53808. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  53809. */
  53810. MeshBuilder.CreateCylinder = function (name, options, scene) {
  53811. var cylinder = new BABYLON.Mesh(name, scene);
  53812. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  53813. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  53814. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  53815. vertexData.applyToMesh(cylinder, options.updatable);
  53816. return cylinder;
  53817. };
  53818. /**
  53819. * Creates a torus mesh.
  53820. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  53821. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  53822. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  53823. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  53824. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  53825. * 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).
  53826. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  53827. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  53828. */
  53829. MeshBuilder.CreateTorus = function (name, options, scene) {
  53830. var torus = new BABYLON.Mesh(name, scene);
  53831. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  53832. torus._originalBuilderSideOrientation = options.sideOrientation;
  53833. var vertexData = BABYLON.VertexData.CreateTorus(options);
  53834. vertexData.applyToMesh(torus, options.updatable);
  53835. return torus;
  53836. };
  53837. /**
  53838. * Creates a torus knot mesh.
  53839. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  53840. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  53841. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  53842. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  53843. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  53844. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  53845. * 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).
  53846. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  53847. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  53848. */
  53849. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  53850. var torusKnot = new BABYLON.Mesh(name, scene);
  53851. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  53852. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  53853. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  53854. vertexData.applyToMesh(torusKnot, options.updatable);
  53855. return torusKnot;
  53856. };
  53857. /**
  53858. * Creates a line system mesh.
  53859. * A line system is a pool of many lines gathered in a single mesh.
  53860. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  53861. * 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.
  53862. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  53863. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  53864. * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter. The way to update it is the same than for
  53865. * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point.
  53866. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need the alpha blending (faster).
  53867. * 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
  53868. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  53869. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  53870. */
  53871. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  53872. var instance = options.instance;
  53873. var lines = options.lines;
  53874. var colors = options.colors;
  53875. if (instance) {
  53876. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  53877. var vertexColor;
  53878. var lineColors;
  53879. if (colors) {
  53880. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  53881. }
  53882. var i = 0;
  53883. var c = 0;
  53884. for (var l = 0; l < lines.length; l++) {
  53885. var points = lines[l];
  53886. for (var p = 0; p < points.length; p++) {
  53887. positions[i] = points[p].x;
  53888. positions[i + 1] = points[p].y;
  53889. positions[i + 2] = points[p].z;
  53890. if (colors && vertexColor) {
  53891. lineColors = colors[l];
  53892. vertexColor[c] = lineColors[p].r;
  53893. vertexColor[c + 1] = lineColors[p].g;
  53894. vertexColor[c + 2] = lineColors[p].b;
  53895. vertexColor[c + 3] = lineColors[p].a;
  53896. c += 4;
  53897. }
  53898. i += 3;
  53899. }
  53900. }
  53901. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  53902. if (colors && vertexColor) {
  53903. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  53904. }
  53905. return instance;
  53906. }
  53907. // line system creation
  53908. var useVertexColor = (colors) ? true : false;
  53909. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  53910. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  53911. vertexData.applyToMesh(lineSystem, options.updatable);
  53912. return lineSystem;
  53913. };
  53914. /**
  53915. * Creates a line mesh.
  53916. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  53917. * 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.
  53918. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  53919. * The parameter `points` is an array successive Vector3.
  53920. * 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
  53921. * The optional parameter `colors` is an array of successive Color4, one per line point.
  53922. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need alpha blending (faster).
  53923. * When updating an instance, remember that only point positions can change, not the number of points.
  53924. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  53925. */
  53926. MeshBuilder.CreateLines = function (name, options, scene) {
  53927. if (scene === void 0) { scene = null; }
  53928. var colors = (options.colors) ? [options.colors] : null;
  53929. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  53930. return lines;
  53931. };
  53932. /**
  53933. * Creates a dashed line mesh.
  53934. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  53935. * 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.
  53936. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  53937. * The parameter `points` is an array successive Vector3.
  53938. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  53939. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  53940. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  53941. * 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
  53942. * When updating an instance, remember that only point positions can change, not the number of points.
  53943. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  53944. */
  53945. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  53946. if (scene === void 0) { scene = null; }
  53947. var points = options.points;
  53948. var instance = options.instance;
  53949. var gapSize = options.gapSize || 1;
  53950. var dashSize = options.dashSize || 3;
  53951. if (instance) {
  53952. var positionFunction = function (positions) {
  53953. var curvect = BABYLON.Vector3.Zero();
  53954. var nbSeg = positions.length / 6;
  53955. var lg = 0;
  53956. var nb = 0;
  53957. var shft = 0;
  53958. var dashshft = 0;
  53959. var curshft = 0;
  53960. var p = 0;
  53961. var i = 0;
  53962. var j = 0;
  53963. for (i = 0; i < points.length - 1; i++) {
  53964. points[i + 1].subtractToRef(points[i], curvect);
  53965. lg += curvect.length();
  53966. }
  53967. shft = lg / nbSeg;
  53968. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  53969. for (i = 0; i < points.length - 1; i++) {
  53970. points[i + 1].subtractToRef(points[i], curvect);
  53971. nb = Math.floor(curvect.length() / shft);
  53972. curvect.normalize();
  53973. j = 0;
  53974. while (j < nb && p < positions.length) {
  53975. curshft = shft * j;
  53976. positions[p] = points[i].x + curshft * curvect.x;
  53977. positions[p + 1] = points[i].y + curshft * curvect.y;
  53978. positions[p + 2] = points[i].z + curshft * curvect.z;
  53979. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  53980. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  53981. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  53982. p += 6;
  53983. j++;
  53984. }
  53985. }
  53986. while (p < positions.length) {
  53987. positions[p] = points[i].x;
  53988. positions[p + 1] = points[i].y;
  53989. positions[p + 2] = points[i].z;
  53990. p += 3;
  53991. }
  53992. };
  53993. instance.updateMeshPositions(positionFunction, false);
  53994. return instance;
  53995. }
  53996. // dashed lines creation
  53997. var dashedLines = new BABYLON.LinesMesh(name, scene);
  53998. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  53999. vertexData.applyToMesh(dashedLines, options.updatable);
  54000. dashedLines.dashSize = dashSize;
  54001. dashedLines.gapSize = gapSize;
  54002. return dashedLines;
  54003. };
  54004. /**
  54005. * Creates an extruded shape mesh.
  54006. * 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.
  54007. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  54008. *
  54009. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  54010. * 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
  54011. * extruded along the Z axis.
  54012. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  54013. * 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.
  54014. * The parameter `scale` (float, default 1) is the value to scale the shape.
  54015. * 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
  54016. * 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
  54017. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  54018. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54019. * 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).
  54020. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54021. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  54022. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54023. */
  54024. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  54025. if (scene === void 0) { scene = null; }
  54026. var path = options.path;
  54027. var shape = options.shape;
  54028. var scale = options.scale || 1;
  54029. var rotation = options.rotation || 0;
  54030. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  54031. var updatable = options.updatable;
  54032. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54033. var instance = options.instance || null;
  54034. var invertUV = options.invertUV || false;
  54035. 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);
  54036. };
  54037. /**
  54038. * Creates an custom extruded shape mesh.
  54039. * 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.
  54040. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  54041. *
  54042. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  54043. * 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
  54044. * extruded along the Z axis.
  54045. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  54046. * 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
  54047. * and the distance of this point from the begining of the path :
  54048. * ```javascript
  54049. * var rotationFunction = function(i, distance) {
  54050. * // do things
  54051. * return rotationValue; }
  54052. * ```
  54053. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  54054. * 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
  54055. * and the distance of this point from the begining of the path :
  54056. * ```javascript
  54057. * var scaleFunction = function(i, distance) {
  54058. * // do things
  54059. * return scaleValue;}
  54060. * ```
  54061. * It must returns a float value that will be the scale value applied to the shape on each path point.
  54062. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  54063. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  54064. * 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
  54065. * 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
  54066. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  54067. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54068. * 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).
  54069. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54070. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  54071. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54072. */
  54073. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  54074. var path = options.path;
  54075. var shape = options.shape;
  54076. var scaleFunction = options.scaleFunction || (function () { return 1; });
  54077. var rotationFunction = options.rotationFunction || (function () { return 0; });
  54078. var ribbonCloseArray = options.ribbonCloseArray || false;
  54079. var ribbonClosePath = options.ribbonClosePath || false;
  54080. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  54081. var updatable = options.updatable;
  54082. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54083. var instance = options.instance;
  54084. var invertUV = options.invertUV || false;
  54085. 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);
  54086. };
  54087. /**
  54088. * Creates lathe mesh.
  54089. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  54090. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  54091. *
  54092. * 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
  54093. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  54094. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  54095. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  54096. * 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.
  54097. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  54098. * 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
  54099. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54100. * 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).
  54101. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54102. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  54103. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54104. */
  54105. MeshBuilder.CreateLathe = function (name, options, scene) {
  54106. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  54107. var closed = (options.closed === undefined) ? true : options.closed;
  54108. var shape = options.shape;
  54109. var radius = options.radius || 1;
  54110. var tessellation = options.tessellation || 64;
  54111. var updatable = options.updatable;
  54112. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54113. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  54114. var pi2 = Math.PI * 2;
  54115. var paths = new Array();
  54116. var invertUV = options.invertUV || false;
  54117. var i = 0;
  54118. var p = 0;
  54119. var step = pi2 / tessellation * arc;
  54120. var rotated;
  54121. var path = new Array();
  54122. ;
  54123. for (i = 0; i <= tessellation; i++) {
  54124. var path = [];
  54125. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  54126. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  54127. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  54128. }
  54129. for (p = 0; p < shape.length; p++) {
  54130. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  54131. path.push(rotated);
  54132. }
  54133. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  54134. 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));
  54135. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  54136. }
  54137. paths.push(path);
  54138. }
  54139. // lathe ribbon
  54140. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  54141. return lathe;
  54142. };
  54143. /**
  54144. * Creates a plane mesh.
  54145. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  54146. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  54147. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  54148. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  54149. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54150. * 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).
  54151. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54152. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54153. */
  54154. MeshBuilder.CreatePlane = function (name, options, scene) {
  54155. var plane = new BABYLON.Mesh(name, scene);
  54156. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54157. plane._originalBuilderSideOrientation = options.sideOrientation;
  54158. var vertexData = BABYLON.VertexData.CreatePlane(options);
  54159. vertexData.applyToMesh(plane, options.updatable);
  54160. if (options.sourcePlane) {
  54161. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  54162. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  54163. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  54164. plane.rotate(vectorProduct, product);
  54165. }
  54166. return plane;
  54167. };
  54168. /**
  54169. * Creates a ground mesh.
  54170. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  54171. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  54172. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  54173. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54174. */
  54175. MeshBuilder.CreateGround = function (name, options, scene) {
  54176. var ground = new BABYLON.GroundMesh(name, scene);
  54177. ground._setReady(false);
  54178. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  54179. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  54180. ground._width = options.width || 1;
  54181. ground._height = options.height || 1;
  54182. ground._maxX = ground._width / 2;
  54183. ground._maxZ = ground._height / 2;
  54184. ground._minX = -ground._maxX;
  54185. ground._minZ = -ground._maxZ;
  54186. var vertexData = BABYLON.VertexData.CreateGround(options);
  54187. vertexData.applyToMesh(ground, options.updatable);
  54188. ground._setReady(true);
  54189. return ground;
  54190. };
  54191. /**
  54192. * Creates a tiled ground mesh.
  54193. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  54194. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  54195. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  54196. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  54197. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  54198. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  54199. * numbers of subdivisions on the ground width and height of each tile.
  54200. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54201. */
  54202. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  54203. var tiledGround = new BABYLON.Mesh(name, scene);
  54204. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  54205. vertexData.applyToMesh(tiledGround, options.updatable);
  54206. return tiledGround;
  54207. };
  54208. /**
  54209. * Creates a ground mesh from a height map.
  54210. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  54211. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  54212. * The parameter `url` sets the URL of the height map image resource.
  54213. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  54214. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  54215. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  54216. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  54217. * 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.
  54218. * 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).
  54219. * This function is passed the newly built mesh :
  54220. * ```javascript
  54221. * function(mesh) { // do things
  54222. * return; }
  54223. * ```
  54224. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54225. */
  54226. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  54227. var width = options.width || 10.0;
  54228. var height = options.height || 10.0;
  54229. var subdivisions = options.subdivisions || 1 | 0;
  54230. var minHeight = options.minHeight || 0.0;
  54231. var maxHeight = options.maxHeight || 1.0;
  54232. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  54233. var updatable = options.updatable;
  54234. var onReady = options.onReady;
  54235. var ground = new BABYLON.GroundMesh(name, scene);
  54236. ground._subdivisionsX = subdivisions;
  54237. ground._subdivisionsY = subdivisions;
  54238. ground._width = width;
  54239. ground._height = height;
  54240. ground._maxX = ground._width / 2.0;
  54241. ground._maxZ = ground._height / 2.0;
  54242. ground._minX = -ground._maxX;
  54243. ground._minZ = -ground._maxZ;
  54244. ground._setReady(false);
  54245. var onload = function (img) {
  54246. // Getting height map data
  54247. var canvas = document.createElement("canvas");
  54248. var context = canvas.getContext("2d");
  54249. if (!context) {
  54250. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  54251. }
  54252. if (scene.isDisposed) {
  54253. return;
  54254. }
  54255. var bufferWidth = img.width;
  54256. var bufferHeight = img.height;
  54257. canvas.width = bufferWidth;
  54258. canvas.height = bufferHeight;
  54259. context.drawImage(img, 0, 0);
  54260. // Create VertexData from map data
  54261. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  54262. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  54263. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  54264. width: width, height: height,
  54265. subdivisions: subdivisions,
  54266. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  54267. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  54268. });
  54269. vertexData.applyToMesh(ground, updatable);
  54270. ground._setReady(true);
  54271. //execute ready callback, if set
  54272. if (onReady) {
  54273. onReady(ground);
  54274. }
  54275. };
  54276. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  54277. return ground;
  54278. };
  54279. /**
  54280. * Creates a polygon mesh.
  54281. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  54282. * 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.
  54283. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54284. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54285. * 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).
  54286. * Remember you can only change the shape positions, not their number when updating a polygon.
  54287. */
  54288. MeshBuilder.CreatePolygon = function (name, options, scene) {
  54289. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54290. var shape = options.shape;
  54291. var holes = options.holes || [];
  54292. var depth = options.depth || 0;
  54293. var contours = [];
  54294. var hole = [];
  54295. for (var i = 0; i < shape.length; i++) {
  54296. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  54297. }
  54298. var epsilon = 0.00000001;
  54299. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  54300. contours.pop();
  54301. }
  54302. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  54303. for (var hNb = 0; hNb < holes.length; hNb++) {
  54304. hole = [];
  54305. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  54306. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  54307. }
  54308. polygonTriangulation.addHole(hole);
  54309. }
  54310. var polygon = polygonTriangulation.build(options.updatable, depth);
  54311. polygon._originalBuilderSideOrientation = options.sideOrientation;
  54312. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  54313. vertexData.applyToMesh(polygon, options.updatable);
  54314. return polygon;
  54315. };
  54316. ;
  54317. /**
  54318. * Creates an extruded polygon mesh, with depth in the Y direction.
  54319. * 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).
  54320. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  54321. */
  54322. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  54323. return MeshBuilder.CreatePolygon(name, options, scene);
  54324. };
  54325. ;
  54326. /**
  54327. * Creates a tube mesh.
  54328. * 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.
  54329. *
  54330. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  54331. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  54332. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  54333. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  54334. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  54335. * 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.
  54336. * It must return a radius value (positive float) :
  54337. * ```javascript
  54338. * var radiusFunction = function(i, distance) {
  54339. * // do things
  54340. * return radius; }
  54341. * ```
  54342. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  54343. * 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
  54344. * 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
  54345. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54346. * 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).
  54347. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54348. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  54349. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54350. */
  54351. MeshBuilder.CreateTube = function (name, options, scene) {
  54352. var path = options.path;
  54353. var instance = options.instance;
  54354. var radius = 1.0;
  54355. if (instance) {
  54356. radius = instance.radius;
  54357. }
  54358. if (options.radius !== undefined) {
  54359. radius = options.radius;
  54360. }
  54361. ;
  54362. var tessellation = options.tessellation || 64 | 0;
  54363. var radiusFunction = options.radiusFunction || null;
  54364. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  54365. var invertUV = options.invertUV || false;
  54366. var updatable = options.updatable;
  54367. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54368. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  54369. // tube geometry
  54370. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  54371. var tangents = path3D.getTangents();
  54372. var normals = path3D.getNormals();
  54373. var distances = path3D.getDistances();
  54374. var pi2 = Math.PI * 2;
  54375. var step = pi2 / tessellation * arc;
  54376. var returnRadius = function () { return radius; };
  54377. var radiusFunctionFinal = radiusFunction || returnRadius;
  54378. var circlePath;
  54379. var rad;
  54380. var normal;
  54381. var rotated;
  54382. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  54383. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  54384. for (var i = 0; i < path.length; i++) {
  54385. rad = radiusFunctionFinal(i, distances[i]); // current radius
  54386. circlePath = Array(); // current circle array
  54387. normal = normals[i]; // current normal
  54388. for (var t = 0; t < tessellation; t++) {
  54389. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  54390. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  54391. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  54392. rotated.scaleInPlace(rad).addInPlace(path[i]);
  54393. circlePath[t] = rotated;
  54394. }
  54395. circlePaths[index] = circlePath;
  54396. index++;
  54397. }
  54398. // cap
  54399. var capPath = function (nbPoints, pathIndex) {
  54400. var pointCap = Array();
  54401. for (var i = 0; i < nbPoints; i++) {
  54402. pointCap.push(path[pathIndex]);
  54403. }
  54404. return pointCap;
  54405. };
  54406. switch (cap) {
  54407. case BABYLON.Mesh.NO_CAP:
  54408. break;
  54409. case BABYLON.Mesh.CAP_START:
  54410. circlePaths[0] = capPath(tessellation, 0);
  54411. circlePaths[1] = circlePaths[2].slice(0);
  54412. break;
  54413. case BABYLON.Mesh.CAP_END:
  54414. circlePaths[index] = circlePaths[index - 1].slice(0);
  54415. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  54416. break;
  54417. case BABYLON.Mesh.CAP_ALL:
  54418. circlePaths[0] = capPath(tessellation, 0);
  54419. circlePaths[1] = circlePaths[2].slice(0);
  54420. circlePaths[index] = circlePaths[index - 1].slice(0);
  54421. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  54422. break;
  54423. default:
  54424. break;
  54425. }
  54426. return circlePaths;
  54427. };
  54428. var path3D;
  54429. var pathArray;
  54430. if (instance) {
  54431. var arc = options.arc || instance.arc;
  54432. path3D = (instance.path3D).update(path);
  54433. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  54434. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  54435. instance.path3D = path3D;
  54436. instance.pathArray = pathArray;
  54437. instance.arc = arc;
  54438. instance.radius = radius;
  54439. return instance;
  54440. }
  54441. // tube creation
  54442. path3D = new BABYLON.Path3D(path);
  54443. var newPathArray = new Array();
  54444. cap = (cap < 0 || cap > 3) ? 0 : cap;
  54445. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  54446. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  54447. tube.pathArray = pathArray;
  54448. tube.path3D = path3D;
  54449. tube.tessellation = tessellation;
  54450. tube.cap = cap;
  54451. tube.arc = options.arc;
  54452. tube.radius = radius;
  54453. return tube;
  54454. };
  54455. /**
  54456. * Creates a polyhedron mesh.
  54457. *
  54458. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  54459. * 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
  54460. * to choose the wanted type.
  54461. * The parameter `size` (positive float, default 1) sets the polygon size.
  54462. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  54463. * 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`.
  54464. * 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
  54465. * 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)`).
  54466. * 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
  54467. * 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.
  54468. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54469. * 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).
  54470. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54471. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54472. */
  54473. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  54474. var polyhedron = new BABYLON.Mesh(name, scene);
  54475. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54476. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  54477. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  54478. vertexData.applyToMesh(polyhedron, options.updatable);
  54479. return polyhedron;
  54480. };
  54481. /**
  54482. * Creates a decal mesh.
  54483. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  54484. * 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.
  54485. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  54486. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  54487. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  54488. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  54489. */
  54490. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  54491. var indices = sourceMesh.getIndices();
  54492. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  54493. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  54494. var position = options.position || BABYLON.Vector3.Zero();
  54495. var normal = options.normal || BABYLON.Vector3.Up();
  54496. var size = options.size || BABYLON.Vector3.One();
  54497. var angle = options.angle || 0;
  54498. // Getting correct rotation
  54499. if (!normal) {
  54500. var target = new BABYLON.Vector3(0, 0, 1);
  54501. var camera = sourceMesh.getScene().activeCamera;
  54502. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  54503. normal = camera.globalPosition.subtract(cameraWorldTarget);
  54504. }
  54505. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  54506. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  54507. var pitch = Math.atan2(normal.y, len);
  54508. // Matrix
  54509. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  54510. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  54511. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  54512. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  54513. var vertexData = new BABYLON.VertexData();
  54514. vertexData.indices = [];
  54515. vertexData.positions = [];
  54516. vertexData.normals = [];
  54517. vertexData.uvs = [];
  54518. var currentVertexDataIndex = 0;
  54519. var extractDecalVector3 = function (indexId) {
  54520. var result = new BABYLON.PositionNormalVertex();
  54521. if (!indices || !positions || !normals) {
  54522. return result;
  54523. }
  54524. var vertexId = indices[indexId];
  54525. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  54526. // Send vector to decal local world
  54527. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  54528. // Get normal
  54529. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  54530. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  54531. return result;
  54532. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  54533. var clip = function (vertices, axis) {
  54534. if (vertices.length === 0) {
  54535. return vertices;
  54536. }
  54537. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  54538. var clipVertices = function (v0, v1) {
  54539. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  54540. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  54541. };
  54542. var result = new Array();
  54543. for (var index = 0; index < vertices.length; index += 3) {
  54544. var v1Out;
  54545. var v2Out;
  54546. var v3Out;
  54547. var total = 0;
  54548. var nV1 = null;
  54549. var nV2 = null;
  54550. var nV3 = null;
  54551. var nV4 = null;
  54552. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  54553. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  54554. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  54555. v1Out = d1 > 0;
  54556. v2Out = d2 > 0;
  54557. v3Out = d3 > 0;
  54558. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  54559. switch (total) {
  54560. case 0:
  54561. result.push(vertices[index]);
  54562. result.push(vertices[index + 1]);
  54563. result.push(vertices[index + 2]);
  54564. break;
  54565. case 1:
  54566. if (v1Out) {
  54567. nV1 = vertices[index + 1];
  54568. nV2 = vertices[index + 2];
  54569. nV3 = clipVertices(vertices[index], nV1);
  54570. nV4 = clipVertices(vertices[index], nV2);
  54571. }
  54572. if (v2Out) {
  54573. nV1 = vertices[index];
  54574. nV2 = vertices[index + 2];
  54575. nV3 = clipVertices(vertices[index + 1], nV1);
  54576. nV4 = clipVertices(vertices[index + 1], nV2);
  54577. result.push(nV3);
  54578. result.push(nV2.clone());
  54579. result.push(nV1.clone());
  54580. result.push(nV2.clone());
  54581. result.push(nV3.clone());
  54582. result.push(nV4);
  54583. break;
  54584. }
  54585. if (v3Out) {
  54586. nV1 = vertices[index];
  54587. nV2 = vertices[index + 1];
  54588. nV3 = clipVertices(vertices[index + 2], nV1);
  54589. nV4 = clipVertices(vertices[index + 2], nV2);
  54590. }
  54591. if (nV1 && nV2 && nV3 && nV4) {
  54592. result.push(nV1.clone());
  54593. result.push(nV2.clone());
  54594. result.push(nV3);
  54595. result.push(nV4);
  54596. result.push(nV3.clone());
  54597. result.push(nV2.clone());
  54598. }
  54599. break;
  54600. case 2:
  54601. if (!v1Out) {
  54602. nV1 = vertices[index].clone();
  54603. nV2 = clipVertices(nV1, vertices[index + 1]);
  54604. nV3 = clipVertices(nV1, vertices[index + 2]);
  54605. result.push(nV1);
  54606. result.push(nV2);
  54607. result.push(nV3);
  54608. }
  54609. if (!v2Out) {
  54610. nV1 = vertices[index + 1].clone();
  54611. nV2 = clipVertices(nV1, vertices[index + 2]);
  54612. nV3 = clipVertices(nV1, vertices[index]);
  54613. result.push(nV1);
  54614. result.push(nV2);
  54615. result.push(nV3);
  54616. }
  54617. if (!v3Out) {
  54618. nV1 = vertices[index + 2].clone();
  54619. nV2 = clipVertices(nV1, vertices[index]);
  54620. nV3 = clipVertices(nV1, vertices[index + 1]);
  54621. result.push(nV1);
  54622. result.push(nV2);
  54623. result.push(nV3);
  54624. }
  54625. break;
  54626. case 3:
  54627. break;
  54628. }
  54629. }
  54630. return result;
  54631. };
  54632. for (var index = 0; index < indices.length; index += 3) {
  54633. var faceVertices = new Array();
  54634. faceVertices.push(extractDecalVector3(index));
  54635. faceVertices.push(extractDecalVector3(index + 1));
  54636. faceVertices.push(extractDecalVector3(index + 2));
  54637. // Clip
  54638. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  54639. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  54640. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  54641. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  54642. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  54643. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  54644. if (faceVertices.length === 0) {
  54645. continue;
  54646. }
  54647. // Add UVs and get back to world
  54648. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  54649. var vertex = faceVertices[vIndex];
  54650. //TODO check for Int32Array | Uint32Array | Uint16Array
  54651. vertexData.indices.push(currentVertexDataIndex);
  54652. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  54653. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  54654. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  54655. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  54656. currentVertexDataIndex++;
  54657. }
  54658. }
  54659. // Return mesh
  54660. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  54661. vertexData.applyToMesh(decal);
  54662. decal.position = position.clone();
  54663. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  54664. return decal;
  54665. };
  54666. // Privates
  54667. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  54668. // extrusion geometry
  54669. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  54670. var tangents = path3D.getTangents();
  54671. var normals = path3D.getNormals();
  54672. var binormals = path3D.getBinormals();
  54673. var distances = path3D.getDistances();
  54674. var angle = 0;
  54675. var returnScale = function () { return scale !== null ? scale : 1; };
  54676. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  54677. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  54678. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  54679. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  54680. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  54681. for (var i = 0; i < curve.length; i++) {
  54682. var shapePath = new Array();
  54683. var angleStep = rotate(i, distances[i]);
  54684. var scaleRatio = scl(i, distances[i]);
  54685. for (var p = 0; p < shape.length; p++) {
  54686. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  54687. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  54688. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  54689. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  54690. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  54691. shapePath[p] = rotated;
  54692. }
  54693. shapePaths[index] = shapePath;
  54694. angle += angleStep;
  54695. index++;
  54696. }
  54697. // cap
  54698. var capPath = function (shapePath) {
  54699. var pointCap = Array();
  54700. var barycenter = BABYLON.Vector3.Zero();
  54701. var i;
  54702. for (i = 0; i < shapePath.length; i++) {
  54703. barycenter.addInPlace(shapePath[i]);
  54704. }
  54705. barycenter.scaleInPlace(1.0 / shapePath.length);
  54706. for (i = 0; i < shapePath.length; i++) {
  54707. pointCap.push(barycenter);
  54708. }
  54709. return pointCap;
  54710. };
  54711. switch (cap) {
  54712. case BABYLON.Mesh.NO_CAP:
  54713. break;
  54714. case BABYLON.Mesh.CAP_START:
  54715. shapePaths[0] = capPath(shapePaths[2]);
  54716. shapePaths[1] = shapePaths[2];
  54717. break;
  54718. case BABYLON.Mesh.CAP_END:
  54719. shapePaths[index] = shapePaths[index - 1];
  54720. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  54721. break;
  54722. case BABYLON.Mesh.CAP_ALL:
  54723. shapePaths[0] = capPath(shapePaths[2]);
  54724. shapePaths[1] = shapePaths[2];
  54725. shapePaths[index] = shapePaths[index - 1];
  54726. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  54727. break;
  54728. default:
  54729. break;
  54730. }
  54731. return shapePaths;
  54732. };
  54733. var path3D;
  54734. var pathArray;
  54735. if (instance) {
  54736. path3D = (instance.path3D).update(curve);
  54737. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  54738. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  54739. return instance;
  54740. }
  54741. // extruded shape creation
  54742. path3D = new BABYLON.Path3D(curve);
  54743. var newShapePaths = new Array();
  54744. cap = (cap < 0 || cap > 3) ? 0 : cap;
  54745. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  54746. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  54747. extrudedGeneric.pathArray = pathArray;
  54748. extrudedGeneric.path3D = path3D;
  54749. extrudedGeneric.cap = cap;
  54750. return extrudedGeneric;
  54751. };
  54752. return MeshBuilder;
  54753. }());
  54754. BABYLON.MeshBuilder = MeshBuilder;
  54755. })(BABYLON || (BABYLON = {}));
  54756. //# sourceMappingURL=babylon.meshBuilder.js.map
  54757. var BABYLON;
  54758. (function (BABYLON) {
  54759. var AudioEngine = /** @class */ (function () {
  54760. function AudioEngine() {
  54761. this._audioContext = null;
  54762. this._audioContextInitialized = false;
  54763. this.canUseWebAudio = false;
  54764. this.WarnedWebAudioUnsupported = false;
  54765. this.unlocked = false;
  54766. this.isMP3supported = false;
  54767. this.isOGGsupported = false;
  54768. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  54769. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  54770. this.canUseWebAudio = true;
  54771. }
  54772. var audioElem = document.createElement('audio');
  54773. try {
  54774. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  54775. this.isMP3supported = true;
  54776. }
  54777. }
  54778. catch (e) {
  54779. // protect error during capability check.
  54780. }
  54781. try {
  54782. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  54783. this.isOGGsupported = true;
  54784. }
  54785. }
  54786. catch (e) {
  54787. // protect error during capability check.
  54788. }
  54789. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  54790. this._unlockiOSaudio();
  54791. }
  54792. else {
  54793. this.unlocked = true;
  54794. }
  54795. }
  54796. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  54797. get: function () {
  54798. if (!this._audioContextInitialized) {
  54799. this._initializeAudioContext();
  54800. }
  54801. return this._audioContext;
  54802. },
  54803. enumerable: true,
  54804. configurable: true
  54805. });
  54806. AudioEngine.prototype._unlockiOSaudio = function () {
  54807. var _this = this;
  54808. var unlockaudio = function () {
  54809. if (!_this.audioContext) {
  54810. return;
  54811. }
  54812. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  54813. var source = _this.audioContext.createBufferSource();
  54814. source.buffer = buffer;
  54815. source.connect(_this.audioContext.destination);
  54816. source.start(0);
  54817. setTimeout(function () {
  54818. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  54819. _this.unlocked = true;
  54820. window.removeEventListener('touchend', unlockaudio, false);
  54821. if (_this.onAudioUnlocked) {
  54822. _this.onAudioUnlocked();
  54823. }
  54824. }
  54825. }, 0);
  54826. };
  54827. window.addEventListener('touchend', unlockaudio, false);
  54828. };
  54829. AudioEngine.prototype._initializeAudioContext = function () {
  54830. try {
  54831. if (this.canUseWebAudio) {
  54832. this._audioContext = new AudioContext();
  54833. // create a global volume gain node
  54834. this.masterGain = this._audioContext.createGain();
  54835. this.masterGain.gain.value = 1;
  54836. this.masterGain.connect(this._audioContext.destination);
  54837. this._audioContextInitialized = true;
  54838. }
  54839. }
  54840. catch (e) {
  54841. this.canUseWebAudio = false;
  54842. BABYLON.Tools.Error("Web Audio: " + e.message);
  54843. }
  54844. };
  54845. AudioEngine.prototype.dispose = function () {
  54846. if (this.canUseWebAudio && this._audioContextInitialized) {
  54847. if (this._connectedAnalyser && this._audioContext) {
  54848. this._connectedAnalyser.stopDebugCanvas();
  54849. this._connectedAnalyser.dispose();
  54850. this.masterGain.disconnect();
  54851. this.masterGain.connect(this._audioContext.destination);
  54852. this._connectedAnalyser = null;
  54853. }
  54854. this.masterGain.gain.value = 1;
  54855. }
  54856. this.WarnedWebAudioUnsupported = false;
  54857. };
  54858. AudioEngine.prototype.getGlobalVolume = function () {
  54859. if (this.canUseWebAudio && this._audioContextInitialized) {
  54860. return this.masterGain.gain.value;
  54861. }
  54862. else {
  54863. return -1;
  54864. }
  54865. };
  54866. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  54867. if (this.canUseWebAudio && this._audioContextInitialized) {
  54868. this.masterGain.gain.value = newVolume;
  54869. }
  54870. };
  54871. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  54872. if (this._connectedAnalyser) {
  54873. this._connectedAnalyser.stopDebugCanvas();
  54874. }
  54875. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  54876. this._connectedAnalyser = analyser;
  54877. this.masterGain.disconnect();
  54878. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  54879. }
  54880. };
  54881. return AudioEngine;
  54882. }());
  54883. BABYLON.AudioEngine = AudioEngine;
  54884. })(BABYLON || (BABYLON = {}));
  54885. //# sourceMappingURL=babylon.audioEngine.js.map
  54886. var BABYLON;
  54887. (function (BABYLON) {
  54888. var Sound = /** @class */ (function () {
  54889. /**
  54890. * Create a sound and attach it to a scene
  54891. * @param name Name of your sound
  54892. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  54893. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  54894. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  54895. */
  54896. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  54897. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  54898. var _this = this;
  54899. this.autoplay = false;
  54900. this.loop = false;
  54901. this.useCustomAttenuation = false;
  54902. this.spatialSound = false;
  54903. this.refDistance = 1;
  54904. this.rolloffFactor = 1;
  54905. this.maxDistance = 100;
  54906. this.distanceModel = "linear";
  54907. this._panningModel = "equalpower";
  54908. this._playbackRate = 1;
  54909. this._streaming = false;
  54910. this._startTime = 0;
  54911. this._startOffset = 0;
  54912. this._position = BABYLON.Vector3.Zero();
  54913. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  54914. this._volume = 1;
  54915. this._isReadyToPlay = false;
  54916. this.isPlaying = false;
  54917. this.isPaused = false;
  54918. this._isDirectional = false;
  54919. // Used if you'd like to create a directional sound.
  54920. // If not set, the sound will be omnidirectional
  54921. this._coneInnerAngle = 360;
  54922. this._coneOuterAngle = 360;
  54923. this._coneOuterGain = 0;
  54924. this._isOutputConnected = false;
  54925. this._urlType = "Unknown";
  54926. this.name = name;
  54927. this._scene = scene;
  54928. this._readyToPlayCallback = readyToPlayCallback;
  54929. // Default custom attenuation function is a linear attenuation
  54930. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  54931. if (currentDistance < maxDistance) {
  54932. return currentVolume * (1 - currentDistance / maxDistance);
  54933. }
  54934. else {
  54935. return 0;
  54936. }
  54937. };
  54938. if (options) {
  54939. this.autoplay = options.autoplay || false;
  54940. this.loop = options.loop || false;
  54941. // if volume === 0, we need another way to check this option
  54942. if (options.volume !== undefined) {
  54943. this._volume = options.volume;
  54944. }
  54945. this.spatialSound = options.spatialSound || false;
  54946. this.maxDistance = options.maxDistance || 100;
  54947. this.useCustomAttenuation = options.useCustomAttenuation || false;
  54948. this.rolloffFactor = options.rolloffFactor || 1;
  54949. this.refDistance = options.refDistance || 1;
  54950. this.distanceModel = options.distanceModel || "linear";
  54951. this._playbackRate = options.playbackRate || 1;
  54952. this._streaming = options.streaming || false;
  54953. }
  54954. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  54955. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  54956. this._soundGain.gain.value = this._volume;
  54957. this._inputAudioNode = this._soundGain;
  54958. this._ouputAudioNode = this._soundGain;
  54959. if (this.spatialSound) {
  54960. this._createSpatialParameters();
  54961. }
  54962. this._scene.mainSoundTrack.AddSound(this);
  54963. var validParameter = true;
  54964. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  54965. if (urlOrArrayBuffer) {
  54966. if (typeof (urlOrArrayBuffer) === "string")
  54967. this._urlType = "String";
  54968. if (Array.isArray(urlOrArrayBuffer))
  54969. this._urlType = "Array";
  54970. if (urlOrArrayBuffer instanceof ArrayBuffer)
  54971. this._urlType = "ArrayBuffer";
  54972. var urls = [];
  54973. var codecSupportedFound = false;
  54974. switch (this._urlType) {
  54975. case "ArrayBuffer":
  54976. if (urlOrArrayBuffer.byteLength > 0) {
  54977. codecSupportedFound = true;
  54978. this._soundLoaded(urlOrArrayBuffer);
  54979. }
  54980. break;
  54981. case "String":
  54982. urls.push(urlOrArrayBuffer);
  54983. case "Array":
  54984. if (urls.length === 0)
  54985. urls = urlOrArrayBuffer;
  54986. // If we found a supported format, we load it immediately and stop the loop
  54987. for (var i = 0; i < urls.length; i++) {
  54988. var url = urls[i];
  54989. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  54990. codecSupportedFound = true;
  54991. }
  54992. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  54993. codecSupportedFound = true;
  54994. }
  54995. if (url.indexOf(".wav", url.length - 4) !== -1) {
  54996. codecSupportedFound = true;
  54997. }
  54998. if (url.indexOf("blob:") !== -1) {
  54999. codecSupportedFound = true;
  55000. }
  55001. if (codecSupportedFound) {
  55002. // Loading sound using XHR2
  55003. if (!this._streaming) {
  55004. this._scene._loadFile(url, function (data) { _this._soundLoaded(data); }, undefined, true, true);
  55005. }
  55006. else {
  55007. this._htmlAudioElement = new Audio(url);
  55008. this._htmlAudioElement.controls = false;
  55009. this._htmlAudioElement.loop = this.loop;
  55010. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  55011. this._htmlAudioElement.preload = "auto";
  55012. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  55013. _this._isReadyToPlay = true;
  55014. if (_this.autoplay) {
  55015. _this.play();
  55016. }
  55017. if (_this._readyToPlayCallback) {
  55018. _this._readyToPlayCallback();
  55019. }
  55020. });
  55021. document.body.appendChild(this._htmlAudioElement);
  55022. }
  55023. break;
  55024. }
  55025. }
  55026. break;
  55027. default:
  55028. validParameter = false;
  55029. break;
  55030. }
  55031. if (!validParameter) {
  55032. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  55033. }
  55034. else {
  55035. if (!codecSupportedFound) {
  55036. this._isReadyToPlay = true;
  55037. // Simulating a ready to play event to avoid breaking code path
  55038. if (this._readyToPlayCallback) {
  55039. window.setTimeout(function () {
  55040. if (_this._readyToPlayCallback) {
  55041. _this._readyToPlayCallback();
  55042. }
  55043. }, 1000);
  55044. }
  55045. }
  55046. }
  55047. }
  55048. }
  55049. else {
  55050. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  55051. this._scene.mainSoundTrack.AddSound(this);
  55052. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  55053. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  55054. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  55055. }
  55056. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  55057. if (this._readyToPlayCallback) {
  55058. window.setTimeout(function () {
  55059. if (_this._readyToPlayCallback) {
  55060. _this._readyToPlayCallback();
  55061. }
  55062. }, 1000);
  55063. }
  55064. }
  55065. }
  55066. Sound.prototype.dispose = function () {
  55067. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  55068. if (this.isPlaying) {
  55069. this.stop();
  55070. }
  55071. this._isReadyToPlay = false;
  55072. if (this.soundTrackId === -1) {
  55073. this._scene.mainSoundTrack.RemoveSound(this);
  55074. }
  55075. else {
  55076. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  55077. }
  55078. if (this._soundGain) {
  55079. this._soundGain.disconnect();
  55080. this._soundGain = null;
  55081. }
  55082. if (this._soundPanner) {
  55083. this._soundPanner.disconnect();
  55084. this._soundPanner = null;
  55085. }
  55086. if (this._soundSource) {
  55087. this._soundSource.disconnect();
  55088. this._soundSource = null;
  55089. }
  55090. this._audioBuffer = null;
  55091. if (this._htmlAudioElement) {
  55092. this._htmlAudioElement.pause();
  55093. this._htmlAudioElement.src = "";
  55094. document.body.removeChild(this._htmlAudioElement);
  55095. }
  55096. if (this._connectedMesh && this._registerFunc) {
  55097. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  55098. this._connectedMesh = null;
  55099. }
  55100. }
  55101. };
  55102. Sound.prototype.isReady = function () {
  55103. return this._isReadyToPlay;
  55104. };
  55105. Sound.prototype._soundLoaded = function (audioData) {
  55106. var _this = this;
  55107. if (!BABYLON.Engine.audioEngine.audioContext) {
  55108. return;
  55109. }
  55110. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  55111. _this._audioBuffer = buffer;
  55112. _this._isReadyToPlay = true;
  55113. if (_this.autoplay) {
  55114. _this.play();
  55115. }
  55116. if (_this._readyToPlayCallback) {
  55117. _this._readyToPlayCallback();
  55118. }
  55119. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  55120. };
  55121. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  55122. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  55123. this._audioBuffer = audioBuffer;
  55124. this._isReadyToPlay = true;
  55125. }
  55126. };
  55127. Sound.prototype.updateOptions = function (options) {
  55128. if (options) {
  55129. this.loop = options.loop || this.loop;
  55130. this.maxDistance = options.maxDistance || this.maxDistance;
  55131. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  55132. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  55133. this.refDistance = options.refDistance || this.refDistance;
  55134. this.distanceModel = options.distanceModel || this.distanceModel;
  55135. this._playbackRate = options.playbackRate || this._playbackRate;
  55136. this._updateSpatialParameters();
  55137. if (this.isPlaying) {
  55138. if (this._streaming) {
  55139. this._htmlAudioElement.playbackRate = this._playbackRate;
  55140. }
  55141. else {
  55142. if (this._soundSource) {
  55143. this._soundSource.playbackRate.value = this._playbackRate;
  55144. }
  55145. }
  55146. }
  55147. }
  55148. };
  55149. Sound.prototype._createSpatialParameters = function () {
  55150. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  55151. if (this._scene.headphone) {
  55152. this._panningModel = "HRTF";
  55153. }
  55154. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  55155. this._updateSpatialParameters();
  55156. this._soundPanner.connect(this._ouputAudioNode);
  55157. this._inputAudioNode = this._soundPanner;
  55158. }
  55159. };
  55160. Sound.prototype._updateSpatialParameters = function () {
  55161. if (this.spatialSound && this._soundPanner) {
  55162. if (this.useCustomAttenuation) {
  55163. // Tricks to disable in a way embedded Web Audio attenuation
  55164. this._soundPanner.distanceModel = "linear";
  55165. this._soundPanner.maxDistance = Number.MAX_VALUE;
  55166. this._soundPanner.refDistance = 1;
  55167. this._soundPanner.rolloffFactor = 1;
  55168. this._soundPanner.panningModel = this._panningModel;
  55169. }
  55170. else {
  55171. this._soundPanner.distanceModel = this.distanceModel;
  55172. this._soundPanner.maxDistance = this.maxDistance;
  55173. this._soundPanner.refDistance = this.refDistance;
  55174. this._soundPanner.rolloffFactor = this.rolloffFactor;
  55175. this._soundPanner.panningModel = this._panningModel;
  55176. }
  55177. }
  55178. };
  55179. Sound.prototype.switchPanningModelToHRTF = function () {
  55180. this._panningModel = "HRTF";
  55181. this._switchPanningModel();
  55182. };
  55183. Sound.prototype.switchPanningModelToEqualPower = function () {
  55184. this._panningModel = "equalpower";
  55185. this._switchPanningModel();
  55186. };
  55187. Sound.prototype._switchPanningModel = function () {
  55188. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  55189. this._soundPanner.panningModel = this._panningModel;
  55190. }
  55191. };
  55192. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  55193. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  55194. if (this._isOutputConnected) {
  55195. this._ouputAudioNode.disconnect();
  55196. }
  55197. this._ouputAudioNode.connect(soundTrackAudioNode);
  55198. this._isOutputConnected = true;
  55199. }
  55200. };
  55201. /**
  55202. * Transform this sound into a directional source
  55203. * @param coneInnerAngle Size of the inner cone in degree
  55204. * @param coneOuterAngle Size of the outer cone in degree
  55205. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  55206. */
  55207. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  55208. if (coneOuterAngle < coneInnerAngle) {
  55209. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  55210. return;
  55211. }
  55212. this._coneInnerAngle = coneInnerAngle;
  55213. this._coneOuterAngle = coneOuterAngle;
  55214. this._coneOuterGain = coneOuterGain;
  55215. this._isDirectional = true;
  55216. if (this.isPlaying && this.loop) {
  55217. this.stop();
  55218. this.play();
  55219. }
  55220. };
  55221. Sound.prototype.setPosition = function (newPosition) {
  55222. this._position = newPosition;
  55223. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  55224. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  55225. }
  55226. };
  55227. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  55228. this._localDirection = newLocalDirection;
  55229. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  55230. this._updateDirection();
  55231. }
  55232. };
  55233. Sound.prototype._updateDirection = function () {
  55234. if (!this._connectedMesh || !this._soundPanner) {
  55235. return;
  55236. }
  55237. var mat = this._connectedMesh.getWorldMatrix();
  55238. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  55239. direction.normalize();
  55240. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  55241. };
  55242. Sound.prototype.updateDistanceFromListener = function () {
  55243. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  55244. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  55245. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  55246. }
  55247. };
  55248. Sound.prototype.setAttenuationFunction = function (callback) {
  55249. this._customAttenuationFunction = callback;
  55250. };
  55251. /**
  55252. * Play the sound
  55253. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  55254. * @param offset (optional) Start the sound setting it at a specific time
  55255. */
  55256. Sound.prototype.play = function (time, offset) {
  55257. var _this = this;
  55258. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  55259. try {
  55260. if (this._startOffset < 0) {
  55261. time = -this._startOffset;
  55262. this._startOffset = 0;
  55263. }
  55264. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  55265. if (!this._soundSource || !this._streamingSource) {
  55266. if (this.spatialSound && this._soundPanner) {
  55267. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  55268. if (this._isDirectional) {
  55269. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  55270. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  55271. this._soundPanner.coneOuterGain = this._coneOuterGain;
  55272. if (this._connectedMesh) {
  55273. this._updateDirection();
  55274. }
  55275. else {
  55276. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  55277. }
  55278. }
  55279. }
  55280. }
  55281. if (this._streaming) {
  55282. if (!this._streamingSource) {
  55283. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  55284. this._htmlAudioElement.onended = function () { _this._onended(); };
  55285. this._htmlAudioElement.playbackRate = this._playbackRate;
  55286. }
  55287. this._streamingSource.disconnect();
  55288. this._streamingSource.connect(this._inputAudioNode);
  55289. this._htmlAudioElement.play();
  55290. }
  55291. else {
  55292. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  55293. this._soundSource.buffer = this._audioBuffer;
  55294. this._soundSource.connect(this._inputAudioNode);
  55295. this._soundSource.loop = this.loop;
  55296. this._soundSource.playbackRate.value = this._playbackRate;
  55297. this._soundSource.onended = function () { _this._onended(); };
  55298. if (this._soundSource.buffer) {
  55299. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  55300. }
  55301. }
  55302. this._startTime = startTime;
  55303. this.isPlaying = true;
  55304. this.isPaused = false;
  55305. }
  55306. catch (ex) {
  55307. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  55308. }
  55309. }
  55310. };
  55311. Sound.prototype._onended = function () {
  55312. this.isPlaying = false;
  55313. if (this.onended) {
  55314. this.onended();
  55315. }
  55316. };
  55317. /**
  55318. * Stop the sound
  55319. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  55320. */
  55321. Sound.prototype.stop = function (time) {
  55322. if (this.isPlaying) {
  55323. if (this._streaming) {
  55324. this._htmlAudioElement.pause();
  55325. // Test needed for Firefox or it will generate an Invalid State Error
  55326. if (this._htmlAudioElement.currentTime > 0) {
  55327. this._htmlAudioElement.currentTime = 0;
  55328. }
  55329. }
  55330. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  55331. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  55332. this._soundSource.stop(stopTime);
  55333. this._soundSource.onended = function () { };
  55334. if (!this.isPaused) {
  55335. this._startOffset = 0;
  55336. }
  55337. }
  55338. this.isPlaying = false;
  55339. }
  55340. };
  55341. Sound.prototype.pause = function () {
  55342. if (this.isPlaying) {
  55343. this.isPaused = true;
  55344. if (this._streaming) {
  55345. this._htmlAudioElement.pause();
  55346. }
  55347. else if (BABYLON.Engine.audioEngine.audioContext) {
  55348. this.stop(0);
  55349. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  55350. }
  55351. }
  55352. };
  55353. Sound.prototype.setVolume = function (newVolume, time) {
  55354. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  55355. if (time && BABYLON.Engine.audioEngine.audioContext) {
  55356. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  55357. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  55358. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  55359. }
  55360. else {
  55361. this._soundGain.gain.value = newVolume;
  55362. }
  55363. }
  55364. this._volume = newVolume;
  55365. };
  55366. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  55367. this._playbackRate = newPlaybackRate;
  55368. if (this.isPlaying) {
  55369. if (this._streaming) {
  55370. this._htmlAudioElement.playbackRate = this._playbackRate;
  55371. }
  55372. else if (this._soundSource) {
  55373. this._soundSource.playbackRate.value = this._playbackRate;
  55374. }
  55375. }
  55376. };
  55377. Sound.prototype.getVolume = function () {
  55378. return this._volume;
  55379. };
  55380. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  55381. var _this = this;
  55382. if (this._connectedMesh && this._registerFunc) {
  55383. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  55384. this._registerFunc = null;
  55385. }
  55386. this._connectedMesh = meshToConnectTo;
  55387. if (!this.spatialSound) {
  55388. this.spatialSound = true;
  55389. this._createSpatialParameters();
  55390. if (this.isPlaying && this.loop) {
  55391. this.stop();
  55392. this.play();
  55393. }
  55394. }
  55395. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  55396. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  55397. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  55398. };
  55399. Sound.prototype.detachFromMesh = function () {
  55400. if (this._connectedMesh && this._registerFunc) {
  55401. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  55402. this._registerFunc = null;
  55403. this._connectedMesh = null;
  55404. }
  55405. };
  55406. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  55407. if (!node.getBoundingInfo) {
  55408. return;
  55409. }
  55410. var mesh = node;
  55411. var boundingInfo = mesh.getBoundingInfo();
  55412. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  55413. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  55414. this._updateDirection();
  55415. }
  55416. };
  55417. Sound.prototype.clone = function () {
  55418. var _this = this;
  55419. if (!this._streaming) {
  55420. var setBufferAndRun = function () {
  55421. if (_this._isReadyToPlay) {
  55422. clonedSound._audioBuffer = _this.getAudioBuffer();
  55423. clonedSound._isReadyToPlay = true;
  55424. if (clonedSound.autoplay) {
  55425. clonedSound.play();
  55426. }
  55427. }
  55428. else {
  55429. window.setTimeout(setBufferAndRun, 300);
  55430. }
  55431. };
  55432. var currentOptions = {
  55433. autoplay: this.autoplay, loop: this.loop,
  55434. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  55435. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  55436. refDistance: this.refDistance, distanceModel: this.distanceModel
  55437. };
  55438. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  55439. if (this.useCustomAttenuation) {
  55440. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  55441. }
  55442. clonedSound.setPosition(this._position);
  55443. clonedSound.setPlaybackRate(this._playbackRate);
  55444. setBufferAndRun();
  55445. return clonedSound;
  55446. }
  55447. else {
  55448. return null;
  55449. }
  55450. };
  55451. Sound.prototype.getAudioBuffer = function () {
  55452. return this._audioBuffer;
  55453. };
  55454. Sound.prototype.serialize = function () {
  55455. var serializationObject = {
  55456. name: this.name,
  55457. url: this.name,
  55458. autoplay: this.autoplay,
  55459. loop: this.loop,
  55460. volume: this._volume,
  55461. spatialSound: this.spatialSound,
  55462. maxDistance: this.maxDistance,
  55463. rolloffFactor: this.rolloffFactor,
  55464. refDistance: this.refDistance,
  55465. distanceModel: this.distanceModel,
  55466. playbackRate: this._playbackRate,
  55467. panningModel: this._panningModel,
  55468. soundTrackId: this.soundTrackId
  55469. };
  55470. if (this.spatialSound) {
  55471. if (this._connectedMesh)
  55472. serializationObject.connectedMeshId = this._connectedMesh.id;
  55473. serializationObject.position = this._position.asArray();
  55474. serializationObject.refDistance = this.refDistance;
  55475. serializationObject.distanceModel = this.distanceModel;
  55476. serializationObject.isDirectional = this._isDirectional;
  55477. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  55478. serializationObject.coneInnerAngle = this._coneInnerAngle;
  55479. serializationObject.coneOuterAngle = this._coneOuterAngle;
  55480. serializationObject.coneOuterGain = this._coneOuterGain;
  55481. }
  55482. return serializationObject;
  55483. };
  55484. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  55485. var soundName = parsedSound.name;
  55486. var soundUrl;
  55487. if (parsedSound.url) {
  55488. soundUrl = rootUrl + parsedSound.url;
  55489. }
  55490. else {
  55491. soundUrl = rootUrl + soundName;
  55492. }
  55493. var options = {
  55494. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  55495. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  55496. rolloffFactor: parsedSound.rolloffFactor,
  55497. refDistance: parsedSound.refDistance,
  55498. distanceModel: parsedSound.distanceModel,
  55499. playbackRate: parsedSound.playbackRate
  55500. };
  55501. var newSound;
  55502. if (!sourceSound) {
  55503. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  55504. scene._addPendingData(newSound);
  55505. }
  55506. else {
  55507. var setBufferAndRun = function () {
  55508. if (sourceSound._isReadyToPlay) {
  55509. newSound._audioBuffer = sourceSound.getAudioBuffer();
  55510. newSound._isReadyToPlay = true;
  55511. if (newSound.autoplay) {
  55512. newSound.play();
  55513. }
  55514. }
  55515. else {
  55516. window.setTimeout(setBufferAndRun, 300);
  55517. }
  55518. };
  55519. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  55520. setBufferAndRun();
  55521. }
  55522. if (parsedSound.position) {
  55523. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  55524. newSound.setPosition(soundPosition);
  55525. }
  55526. if (parsedSound.isDirectional) {
  55527. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  55528. if (parsedSound.localDirectionToMesh) {
  55529. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  55530. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  55531. }
  55532. }
  55533. if (parsedSound.connectedMeshId) {
  55534. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  55535. if (connectedMesh) {
  55536. newSound.attachToMesh(connectedMesh);
  55537. }
  55538. }
  55539. return newSound;
  55540. };
  55541. return Sound;
  55542. }());
  55543. BABYLON.Sound = Sound;
  55544. })(BABYLON || (BABYLON = {}));
  55545. //# sourceMappingURL=babylon.sound.js.map
  55546. var BABYLON;
  55547. (function (BABYLON) {
  55548. var SoundTrack = /** @class */ (function () {
  55549. function SoundTrack(scene, options) {
  55550. this.id = -1;
  55551. this._isMainTrack = false;
  55552. this._isInitialized = false;
  55553. this._scene = scene;
  55554. this.soundCollection = new Array();
  55555. this._options = options;
  55556. if (!this._isMainTrack) {
  55557. this._scene.soundTracks.push(this);
  55558. this.id = this._scene.soundTracks.length - 1;
  55559. }
  55560. }
  55561. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  55562. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  55563. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  55564. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  55565. if (this._options) {
  55566. if (this._options.volume) {
  55567. this._outputAudioNode.gain.value = this._options.volume;
  55568. }
  55569. if (this._options.mainTrack) {
  55570. this._isMainTrack = this._options.mainTrack;
  55571. }
  55572. }
  55573. this._isInitialized = true;
  55574. }
  55575. };
  55576. SoundTrack.prototype.dispose = function () {
  55577. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  55578. if (this._connectedAnalyser) {
  55579. this._connectedAnalyser.stopDebugCanvas();
  55580. }
  55581. while (this.soundCollection.length) {
  55582. this.soundCollection[0].dispose();
  55583. }
  55584. if (this._outputAudioNode) {
  55585. this._outputAudioNode.disconnect();
  55586. }
  55587. this._outputAudioNode = null;
  55588. }
  55589. };
  55590. SoundTrack.prototype.AddSound = function (sound) {
  55591. if (!this._isInitialized) {
  55592. this._initializeSoundTrackAudioGraph();
  55593. }
  55594. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  55595. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  55596. }
  55597. if (sound.soundTrackId) {
  55598. if (sound.soundTrackId === -1) {
  55599. this._scene.mainSoundTrack.RemoveSound(sound);
  55600. }
  55601. else {
  55602. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  55603. }
  55604. }
  55605. this.soundCollection.push(sound);
  55606. sound.soundTrackId = this.id;
  55607. };
  55608. SoundTrack.prototype.RemoveSound = function (sound) {
  55609. var index = this.soundCollection.indexOf(sound);
  55610. if (index !== -1) {
  55611. this.soundCollection.splice(index, 1);
  55612. }
  55613. };
  55614. SoundTrack.prototype.setVolume = function (newVolume) {
  55615. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  55616. this._outputAudioNode.gain.value = newVolume;
  55617. }
  55618. };
  55619. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  55620. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  55621. for (var i = 0; i < this.soundCollection.length; i++) {
  55622. this.soundCollection[i].switchPanningModelToHRTF();
  55623. }
  55624. }
  55625. };
  55626. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  55627. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  55628. for (var i = 0; i < this.soundCollection.length; i++) {
  55629. this.soundCollection[i].switchPanningModelToEqualPower();
  55630. }
  55631. }
  55632. };
  55633. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  55634. if (this._connectedAnalyser) {
  55635. this._connectedAnalyser.stopDebugCanvas();
  55636. }
  55637. this._connectedAnalyser = analyser;
  55638. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  55639. this._outputAudioNode.disconnect();
  55640. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  55641. }
  55642. };
  55643. return SoundTrack;
  55644. }());
  55645. BABYLON.SoundTrack = SoundTrack;
  55646. })(BABYLON || (BABYLON = {}));
  55647. //# sourceMappingURL=babylon.soundtrack.js.map
  55648. var BABYLON;
  55649. (function (BABYLON) {
  55650. var Analyser = /** @class */ (function () {
  55651. function Analyser(scene) {
  55652. this.SMOOTHING = 0.75;
  55653. this.FFT_SIZE = 512;
  55654. this.BARGRAPHAMPLITUDE = 256;
  55655. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  55656. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  55657. this._scene = scene;
  55658. this._audioEngine = BABYLON.Engine.audioEngine;
  55659. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  55660. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  55661. this._webAudioAnalyser.minDecibels = -140;
  55662. this._webAudioAnalyser.maxDecibels = 0;
  55663. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  55664. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  55665. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  55666. }
  55667. }
  55668. Analyser.prototype.getFrequencyBinCount = function () {
  55669. if (this._audioEngine.canUseWebAudio) {
  55670. return this._webAudioAnalyser.frequencyBinCount;
  55671. }
  55672. else {
  55673. return 0;
  55674. }
  55675. };
  55676. Analyser.prototype.getByteFrequencyData = function () {
  55677. if (this._audioEngine.canUseWebAudio) {
  55678. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  55679. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  55680. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  55681. }
  55682. return this._byteFreqs;
  55683. };
  55684. Analyser.prototype.getByteTimeDomainData = function () {
  55685. if (this._audioEngine.canUseWebAudio) {
  55686. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  55687. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  55688. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  55689. }
  55690. return this._byteTime;
  55691. };
  55692. Analyser.prototype.getFloatFrequencyData = function () {
  55693. if (this._audioEngine.canUseWebAudio) {
  55694. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  55695. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  55696. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  55697. }
  55698. return this._floatFreqs;
  55699. };
  55700. Analyser.prototype.drawDebugCanvas = function () {
  55701. var _this = this;
  55702. if (this._audioEngine.canUseWebAudio) {
  55703. if (!this._debugCanvas) {
  55704. this._debugCanvas = document.createElement("canvas");
  55705. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  55706. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  55707. this._debugCanvas.style.position = "absolute";
  55708. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  55709. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  55710. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  55711. document.body.appendChild(this._debugCanvas);
  55712. this._registerFunc = function () {
  55713. _this.drawDebugCanvas();
  55714. };
  55715. this._scene.registerBeforeRender(this._registerFunc);
  55716. }
  55717. if (this._registerFunc && this._debugCanvasContext) {
  55718. var workingArray = this.getByteFrequencyData();
  55719. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  55720. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  55721. // Draw the frequency domain chart.
  55722. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  55723. var value = workingArray[i];
  55724. var percent = value / this.BARGRAPHAMPLITUDE;
  55725. var height = this.DEBUGCANVASSIZE.height * percent;
  55726. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  55727. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  55728. var hue = i / this.getFrequencyBinCount() * 360;
  55729. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  55730. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  55731. }
  55732. }
  55733. }
  55734. };
  55735. Analyser.prototype.stopDebugCanvas = function () {
  55736. if (this._debugCanvas) {
  55737. if (this._registerFunc) {
  55738. this._scene.unregisterBeforeRender(this._registerFunc);
  55739. this._registerFunc = null;
  55740. }
  55741. document.body.removeChild(this._debugCanvas);
  55742. this._debugCanvas = null;
  55743. this._debugCanvasContext = null;
  55744. }
  55745. };
  55746. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  55747. if (this._audioEngine.canUseWebAudio) {
  55748. inputAudioNode.connect(this._webAudioAnalyser);
  55749. this._webAudioAnalyser.connect(outputAudioNode);
  55750. }
  55751. };
  55752. Analyser.prototype.dispose = function () {
  55753. if (this._audioEngine.canUseWebAudio) {
  55754. this._webAudioAnalyser.disconnect();
  55755. }
  55756. };
  55757. return Analyser;
  55758. }());
  55759. BABYLON.Analyser = Analyser;
  55760. })(BABYLON || (BABYLON = {}));
  55761. //# sourceMappingURL=babylon.analyser.js.map
  55762. var BABYLON;
  55763. (function (BABYLON) {
  55764. var CubeTexture = /** @class */ (function (_super) {
  55765. __extends(CubeTexture, _super);
  55766. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  55767. if (extensions === void 0) { extensions = null; }
  55768. if (noMipmap === void 0) { noMipmap = false; }
  55769. if (files === void 0) { files = null; }
  55770. if (onLoad === void 0) { onLoad = null; }
  55771. if (onError === void 0) { onError = null; }
  55772. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  55773. if (prefiltered === void 0) { prefiltered = false; }
  55774. if (forcedExtension === void 0) { forcedExtension = null; }
  55775. var _this = _super.call(this, scene) || this;
  55776. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  55777. /**
  55778. * Gets or sets the center of the bounding box associated with the cube texture
  55779. * It must define where the camera used to render the texture was set
  55780. */
  55781. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  55782. _this.name = rootUrl;
  55783. _this.url = rootUrl;
  55784. _this._noMipmap = noMipmap;
  55785. _this.hasAlpha = false;
  55786. _this._format = format;
  55787. _this._prefiltered = prefiltered;
  55788. _this.isCube = true;
  55789. _this._textureMatrix = BABYLON.Matrix.Identity();
  55790. if (prefiltered) {
  55791. _this.gammaSpace = false;
  55792. }
  55793. if (!rootUrl && !files) {
  55794. return _this;
  55795. }
  55796. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  55797. var lastDot = rootUrl.lastIndexOf(".");
  55798. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  55799. var isDDS = (extension === ".dds");
  55800. if (!files) {
  55801. if (!isDDS && !extensions) {
  55802. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  55803. }
  55804. files = [];
  55805. if (extensions) {
  55806. for (var index = 0; index < extensions.length; index++) {
  55807. files.push(rootUrl + extensions[index]);
  55808. }
  55809. }
  55810. }
  55811. _this._files = files;
  55812. if (!_this._texture) {
  55813. if (!scene.useDelayedTextureLoading) {
  55814. if (prefiltered) {
  55815. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  55816. }
  55817. else {
  55818. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  55819. }
  55820. }
  55821. else {
  55822. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  55823. }
  55824. }
  55825. else if (onLoad) {
  55826. if (_this._texture.isReady) {
  55827. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  55828. }
  55829. else {
  55830. _this._texture.onLoadedObservable.add(onLoad);
  55831. }
  55832. }
  55833. return _this;
  55834. }
  55835. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  55836. get: function () {
  55837. return this._boundingBoxSize;
  55838. },
  55839. /**
  55840. * Gets or sets the size of the bounding box associated with the cube texture
  55841. * When defined, the cubemap will switch to local mode
  55842. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  55843. * @example https://www.babylonjs-playground.com/#RNASML
  55844. */
  55845. set: function (value) {
  55846. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  55847. return;
  55848. }
  55849. this._boundingBoxSize = value;
  55850. var scene = this.getScene();
  55851. if (scene) {
  55852. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  55853. }
  55854. },
  55855. enumerable: true,
  55856. configurable: true
  55857. });
  55858. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  55859. return new CubeTexture("", scene, null, noMipmap, files);
  55860. };
  55861. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  55862. if (forcedExtension === void 0) { forcedExtension = null; }
  55863. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  55864. };
  55865. // Methods
  55866. CubeTexture.prototype.delayLoad = function () {
  55867. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  55868. return;
  55869. }
  55870. var scene = this.getScene();
  55871. if (!scene) {
  55872. return;
  55873. }
  55874. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  55875. this._texture = this._getFromCache(this.url, this._noMipmap);
  55876. if (!this._texture) {
  55877. if (this._prefiltered) {
  55878. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  55879. }
  55880. else {
  55881. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  55882. }
  55883. }
  55884. };
  55885. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  55886. return this._textureMatrix;
  55887. };
  55888. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  55889. this._textureMatrix = value;
  55890. };
  55891. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  55892. var texture = BABYLON.SerializationHelper.Parse(function () {
  55893. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  55894. }, parsedTexture, scene);
  55895. // Animations
  55896. if (parsedTexture.animations) {
  55897. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  55898. var parsedAnimation = parsedTexture.animations[animationIndex];
  55899. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  55900. }
  55901. }
  55902. return texture;
  55903. };
  55904. CubeTexture.prototype.clone = function () {
  55905. var _this = this;
  55906. return BABYLON.SerializationHelper.Clone(function () {
  55907. var scene = _this.getScene();
  55908. if (!scene) {
  55909. return _this;
  55910. }
  55911. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  55912. }, this);
  55913. };
  55914. return CubeTexture;
  55915. }(BABYLON.BaseTexture));
  55916. BABYLON.CubeTexture = CubeTexture;
  55917. })(BABYLON || (BABYLON = {}));
  55918. //# sourceMappingURL=babylon.cubeTexture.js.map
  55919. var BABYLON;
  55920. (function (BABYLON) {
  55921. var RenderTargetTexture = /** @class */ (function (_super) {
  55922. __extends(RenderTargetTexture, _super);
  55923. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  55924. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  55925. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  55926. if (isCube === void 0) { isCube = false; }
  55927. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  55928. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  55929. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  55930. if (isMulti === void 0) { isMulti = false; }
  55931. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  55932. _this.isCube = isCube;
  55933. /**
  55934. * Use this list to define the list of mesh you want to render.
  55935. */
  55936. _this.renderList = new Array();
  55937. _this.renderParticles = true;
  55938. _this.renderSprites = false;
  55939. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  55940. _this.ignoreCameraViewport = false;
  55941. // Events
  55942. /**
  55943. * An event triggered when the texture is unbind.
  55944. * @type {BABYLON.Observable}
  55945. */
  55946. _this.onBeforeBindObservable = new BABYLON.Observable();
  55947. /**
  55948. * An event triggered when the texture is unbind.
  55949. * @type {BABYLON.Observable}
  55950. */
  55951. _this.onAfterUnbindObservable = new BABYLON.Observable();
  55952. /**
  55953. * An event triggered before rendering the texture
  55954. * @type {BABYLON.Observable}
  55955. */
  55956. _this.onBeforeRenderObservable = new BABYLON.Observable();
  55957. /**
  55958. * An event triggered after rendering the texture
  55959. * @type {BABYLON.Observable}
  55960. */
  55961. _this.onAfterRenderObservable = new BABYLON.Observable();
  55962. /**
  55963. * An event triggered after the texture clear
  55964. * @type {BABYLON.Observable}
  55965. */
  55966. _this.onClearObservable = new BABYLON.Observable();
  55967. _this._currentRefreshId = -1;
  55968. _this._refreshRate = 1;
  55969. _this._samples = 1;
  55970. /**
  55971. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  55972. * It must define where the camera used to render the texture is set
  55973. */
  55974. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  55975. scene = _this.getScene();
  55976. if (!scene) {
  55977. return _this;
  55978. }
  55979. _this._engine = scene.getEngine();
  55980. _this.name = name;
  55981. _this.isRenderTarget = true;
  55982. _this._initialSizeParameter = size;
  55983. _this._processSizeParameter(size);
  55984. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  55985. });
  55986. _this._generateMipMaps = generateMipMaps ? true : false;
  55987. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  55988. // Rendering groups
  55989. _this._renderingManager = new BABYLON.RenderingManager(scene);
  55990. if (isMulti) {
  55991. return _this;
  55992. }
  55993. _this._renderTargetOptions = {
  55994. generateMipMaps: generateMipMaps,
  55995. type: type,
  55996. samplingMode: samplingMode,
  55997. generateDepthBuffer: generateDepthBuffer,
  55998. generateStencilBuffer: generateStencilBuffer
  55999. };
  56000. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  56001. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  56002. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  56003. }
  56004. if (isCube) {
  56005. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  56006. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  56007. _this._textureMatrix = BABYLON.Matrix.Identity();
  56008. }
  56009. else {
  56010. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  56011. }
  56012. return _this;
  56013. }
  56014. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  56015. get: function () {
  56016. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  56017. },
  56018. enumerable: true,
  56019. configurable: true
  56020. });
  56021. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  56022. get: function () {
  56023. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  56024. },
  56025. enumerable: true,
  56026. configurable: true
  56027. });
  56028. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  56029. get: function () {
  56030. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  56031. },
  56032. enumerable: true,
  56033. configurable: true
  56034. });
  56035. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  56036. set: function (callback) {
  56037. if (this._onAfterUnbindObserver) {
  56038. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  56039. }
  56040. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  56041. },
  56042. enumerable: true,
  56043. configurable: true
  56044. });
  56045. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  56046. set: function (callback) {
  56047. if (this._onBeforeRenderObserver) {
  56048. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  56049. }
  56050. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  56051. },
  56052. enumerable: true,
  56053. configurable: true
  56054. });
  56055. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  56056. set: function (callback) {
  56057. if (this._onAfterRenderObserver) {
  56058. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  56059. }
  56060. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  56061. },
  56062. enumerable: true,
  56063. configurable: true
  56064. });
  56065. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  56066. set: function (callback) {
  56067. if (this._onClearObserver) {
  56068. this.onClearObservable.remove(this._onClearObserver);
  56069. }
  56070. this._onClearObserver = this.onClearObservable.add(callback);
  56071. },
  56072. enumerable: true,
  56073. configurable: true
  56074. });
  56075. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  56076. get: function () {
  56077. return this._renderTargetOptions;
  56078. },
  56079. enumerable: true,
  56080. configurable: true
  56081. });
  56082. RenderTargetTexture.prototype._onRatioRescale = function () {
  56083. if (this._sizeRatio) {
  56084. this.resize(this._initialSizeParameter);
  56085. }
  56086. };
  56087. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  56088. get: function () {
  56089. return this._boundingBoxSize;
  56090. },
  56091. /**
  56092. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  56093. * When defined, the cubemap will switch to local mode
  56094. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  56095. * @example https://www.babylonjs-playground.com/#RNASML
  56096. */
  56097. set: function (value) {
  56098. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  56099. return;
  56100. }
  56101. this._boundingBoxSize = value;
  56102. var scene = this.getScene();
  56103. if (scene) {
  56104. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  56105. }
  56106. },
  56107. enumerable: true,
  56108. configurable: true
  56109. });
  56110. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  56111. if (size.ratio) {
  56112. this._sizeRatio = size.ratio;
  56113. this._size = {
  56114. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  56115. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  56116. };
  56117. }
  56118. else {
  56119. this._size = size;
  56120. }
  56121. };
  56122. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  56123. get: function () {
  56124. return this._samples;
  56125. },
  56126. set: function (value) {
  56127. if (this._samples === value) {
  56128. return;
  56129. }
  56130. var scene = this.getScene();
  56131. if (!scene) {
  56132. return;
  56133. }
  56134. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  56135. },
  56136. enumerable: true,
  56137. configurable: true
  56138. });
  56139. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  56140. this._currentRefreshId = -1;
  56141. };
  56142. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  56143. get: function () {
  56144. return this._refreshRate;
  56145. },
  56146. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  56147. set: function (value) {
  56148. this._refreshRate = value;
  56149. this.resetRefreshCounter();
  56150. },
  56151. enumerable: true,
  56152. configurable: true
  56153. });
  56154. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  56155. if (!this._postProcessManager) {
  56156. var scene = this.getScene();
  56157. if (!scene) {
  56158. return;
  56159. }
  56160. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  56161. this._postProcesses = new Array();
  56162. }
  56163. this._postProcesses.push(postProcess);
  56164. this._postProcesses[0].autoClear = false;
  56165. };
  56166. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  56167. if (!this._postProcesses) {
  56168. return;
  56169. }
  56170. if (dispose) {
  56171. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  56172. var postProcess = _a[_i];
  56173. postProcess.dispose();
  56174. }
  56175. }
  56176. this._postProcesses = [];
  56177. };
  56178. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  56179. if (!this._postProcesses) {
  56180. return;
  56181. }
  56182. var index = this._postProcesses.indexOf(postProcess);
  56183. if (index === -1) {
  56184. return;
  56185. }
  56186. this._postProcesses.splice(index, 1);
  56187. if (this._postProcesses.length > 0) {
  56188. this._postProcesses[0].autoClear = false;
  56189. }
  56190. };
  56191. RenderTargetTexture.prototype._shouldRender = function () {
  56192. if (this._currentRefreshId === -1) {
  56193. this._currentRefreshId = 1;
  56194. return true;
  56195. }
  56196. if (this.refreshRate === this._currentRefreshId) {
  56197. this._currentRefreshId = 1;
  56198. return true;
  56199. }
  56200. this._currentRefreshId++;
  56201. return false;
  56202. };
  56203. RenderTargetTexture.prototype.getRenderSize = function () {
  56204. if (this._size.width) {
  56205. return this._size.width;
  56206. }
  56207. return this._size;
  56208. };
  56209. RenderTargetTexture.prototype.getRenderWidth = function () {
  56210. if (this._size.width) {
  56211. return this._size.width;
  56212. }
  56213. return this._size;
  56214. };
  56215. RenderTargetTexture.prototype.getRenderHeight = function () {
  56216. if (this._size.width) {
  56217. return this._size.height;
  56218. }
  56219. return this._size;
  56220. };
  56221. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  56222. get: function () {
  56223. return true;
  56224. },
  56225. enumerable: true,
  56226. configurable: true
  56227. });
  56228. RenderTargetTexture.prototype.scale = function (ratio) {
  56229. var newSize = this.getRenderSize() * ratio;
  56230. this.resize(newSize);
  56231. };
  56232. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  56233. if (this.isCube) {
  56234. return this._textureMatrix;
  56235. }
  56236. return _super.prototype.getReflectionTextureMatrix.call(this);
  56237. };
  56238. RenderTargetTexture.prototype.resize = function (size) {
  56239. this.releaseInternalTexture();
  56240. var scene = this.getScene();
  56241. if (!scene) {
  56242. return;
  56243. }
  56244. this._processSizeParameter(size);
  56245. if (this.isCube) {
  56246. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  56247. }
  56248. else {
  56249. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  56250. }
  56251. };
  56252. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  56253. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  56254. if (dumpForDebug === void 0) { dumpForDebug = false; }
  56255. var scene = this.getScene();
  56256. if (!scene) {
  56257. return;
  56258. }
  56259. var engine = scene.getEngine();
  56260. if (this.useCameraPostProcesses !== undefined) {
  56261. useCameraPostProcess = this.useCameraPostProcesses;
  56262. }
  56263. if (this._waitingRenderList) {
  56264. this.renderList = [];
  56265. for (var index = 0; index < this._waitingRenderList.length; index++) {
  56266. var id = this._waitingRenderList[index];
  56267. var mesh_1 = scene.getMeshByID(id);
  56268. if (mesh_1) {
  56269. this.renderList.push(mesh_1);
  56270. }
  56271. }
  56272. delete this._waitingRenderList;
  56273. }
  56274. // Is predicate defined?
  56275. if (this.renderListPredicate) {
  56276. if (this.renderList) {
  56277. this.renderList.splice(0); // Clear previous renderList
  56278. }
  56279. else {
  56280. this.renderList = [];
  56281. }
  56282. var scene = this.getScene();
  56283. if (!scene) {
  56284. return;
  56285. }
  56286. var sceneMeshes = scene.meshes;
  56287. for (var index = 0; index < sceneMeshes.length; index++) {
  56288. var mesh = sceneMeshes[index];
  56289. if (this.renderListPredicate(mesh)) {
  56290. this.renderList.push(mesh);
  56291. }
  56292. }
  56293. }
  56294. this.onBeforeBindObservable.notifyObservers(this);
  56295. // Set custom projection.
  56296. // Needs to be before binding to prevent changing the aspect ratio.
  56297. var camera;
  56298. if (this.activeCamera) {
  56299. camera = this.activeCamera;
  56300. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  56301. if (this.activeCamera !== scene.activeCamera) {
  56302. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  56303. }
  56304. }
  56305. else {
  56306. camera = scene.activeCamera;
  56307. if (camera) {
  56308. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  56309. }
  56310. }
  56311. // Prepare renderingManager
  56312. this._renderingManager.reset();
  56313. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  56314. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  56315. var sceneRenderId = scene.getRenderId();
  56316. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  56317. var mesh = currentRenderList[meshIndex];
  56318. if (mesh) {
  56319. if (!mesh.isReady()) {
  56320. // Reset _currentRefreshId
  56321. this.resetRefreshCounter();
  56322. continue;
  56323. }
  56324. mesh._preActivateForIntermediateRendering(sceneRenderId);
  56325. var isMasked = void 0;
  56326. if (!this.renderList && camera) {
  56327. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  56328. }
  56329. else {
  56330. isMasked = false;
  56331. }
  56332. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  56333. mesh._activate(sceneRenderId);
  56334. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  56335. var subMesh = mesh.subMeshes[subIndex];
  56336. scene._activeIndices.addCount(subMesh.indexCount, false);
  56337. this._renderingManager.dispatch(subMesh, mesh);
  56338. }
  56339. }
  56340. }
  56341. }
  56342. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  56343. var particleSystem = scene.particleSystems[particleIndex];
  56344. var emitter = particleSystem.emitter;
  56345. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  56346. continue;
  56347. }
  56348. if (currentRenderList.indexOf(emitter) >= 0) {
  56349. this._renderingManager.dispatchParticles(particleSystem);
  56350. }
  56351. }
  56352. if (this.isCube) {
  56353. for (var face = 0; face < 6; face++) {
  56354. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  56355. scene.incrementRenderId();
  56356. scene.resetCachedMaterial();
  56357. }
  56358. }
  56359. else {
  56360. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  56361. }
  56362. this.onAfterUnbindObservable.notifyObservers(this);
  56363. if (scene.activeCamera) {
  56364. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  56365. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  56366. }
  56367. engine.setViewport(scene.activeCamera.viewport);
  56368. }
  56369. scene.resetCachedMaterial();
  56370. };
  56371. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  56372. var minimum = 128;
  56373. var x = renderDimension * scale;
  56374. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  56375. // Ensure we don't exceed the render dimension (while staying POT)
  56376. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  56377. };
  56378. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  56379. var _this = this;
  56380. if (!this._texture) {
  56381. return;
  56382. }
  56383. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  56384. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  56385. });
  56386. };
  56387. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  56388. var scene = this.getScene();
  56389. if (!scene) {
  56390. return;
  56391. }
  56392. var engine = scene.getEngine();
  56393. if (!this._texture) {
  56394. return;
  56395. }
  56396. // Bind
  56397. if (this._postProcessManager) {
  56398. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  56399. }
  56400. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  56401. if (this._texture) {
  56402. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport);
  56403. }
  56404. }
  56405. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  56406. // Clear
  56407. if (this.onClearObservable.hasObservers()) {
  56408. this.onClearObservable.notifyObservers(engine);
  56409. }
  56410. else {
  56411. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  56412. }
  56413. if (!this._doNotChangeAspectRatio) {
  56414. scene.updateTransformMatrix(true);
  56415. }
  56416. // Render
  56417. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  56418. if (this._postProcessManager) {
  56419. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  56420. }
  56421. else if (useCameraPostProcess) {
  56422. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  56423. }
  56424. if (!this._doNotChangeAspectRatio) {
  56425. scene.updateTransformMatrix(true);
  56426. }
  56427. // Dump ?
  56428. if (dumpForDebug) {
  56429. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  56430. }
  56431. // Unbind
  56432. if (!this.isCube || faceIndex === 5) {
  56433. if (this.isCube) {
  56434. if (faceIndex === 5) {
  56435. engine.generateMipMapsForCubemap(this._texture);
  56436. }
  56437. }
  56438. this.unbindFrameBuffer(engine, faceIndex);
  56439. }
  56440. else {
  56441. this.onAfterRenderObservable.notifyObservers(faceIndex);
  56442. }
  56443. };
  56444. /**
  56445. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  56446. * This allowed control for front to back rendering or reversly depending of the special needs.
  56447. *
  56448. * @param renderingGroupId The rendering group id corresponding to its index
  56449. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  56450. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  56451. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  56452. */
  56453. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  56454. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  56455. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  56456. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  56457. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  56458. };
  56459. /**
  56460. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  56461. *
  56462. * @param renderingGroupId The rendering group id corresponding to its index
  56463. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  56464. */
  56465. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  56466. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  56467. };
  56468. RenderTargetTexture.prototype.clone = function () {
  56469. var textureSize = this.getSize();
  56470. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._renderTargetOptions.generateMipMaps, this._doNotChangeAspectRatio, this._renderTargetOptions.type, this.isCube, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer, this._renderTargetOptions.generateStencilBuffer);
  56471. // Base texture
  56472. newTexture.hasAlpha = this.hasAlpha;
  56473. newTexture.level = this.level;
  56474. // RenderTarget Texture
  56475. newTexture.coordinatesMode = this.coordinatesMode;
  56476. if (this.renderList) {
  56477. newTexture.renderList = this.renderList.slice(0);
  56478. }
  56479. return newTexture;
  56480. };
  56481. RenderTargetTexture.prototype.serialize = function () {
  56482. if (!this.name) {
  56483. return null;
  56484. }
  56485. var serializationObject = _super.prototype.serialize.call(this);
  56486. serializationObject.renderTargetSize = this.getRenderSize();
  56487. serializationObject.renderList = [];
  56488. if (this.renderList) {
  56489. for (var index = 0; index < this.renderList.length; index++) {
  56490. serializationObject.renderList.push(this.renderList[index].id);
  56491. }
  56492. }
  56493. return serializationObject;
  56494. };
  56495. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  56496. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  56497. var objBuffer = this.getInternalTexture();
  56498. var scene = this.getScene();
  56499. if (objBuffer && scene) {
  56500. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  56501. }
  56502. };
  56503. RenderTargetTexture.prototype.dispose = function () {
  56504. if (this._postProcessManager) {
  56505. this._postProcessManager.dispose();
  56506. this._postProcessManager = null;
  56507. }
  56508. this.clearPostProcesses(true);
  56509. if (this._resizeObserver) {
  56510. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  56511. this._resizeObserver = null;
  56512. }
  56513. this.renderList = null;
  56514. // Remove from custom render targets
  56515. var scene = this.getScene();
  56516. if (!scene) {
  56517. return;
  56518. }
  56519. var index = scene.customRenderTargets.indexOf(this);
  56520. if (index >= 0) {
  56521. scene.customRenderTargets.splice(index, 1);
  56522. }
  56523. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  56524. var camera = _a[_i];
  56525. index = camera.customRenderTargets.indexOf(this);
  56526. if (index >= 0) {
  56527. camera.customRenderTargets.splice(index, 1);
  56528. }
  56529. }
  56530. _super.prototype.dispose.call(this);
  56531. };
  56532. RenderTargetTexture.prototype._rebuild = function () {
  56533. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  56534. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  56535. }
  56536. if (this._postProcessManager) {
  56537. this._postProcessManager._rebuild();
  56538. }
  56539. };
  56540. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  56541. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  56542. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  56543. return RenderTargetTexture;
  56544. }(BABYLON.Texture));
  56545. BABYLON.RenderTargetTexture = RenderTargetTexture;
  56546. })(BABYLON || (BABYLON = {}));
  56547. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  56548. var BABYLON;
  56549. (function (BABYLON) {
  56550. ;
  56551. var MultiRenderTarget = /** @class */ (function (_super) {
  56552. __extends(MultiRenderTarget, _super);
  56553. function MultiRenderTarget(name, size, count, scene, options) {
  56554. var _this = this;
  56555. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  56556. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  56557. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  56558. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  56559. _this._engine = scene.getEngine();
  56560. if (!_this.isSupported) {
  56561. _this.dispose();
  56562. return;
  56563. }
  56564. var types = [];
  56565. var samplingModes = [];
  56566. for (var i = 0; i < count; i++) {
  56567. if (options && options.types && options.types[i] !== undefined) {
  56568. types.push(options.types[i]);
  56569. }
  56570. else {
  56571. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  56572. }
  56573. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  56574. samplingModes.push(options.samplingModes[i]);
  56575. }
  56576. else {
  56577. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  56578. }
  56579. }
  56580. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  56581. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  56582. _this._size = size;
  56583. _this._multiRenderTargetOptions = {
  56584. samplingModes: samplingModes,
  56585. generateMipMaps: generateMipMaps,
  56586. generateDepthBuffer: generateDepthBuffer,
  56587. generateStencilBuffer: generateStencilBuffer,
  56588. generateDepthTexture: generateDepthTexture,
  56589. types: types,
  56590. textureCount: count
  56591. };
  56592. _this._createInternalTextures();
  56593. _this._createTextures();
  56594. return _this;
  56595. }
  56596. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  56597. get: function () {
  56598. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  56599. },
  56600. enumerable: true,
  56601. configurable: true
  56602. });
  56603. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  56604. get: function () {
  56605. return this._textures;
  56606. },
  56607. enumerable: true,
  56608. configurable: true
  56609. });
  56610. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  56611. get: function () {
  56612. return this._textures[this._textures.length - 1];
  56613. },
  56614. enumerable: true,
  56615. configurable: true
  56616. });
  56617. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  56618. set: function (wrap) {
  56619. if (this._textures) {
  56620. for (var i = 0; i < this._textures.length; i++) {
  56621. this._textures[i].wrapU = wrap;
  56622. }
  56623. }
  56624. },
  56625. enumerable: true,
  56626. configurable: true
  56627. });
  56628. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  56629. set: function (wrap) {
  56630. if (this._textures) {
  56631. for (var i = 0; i < this._textures.length; i++) {
  56632. this._textures[i].wrapV = wrap;
  56633. }
  56634. }
  56635. },
  56636. enumerable: true,
  56637. configurable: true
  56638. });
  56639. MultiRenderTarget.prototype._rebuild = function () {
  56640. this.releaseInternalTextures();
  56641. this._createInternalTextures();
  56642. for (var i = 0; i < this._internalTextures.length; i++) {
  56643. var texture = this._textures[i];
  56644. texture._texture = this._internalTextures[i];
  56645. }
  56646. // Keeps references to frame buffer and stencil/depth buffer
  56647. this._texture = this._internalTextures[0];
  56648. };
  56649. MultiRenderTarget.prototype._createInternalTextures = function () {
  56650. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  56651. };
  56652. MultiRenderTarget.prototype._createTextures = function () {
  56653. this._textures = [];
  56654. for (var i = 0; i < this._internalTextures.length; i++) {
  56655. var texture = new BABYLON.Texture(null, this.getScene());
  56656. texture._texture = this._internalTextures[i];
  56657. this._textures.push(texture);
  56658. }
  56659. // Keeps references to frame buffer and stencil/depth buffer
  56660. this._texture = this._internalTextures[0];
  56661. };
  56662. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  56663. get: function () {
  56664. return this._samples;
  56665. },
  56666. set: function (value) {
  56667. if (this._samples === value) {
  56668. return;
  56669. }
  56670. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  56671. },
  56672. enumerable: true,
  56673. configurable: true
  56674. });
  56675. MultiRenderTarget.prototype.resize = function (size) {
  56676. this.releaseInternalTextures();
  56677. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  56678. this._createInternalTextures();
  56679. };
  56680. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  56681. var _this = this;
  56682. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  56683. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  56684. });
  56685. };
  56686. MultiRenderTarget.prototype.dispose = function () {
  56687. this.releaseInternalTextures();
  56688. _super.prototype.dispose.call(this);
  56689. };
  56690. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  56691. if (!this._internalTextures) {
  56692. return;
  56693. }
  56694. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  56695. if (this._internalTextures[i] !== undefined) {
  56696. this._internalTextures[i].dispose();
  56697. this._internalTextures.splice(i, 1);
  56698. }
  56699. }
  56700. };
  56701. return MultiRenderTarget;
  56702. }(BABYLON.RenderTargetTexture));
  56703. BABYLON.MultiRenderTarget = MultiRenderTarget;
  56704. })(BABYLON || (BABYLON = {}));
  56705. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  56706. var BABYLON;
  56707. (function (BABYLON) {
  56708. var MirrorTexture = /** @class */ (function (_super) {
  56709. __extends(MirrorTexture, _super);
  56710. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  56711. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  56712. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  56713. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  56714. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  56715. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  56716. _this._transformMatrix = BABYLON.Matrix.Zero();
  56717. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  56718. _this._adaptiveBlurKernel = 0;
  56719. _this._blurKernelX = 0;
  56720. _this._blurKernelY = 0;
  56721. _this._blurRatio = 1.0;
  56722. _this.ignoreCameraViewport = true;
  56723. _this.onBeforeRenderObservable.add(function () {
  56724. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  56725. _this._savedViewMatrix = scene.getViewMatrix();
  56726. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  56727. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  56728. scene.clipPlane = _this.mirrorPlane;
  56729. scene.getEngine().cullBackFaces = false;
  56730. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  56731. });
  56732. _this.onAfterRenderObservable.add(function () {
  56733. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  56734. scene.getEngine().cullBackFaces = true;
  56735. scene._mirroredCameraPosition = null;
  56736. delete scene.clipPlane;
  56737. });
  56738. return _this;
  56739. }
  56740. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  56741. get: function () {
  56742. return this._blurRatio;
  56743. },
  56744. set: function (value) {
  56745. if (this._blurRatio === value) {
  56746. return;
  56747. }
  56748. this._blurRatio = value;
  56749. this._preparePostProcesses();
  56750. },
  56751. enumerable: true,
  56752. configurable: true
  56753. });
  56754. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  56755. set: function (value) {
  56756. this._adaptiveBlurKernel = value;
  56757. this._autoComputeBlurKernel();
  56758. },
  56759. enumerable: true,
  56760. configurable: true
  56761. });
  56762. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  56763. set: function (value) {
  56764. this.blurKernelX = value;
  56765. this.blurKernelY = value;
  56766. },
  56767. enumerable: true,
  56768. configurable: true
  56769. });
  56770. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  56771. get: function () {
  56772. return this._blurKernelX;
  56773. },
  56774. set: function (value) {
  56775. if (this._blurKernelX === value) {
  56776. return;
  56777. }
  56778. this._blurKernelX = value;
  56779. this._preparePostProcesses();
  56780. },
  56781. enumerable: true,
  56782. configurable: true
  56783. });
  56784. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  56785. get: function () {
  56786. return this._blurKernelY;
  56787. },
  56788. set: function (value) {
  56789. if (this._blurKernelY === value) {
  56790. return;
  56791. }
  56792. this._blurKernelY = value;
  56793. this._preparePostProcesses();
  56794. },
  56795. enumerable: true,
  56796. configurable: true
  56797. });
  56798. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  56799. var engine = this.getScene().getEngine();
  56800. var dw = this.getRenderWidth() / engine.getRenderWidth();
  56801. var dh = this.getRenderHeight() / engine.getRenderHeight();
  56802. this.blurKernelX = this._adaptiveBlurKernel * dw;
  56803. this.blurKernelY = this._adaptiveBlurKernel * dh;
  56804. };
  56805. MirrorTexture.prototype._onRatioRescale = function () {
  56806. if (this._sizeRatio) {
  56807. this.resize(this._initialSizeParameter);
  56808. if (!this._adaptiveBlurKernel) {
  56809. this._preparePostProcesses();
  56810. }
  56811. }
  56812. if (this._adaptiveBlurKernel) {
  56813. this._autoComputeBlurKernel();
  56814. }
  56815. };
  56816. MirrorTexture.prototype._preparePostProcesses = function () {
  56817. this.clearPostProcesses(true);
  56818. if (this._blurKernelX && this._blurKernelY) {
  56819. var engine = this.getScene().getEngine();
  56820. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  56821. 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);
  56822. this._blurX.autoClear = false;
  56823. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  56824. this._blurX.inputTexture = this._texture;
  56825. }
  56826. else {
  56827. this._blurX.alwaysForcePOT = true;
  56828. }
  56829. 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);
  56830. this._blurY.autoClear = false;
  56831. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  56832. this.addPostProcess(this._blurX);
  56833. this.addPostProcess(this._blurY);
  56834. }
  56835. else {
  56836. if (this._blurY) {
  56837. this.removePostProcess(this._blurY);
  56838. this._blurY.dispose();
  56839. this._blurY = null;
  56840. }
  56841. if (this._blurX) {
  56842. this.removePostProcess(this._blurX);
  56843. this._blurX.dispose();
  56844. this._blurX = null;
  56845. }
  56846. }
  56847. };
  56848. MirrorTexture.prototype.clone = function () {
  56849. var scene = this.getScene();
  56850. if (!scene) {
  56851. return this;
  56852. }
  56853. var textureSize = this.getSize();
  56854. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  56855. // Base texture
  56856. newTexture.hasAlpha = this.hasAlpha;
  56857. newTexture.level = this.level;
  56858. // Mirror Texture
  56859. newTexture.mirrorPlane = this.mirrorPlane.clone();
  56860. if (this.renderList) {
  56861. newTexture.renderList = this.renderList.slice(0);
  56862. }
  56863. return newTexture;
  56864. };
  56865. MirrorTexture.prototype.serialize = function () {
  56866. if (!this.name) {
  56867. return null;
  56868. }
  56869. var serializationObject = _super.prototype.serialize.call(this);
  56870. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  56871. return serializationObject;
  56872. };
  56873. return MirrorTexture;
  56874. }(BABYLON.RenderTargetTexture));
  56875. BABYLON.MirrorTexture = MirrorTexture;
  56876. })(BABYLON || (BABYLON = {}));
  56877. //# sourceMappingURL=babylon.mirrorTexture.js.map
  56878. var BABYLON;
  56879. (function (BABYLON) {
  56880. /**
  56881. * Creates a refraction texture used by refraction channel of the standard material.
  56882. * @param name the texture name
  56883. * @param size size of the underlying texture
  56884. * @param scene root scene
  56885. */
  56886. var RefractionTexture = /** @class */ (function (_super) {
  56887. __extends(RefractionTexture, _super);
  56888. function RefractionTexture(name, size, scene, generateMipMaps) {
  56889. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  56890. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  56891. _this.depth = 2.0;
  56892. _this.onBeforeRenderObservable.add(function () {
  56893. scene.clipPlane = _this.refractionPlane;
  56894. });
  56895. _this.onAfterRenderObservable.add(function () {
  56896. delete scene.clipPlane;
  56897. });
  56898. return _this;
  56899. }
  56900. RefractionTexture.prototype.clone = function () {
  56901. var scene = this.getScene();
  56902. if (!scene) {
  56903. return this;
  56904. }
  56905. var textureSize = this.getSize();
  56906. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  56907. // Base texture
  56908. newTexture.hasAlpha = this.hasAlpha;
  56909. newTexture.level = this.level;
  56910. // Refraction Texture
  56911. newTexture.refractionPlane = this.refractionPlane.clone();
  56912. if (this.renderList) {
  56913. newTexture.renderList = this.renderList.slice(0);
  56914. }
  56915. newTexture.depth = this.depth;
  56916. return newTexture;
  56917. };
  56918. RefractionTexture.prototype.serialize = function () {
  56919. if (!this.name) {
  56920. return null;
  56921. }
  56922. var serializationObject = _super.prototype.serialize.call(this);
  56923. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  56924. serializationObject.depth = this.depth;
  56925. return serializationObject;
  56926. };
  56927. return RefractionTexture;
  56928. }(BABYLON.RenderTargetTexture));
  56929. BABYLON.RefractionTexture = RefractionTexture;
  56930. })(BABYLON || (BABYLON = {}));
  56931. //# sourceMappingURL=babylon.refractionTexture.js.map
  56932. var BABYLON;
  56933. (function (BABYLON) {
  56934. var DynamicTexture = /** @class */ (function (_super) {
  56935. __extends(DynamicTexture, _super);
  56936. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  56937. if (scene === void 0) { scene = null; }
  56938. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  56939. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  56940. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  56941. _this.name = name;
  56942. _this._engine = _this.getScene().getEngine();
  56943. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  56944. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  56945. _this._generateMipMaps = generateMipMaps;
  56946. if (options.getContext) {
  56947. _this._canvas = options;
  56948. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  56949. }
  56950. else {
  56951. _this._canvas = document.createElement("canvas");
  56952. if (options.width) {
  56953. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  56954. }
  56955. else {
  56956. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  56957. }
  56958. }
  56959. var textureSize = _this.getSize();
  56960. _this._canvas.width = textureSize.width;
  56961. _this._canvas.height = textureSize.height;
  56962. _this._context = _this._canvas.getContext("2d");
  56963. return _this;
  56964. }
  56965. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  56966. get: function () {
  56967. return true;
  56968. },
  56969. enumerable: true,
  56970. configurable: true
  56971. });
  56972. DynamicTexture.prototype._recreate = function (textureSize) {
  56973. this._canvas.width = textureSize.width;
  56974. this._canvas.height = textureSize.height;
  56975. this.releaseInternalTexture();
  56976. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  56977. };
  56978. DynamicTexture.prototype.scale = function (ratio) {
  56979. var textureSize = this.getSize();
  56980. textureSize.width *= ratio;
  56981. textureSize.height *= ratio;
  56982. this._recreate(textureSize);
  56983. };
  56984. DynamicTexture.prototype.scaleTo = function (width, height) {
  56985. var textureSize = this.getSize();
  56986. textureSize.width = width;
  56987. textureSize.height = height;
  56988. this._recreate(textureSize);
  56989. };
  56990. DynamicTexture.prototype.getContext = function () {
  56991. return this._context;
  56992. };
  56993. DynamicTexture.prototype.clear = function () {
  56994. var size = this.getSize();
  56995. this._context.fillRect(0, 0, size.width, size.height);
  56996. };
  56997. DynamicTexture.prototype.update = function (invertY) {
  56998. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format || undefined);
  56999. };
  57000. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  57001. if (update === void 0) { update = true; }
  57002. var size = this.getSize();
  57003. if (clearColor) {
  57004. this._context.fillStyle = clearColor;
  57005. this._context.fillRect(0, 0, size.width, size.height);
  57006. }
  57007. this._context.font = font;
  57008. if (x === null || x === undefined) {
  57009. var textSize = this._context.measureText(text);
  57010. x = (size.width - textSize.width) / 2;
  57011. }
  57012. if (y === null || y === undefined) {
  57013. var fontSize = parseInt((font.replace(/\D/g, '')));
  57014. ;
  57015. y = (size.height / 2) + (fontSize / 3.65);
  57016. }
  57017. this._context.fillStyle = color;
  57018. this._context.fillText(text, x, y);
  57019. if (update) {
  57020. this.update(invertY);
  57021. }
  57022. };
  57023. DynamicTexture.prototype.clone = function () {
  57024. var scene = this.getScene();
  57025. if (!scene) {
  57026. return this;
  57027. }
  57028. var textureSize = this.getSize();
  57029. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  57030. // Base texture
  57031. newTexture.hasAlpha = this.hasAlpha;
  57032. newTexture.level = this.level;
  57033. // Dynamic Texture
  57034. newTexture.wrapU = this.wrapU;
  57035. newTexture.wrapV = this.wrapV;
  57036. return newTexture;
  57037. };
  57038. DynamicTexture.prototype._rebuild = function () {
  57039. this.update();
  57040. };
  57041. return DynamicTexture;
  57042. }(BABYLON.Texture));
  57043. BABYLON.DynamicTexture = DynamicTexture;
  57044. })(BABYLON || (BABYLON = {}));
  57045. //# sourceMappingURL=babylon.dynamicTexture.js.map
  57046. var BABYLON;
  57047. (function (BABYLON) {
  57048. var VideoTexture = /** @class */ (function (_super) {
  57049. __extends(VideoTexture, _super);
  57050. /**
  57051. * Creates a video texture.
  57052. * Sample : https://doc.babylonjs.com/how_to/video_texture
  57053. * @param {string | null} name optional name, will detect from video source, if not defined
  57054. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  57055. * @param {BABYLON.Scene} scene is obviously the current scene.
  57056. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  57057. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  57058. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  57059. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  57060. */
  57061. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  57062. if (generateMipMaps === void 0) { generateMipMaps = false; }
  57063. if (invertY === void 0) { invertY = false; }
  57064. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  57065. if (settings === void 0) { settings = {
  57066. autoPlay: true,
  57067. loop: true,
  57068. autoUpdateTexture: true,
  57069. }; }
  57070. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  57071. _this._createInternalTexture = function () {
  57072. if (_this._texture != null) {
  57073. return;
  57074. }
  57075. if (!_this._engine.needPOTTextures ||
  57076. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  57077. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  57078. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  57079. }
  57080. else {
  57081. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57082. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57083. _this._generateMipMaps = false;
  57084. }
  57085. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  57086. _this._texture.isReady = true;
  57087. _this._updateInternalTexture();
  57088. };
  57089. _this.reset = function () {
  57090. if (_this._texture == null) {
  57091. return;
  57092. }
  57093. _this._texture.dispose();
  57094. _this._texture = null;
  57095. };
  57096. _this._updateInternalTexture = function (e) {
  57097. if (_this._texture == null || !_this._texture.isReady) {
  57098. return;
  57099. }
  57100. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  57101. return;
  57102. }
  57103. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  57104. };
  57105. _this._engine = _this.getScene().getEngine();
  57106. _this._generateMipMaps = generateMipMaps;
  57107. _this._samplingMode = samplingMode;
  57108. _this.autoUpdateTexture = settings.autoUpdateTexture;
  57109. _this.name = name || _this._getName(src);
  57110. _this.video = _this._getVideo(src);
  57111. if (settings.autoPlay !== undefined) {
  57112. _this.video.autoplay = settings.autoPlay;
  57113. }
  57114. if (settings.loop !== undefined) {
  57115. _this.video.loop = settings.loop;
  57116. }
  57117. _this.video.addEventListener("canplay", _this._createInternalTexture);
  57118. _this.video.addEventListener("paused", _this._updateInternalTexture);
  57119. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  57120. _this.video.addEventListener("emptied", _this.reset);
  57121. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  57122. _this._createInternalTexture();
  57123. }
  57124. return _this;
  57125. }
  57126. VideoTexture.prototype._getName = function (src) {
  57127. if (src instanceof HTMLVideoElement) {
  57128. return src.currentSrc;
  57129. }
  57130. if (typeof src === "object") {
  57131. return src.toString();
  57132. }
  57133. return src;
  57134. };
  57135. ;
  57136. VideoTexture.prototype._getVideo = function (src) {
  57137. if (src instanceof HTMLVideoElement) {
  57138. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  57139. return src;
  57140. }
  57141. var video = document.createElement("video");
  57142. if (typeof src === "string") {
  57143. BABYLON.Tools.SetCorsBehavior(src, video);
  57144. video.src = src;
  57145. }
  57146. else {
  57147. BABYLON.Tools.SetCorsBehavior(src[0], video);
  57148. src.forEach(function (url) {
  57149. var source = document.createElement("source");
  57150. source.src = url;
  57151. video.appendChild(source);
  57152. });
  57153. }
  57154. return video;
  57155. };
  57156. ;
  57157. /**
  57158. * Internal method to initiate `update`.
  57159. */
  57160. VideoTexture.prototype._rebuild = function () {
  57161. this.update();
  57162. };
  57163. /**
  57164. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  57165. */
  57166. VideoTexture.prototype.update = function () {
  57167. if (!this.autoUpdateTexture) {
  57168. // Expecting user to call `updateTexture` manually
  57169. return;
  57170. }
  57171. this.updateTexture(true);
  57172. };
  57173. /**
  57174. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  57175. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  57176. */
  57177. VideoTexture.prototype.updateTexture = function (isVisible) {
  57178. if (!isVisible) {
  57179. return;
  57180. }
  57181. if (this.video.paused) {
  57182. return;
  57183. }
  57184. this._updateInternalTexture();
  57185. };
  57186. /**
  57187. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  57188. * @param url New url.
  57189. */
  57190. VideoTexture.prototype.updateURL = function (url) {
  57191. this.video.src = url;
  57192. };
  57193. VideoTexture.prototype.dispose = function () {
  57194. _super.prototype.dispose.call(this);
  57195. this.video.removeEventListener("canplay", this._createInternalTexture);
  57196. this.video.removeEventListener("paused", this._updateInternalTexture);
  57197. this.video.removeEventListener("seeked", this._updateInternalTexture);
  57198. this.video.removeEventListener("emptied", this.reset);
  57199. };
  57200. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  57201. var video = document.createElement("video");
  57202. var constraintsDeviceId;
  57203. if (constraints && constraints.deviceId) {
  57204. constraintsDeviceId = {
  57205. exact: constraints.deviceId,
  57206. };
  57207. }
  57208. navigator.getUserMedia =
  57209. navigator.getUserMedia ||
  57210. navigator.webkitGetUserMedia ||
  57211. navigator.mozGetUserMedia ||
  57212. navigator.msGetUserMedia;
  57213. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  57214. if (navigator.getUserMedia) {
  57215. navigator.getUserMedia({
  57216. video: {
  57217. deviceId: constraintsDeviceId,
  57218. width: {
  57219. min: (constraints && constraints.minWidth) || 256,
  57220. max: (constraints && constraints.maxWidth) || 640,
  57221. },
  57222. height: {
  57223. min: (constraints && constraints.minHeight) || 256,
  57224. max: (constraints && constraints.maxHeight) || 480,
  57225. },
  57226. },
  57227. }, function (stream) {
  57228. if (video.mozSrcObject !== undefined) {
  57229. // hack for Firefox < 19
  57230. video.mozSrcObject = stream;
  57231. }
  57232. else {
  57233. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  57234. }
  57235. video.play();
  57236. if (onReady) {
  57237. onReady(new VideoTexture("video", video, scene, true, true));
  57238. }
  57239. }, function (e) {
  57240. BABYLON.Tools.Error(e.name);
  57241. });
  57242. }
  57243. };
  57244. return VideoTexture;
  57245. }(BABYLON.Texture));
  57246. BABYLON.VideoTexture = VideoTexture;
  57247. })(BABYLON || (BABYLON = {}));
  57248. //# sourceMappingURL=babylon.videoTexture.js.map
  57249. var BABYLON;
  57250. (function (BABYLON) {
  57251. var RawTexture = /** @class */ (function (_super) {
  57252. __extends(RawTexture, _super);
  57253. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  57254. if (generateMipMaps === void 0) { generateMipMaps = true; }
  57255. if (invertY === void 0) { invertY = false; }
  57256. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  57257. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  57258. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  57259. _this.format = format;
  57260. _this._engine = scene.getEngine();
  57261. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  57262. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57263. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57264. return _this;
  57265. }
  57266. RawTexture.prototype.update = function (data) {
  57267. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  57268. };
  57269. // Statics
  57270. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  57271. if (generateMipMaps === void 0) { generateMipMaps = true; }
  57272. if (invertY === void 0) { invertY = false; }
  57273. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  57274. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  57275. };
  57276. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  57277. if (generateMipMaps === void 0) { generateMipMaps = true; }
  57278. if (invertY === void 0) { invertY = false; }
  57279. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  57280. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  57281. };
  57282. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  57283. if (generateMipMaps === void 0) { generateMipMaps = true; }
  57284. if (invertY === void 0) { invertY = false; }
  57285. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  57286. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  57287. };
  57288. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  57289. if (generateMipMaps === void 0) { generateMipMaps = true; }
  57290. if (invertY === void 0) { invertY = false; }
  57291. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  57292. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  57293. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  57294. };
  57295. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  57296. if (generateMipMaps === void 0) { generateMipMaps = true; }
  57297. if (invertY === void 0) { invertY = false; }
  57298. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  57299. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  57300. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  57301. };
  57302. return RawTexture;
  57303. }(BABYLON.Texture));
  57304. BABYLON.RawTexture = RawTexture;
  57305. })(BABYLON || (BABYLON = {}));
  57306. //# sourceMappingURL=babylon.rawTexture.js.map
  57307. var BABYLON;
  57308. (function (BABYLON) {
  57309. /**
  57310. * PostProcess can be used to apply a shader to a texture after it has been rendered
  57311. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  57312. */
  57313. var PostProcess = /** @class */ (function () {
  57314. /**
  57315. * Creates a new instance of @see PostProcess
  57316. * @param name The name of the PostProcess.
  57317. * @param fragmentUrl The url of the fragment shader to be used.
  57318. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  57319. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  57320. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  57321. * @param camera The camera to apply the render pass to.
  57322. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  57323. * @param engine The engine which the post process will be applied. (default: current engine)
  57324. * @param reusable If the post process can be reused on the same frame. (default: false)
  57325. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  57326. * @param textureType Type of textures used when performing the post process. (default: 0)
  57327. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  57328. * @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
  57329. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  57330. */
  57331. function PostProcess(/** Name of the PostProcess. */ name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  57332. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  57333. if (defines === void 0) { defines = null; }
  57334. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  57335. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  57336. if (blockCompilation === void 0) { blockCompilation = false; }
  57337. this.name = name;
  57338. /**
  57339. * Width of the texture to apply the post process on
  57340. */
  57341. this.width = -1;
  57342. /**
  57343. * Height of the texture to apply the post process on
  57344. */
  57345. this.height = -1;
  57346. /**
  57347. * If the buffer needs to be cleared before applying the post process. (default: true)
  57348. * Should be set to false if shader will overwrite all previous pixels.
  57349. */
  57350. this.autoClear = true;
  57351. /**
  57352. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  57353. */
  57354. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  57355. /**
  57356. * Animations to be used for the post processing
  57357. */
  57358. this.animations = new Array();
  57359. /**
  57360. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  57361. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  57362. */
  57363. this.enablePixelPerfectMode = false;
  57364. /**
  57365. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  57366. */
  57367. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  57368. /**
  57369. * Force textures to be a power of two (default: false)
  57370. */
  57371. this.alwaysForcePOT = false;
  57372. /**
  57373. * Number of sample textures (default: 1)
  57374. */
  57375. this.samples = 1;
  57376. /**
  57377. * Modify the scale of the post process to be the same as the viewport (default: false)
  57378. */
  57379. this.adaptScaleToCurrentViewport = false;
  57380. this._reusable = false;
  57381. /**
  57382. * Smart array of input and output textures for the post process.
  57383. */
  57384. this._textures = new BABYLON.SmartArray(2);
  57385. /**
  57386. * The index in _textures that corresponds to the output texture.
  57387. */
  57388. this._currentRenderTextureInd = 0;
  57389. this._scaleRatio = new BABYLON.Vector2(1, 1);
  57390. this._texelSize = BABYLON.Vector2.Zero();
  57391. // Events
  57392. /**
  57393. * An event triggered when the postprocess is activated.
  57394. * @type {BABYLON.Observable}
  57395. */
  57396. this.onActivateObservable = new BABYLON.Observable();
  57397. /**
  57398. * An event triggered when the postprocess changes its size.
  57399. * @type {BABYLON.Observable}
  57400. */
  57401. this.onSizeChangedObservable = new BABYLON.Observable();
  57402. /**
  57403. * An event triggered when the postprocess applies its effect.
  57404. * @type {BABYLON.Observable}
  57405. */
  57406. this.onApplyObservable = new BABYLON.Observable();
  57407. /**
  57408. * An event triggered before rendering the postprocess
  57409. * @type {BABYLON.Observable}
  57410. */
  57411. this.onBeforeRenderObservable = new BABYLON.Observable();
  57412. /**
  57413. * An event triggered after rendering the postprocess
  57414. * @type {BABYLON.Observable}
  57415. */
  57416. this.onAfterRenderObservable = new BABYLON.Observable();
  57417. if (camera != null) {
  57418. this._camera = camera;
  57419. this._scene = camera.getScene();
  57420. camera.attachPostProcess(this);
  57421. this._engine = this._scene.getEngine();
  57422. this._scene.postProcesses.push(this);
  57423. }
  57424. else if (engine) {
  57425. this._engine = engine;
  57426. this._engine.postProcesses.push(this);
  57427. }
  57428. this._options = options;
  57429. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  57430. this._reusable = reusable || false;
  57431. this._textureType = textureType;
  57432. this._samplers = samplers || [];
  57433. this._samplers.push("textureSampler");
  57434. this._fragmentUrl = fragmentUrl;
  57435. this._vertexUrl = vertexUrl;
  57436. this._parameters = parameters || [];
  57437. this._parameters.push("scale");
  57438. this._indexParameters = indexParameters;
  57439. if (!blockCompilation) {
  57440. this.updateEffect(defines);
  57441. }
  57442. }
  57443. Object.defineProperty(PostProcess.prototype, "onActivate", {
  57444. /**
  57445. * A function that is added to the onActivateObservable
  57446. */
  57447. set: function (callback) {
  57448. if (this._onActivateObserver) {
  57449. this.onActivateObservable.remove(this._onActivateObserver);
  57450. }
  57451. if (callback) {
  57452. this._onActivateObserver = this.onActivateObservable.add(callback);
  57453. }
  57454. },
  57455. enumerable: true,
  57456. configurable: true
  57457. });
  57458. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  57459. /**
  57460. * A function that is added to the onSizeChangedObservable
  57461. */
  57462. set: function (callback) {
  57463. if (this._onSizeChangedObserver) {
  57464. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  57465. }
  57466. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  57467. },
  57468. enumerable: true,
  57469. configurable: true
  57470. });
  57471. Object.defineProperty(PostProcess.prototype, "onApply", {
  57472. /**
  57473. * A function that is added to the onApplyObservable
  57474. */
  57475. set: function (callback) {
  57476. if (this._onApplyObserver) {
  57477. this.onApplyObservable.remove(this._onApplyObserver);
  57478. }
  57479. this._onApplyObserver = this.onApplyObservable.add(callback);
  57480. },
  57481. enumerable: true,
  57482. configurable: true
  57483. });
  57484. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  57485. /**
  57486. * A function that is added to the onBeforeRenderObservable
  57487. */
  57488. set: function (callback) {
  57489. if (this._onBeforeRenderObserver) {
  57490. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  57491. }
  57492. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  57493. },
  57494. enumerable: true,
  57495. configurable: true
  57496. });
  57497. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  57498. /**
  57499. * A function that is added to the onAfterRenderObservable
  57500. */
  57501. set: function (callback) {
  57502. if (this._onAfterRenderObserver) {
  57503. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  57504. }
  57505. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  57506. },
  57507. enumerable: true,
  57508. configurable: true
  57509. });
  57510. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  57511. /**
  57512. * 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
  57513. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  57514. */
  57515. get: function () {
  57516. return this._textures.data[this._currentRenderTextureInd];
  57517. },
  57518. set: function (value) {
  57519. this._forcedOutputTexture = value;
  57520. },
  57521. enumerable: true,
  57522. configurable: true
  57523. });
  57524. /**
  57525. * Gets the camera which post process is applied to.
  57526. * @returns The camera the post process is applied to.
  57527. */
  57528. PostProcess.prototype.getCamera = function () {
  57529. return this._camera;
  57530. };
  57531. Object.defineProperty(PostProcess.prototype, "texelSize", {
  57532. /**
  57533. * Gets the texel size of the postprocess.
  57534. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  57535. */
  57536. get: function () {
  57537. if (this._shareOutputWithPostProcess) {
  57538. return this._shareOutputWithPostProcess.texelSize;
  57539. }
  57540. if (this._forcedOutputTexture) {
  57541. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  57542. }
  57543. return this._texelSize;
  57544. },
  57545. enumerable: true,
  57546. configurable: true
  57547. });
  57548. /**
  57549. * Gets the engine which this post process belongs to.
  57550. * @returns The engine the post process was enabled with.
  57551. */
  57552. PostProcess.prototype.getEngine = function () {
  57553. return this._engine;
  57554. };
  57555. /**
  57556. * The effect that is created when initializing the post process.
  57557. * @returns The created effect corrisponding the the postprocess.
  57558. */
  57559. PostProcess.prototype.getEffect = function () {
  57560. return this._effect;
  57561. };
  57562. /**
  57563. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  57564. * @param postProcess The post process to share the output with.
  57565. * @returns This post process.
  57566. */
  57567. PostProcess.prototype.shareOutputWith = function (postProcess) {
  57568. this._disposeTextures();
  57569. this._shareOutputWithPostProcess = postProcess;
  57570. return this;
  57571. };
  57572. /**
  57573. * Updates the effect with the current post process compile time values and recompiles the shader.
  57574. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  57575. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  57576. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  57577. * @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
  57578. * @param onCompiled Called when the shader has been compiled.
  57579. * @param onError Called if there is an error when compiling a shader.
  57580. */
  57581. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  57582. if (defines === void 0) { defines = null; }
  57583. if (uniforms === void 0) { uniforms = null; }
  57584. if (samplers === void 0) { samplers = null; }
  57585. 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);
  57586. };
  57587. /**
  57588. * The post process is reusable if it can be used multiple times within one frame.
  57589. * @returns If the post process is reusable
  57590. */
  57591. PostProcess.prototype.isReusable = function () {
  57592. return this._reusable;
  57593. };
  57594. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  57595. PostProcess.prototype.markTextureDirty = function () {
  57596. this.width = -1;
  57597. };
  57598. /**
  57599. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  57600. * 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.
  57601. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  57602. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  57603. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  57604. */
  57605. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  57606. var _this = this;
  57607. if (sourceTexture === void 0) { sourceTexture = null; }
  57608. camera = camera || this._camera;
  57609. var scene = camera.getScene();
  57610. var engine = scene.getEngine();
  57611. var maxSize = engine.getCaps().maxTextureSize;
  57612. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  57613. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  57614. var desiredWidth = (this._options.width || requiredWidth);
  57615. var desiredHeight = this._options.height || requiredHeight;
  57616. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  57617. if (this.adaptScaleToCurrentViewport) {
  57618. var currentViewport = engine.currentViewport;
  57619. if (currentViewport) {
  57620. desiredWidth *= currentViewport.width;
  57621. desiredHeight *= currentViewport.height;
  57622. }
  57623. }
  57624. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  57625. if (!this._options.width) {
  57626. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  57627. }
  57628. if (!this._options.height) {
  57629. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  57630. }
  57631. }
  57632. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  57633. if (this._textures.length > 0) {
  57634. for (var i = 0; i < this._textures.length; i++) {
  57635. this._engine._releaseTexture(this._textures.data[i]);
  57636. }
  57637. this._textures.reset();
  57638. }
  57639. this.width = desiredWidth;
  57640. this.height = desiredHeight;
  57641. var textureSize = { width: this.width, height: this.height };
  57642. var textureOptions = {
  57643. generateMipMaps: false,
  57644. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  57645. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  57646. samplingMode: this.renderTargetSamplingMode,
  57647. type: this._textureType
  57648. };
  57649. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  57650. if (this._reusable) {
  57651. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  57652. }
  57653. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  57654. this.onSizeChangedObservable.notifyObservers(this);
  57655. }
  57656. this._textures.forEach(function (texture) {
  57657. if (texture.samples !== _this.samples) {
  57658. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  57659. }
  57660. });
  57661. }
  57662. var target;
  57663. if (this._shareOutputWithPostProcess) {
  57664. target = this._shareOutputWithPostProcess.inputTexture;
  57665. }
  57666. else if (this._forcedOutputTexture) {
  57667. target = this._forcedOutputTexture;
  57668. this.width = this._forcedOutputTexture.width;
  57669. this.height = this._forcedOutputTexture.height;
  57670. }
  57671. else {
  57672. target = this.inputTexture;
  57673. }
  57674. // Bind the input of this post process to be used as the output of the previous post process.
  57675. if (this.enablePixelPerfectMode) {
  57676. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  57677. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true);
  57678. }
  57679. else {
  57680. this._scaleRatio.copyFromFloats(1, 1);
  57681. this._engine.bindFramebuffer(target, 0, undefined, undefined, true);
  57682. }
  57683. this.onActivateObservable.notifyObservers(camera);
  57684. // Clear
  57685. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  57686. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  57687. }
  57688. if (this._reusable) {
  57689. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  57690. }
  57691. };
  57692. Object.defineProperty(PostProcess.prototype, "isSupported", {
  57693. /**
  57694. * If the post process is supported.
  57695. */
  57696. get: function () {
  57697. return this._effect.isSupported;
  57698. },
  57699. enumerable: true,
  57700. configurable: true
  57701. });
  57702. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  57703. /**
  57704. * The aspect ratio of the output texture.
  57705. */
  57706. get: function () {
  57707. if (this._shareOutputWithPostProcess) {
  57708. return this._shareOutputWithPostProcess.aspectRatio;
  57709. }
  57710. if (this._forcedOutputTexture) {
  57711. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  57712. }
  57713. return this.width / this.height;
  57714. },
  57715. enumerable: true,
  57716. configurable: true
  57717. });
  57718. /**
  57719. * Get a value indicating if the post-process is ready to be used
  57720. * @returns true if the post-process is ready (shader is compiled)
  57721. */
  57722. PostProcess.prototype.isReady = function () {
  57723. return this._effect && this._effect.isReady();
  57724. };
  57725. /**
  57726. * Binds all textures and uniforms to the shader, this will be run on every pass.
  57727. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  57728. */
  57729. PostProcess.prototype.apply = function () {
  57730. // Check
  57731. if (!this._effect || !this._effect.isReady())
  57732. return null;
  57733. // States
  57734. this._engine.enableEffect(this._effect);
  57735. this._engine.setState(false);
  57736. this._engine.setDepthBuffer(false);
  57737. this._engine.setDepthWrite(false);
  57738. // Alpha
  57739. this._engine.setAlphaMode(this.alphaMode);
  57740. if (this.alphaConstants) {
  57741. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  57742. }
  57743. // Bind the output texture of the preivous post process as the input to this post process.
  57744. var source;
  57745. if (this._shareOutputWithPostProcess) {
  57746. source = this._shareOutputWithPostProcess.inputTexture;
  57747. }
  57748. else if (this._forcedOutputTexture) {
  57749. source = this._forcedOutputTexture;
  57750. }
  57751. else {
  57752. source = this.inputTexture;
  57753. }
  57754. this._effect._bindTexture("textureSampler", source);
  57755. // Parameters
  57756. this._effect.setVector2("scale", this._scaleRatio);
  57757. this.onApplyObservable.notifyObservers(this._effect);
  57758. return this._effect;
  57759. };
  57760. PostProcess.prototype._disposeTextures = function () {
  57761. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  57762. return;
  57763. }
  57764. if (this._textures.length > 0) {
  57765. for (var i = 0; i < this._textures.length; i++) {
  57766. this._engine._releaseTexture(this._textures.data[i]);
  57767. }
  57768. }
  57769. this._textures.dispose();
  57770. };
  57771. /**
  57772. * Disposes the post process.
  57773. * @param camera The camera to dispose the post process on.
  57774. */
  57775. PostProcess.prototype.dispose = function (camera) {
  57776. camera = camera || this._camera;
  57777. this._disposeTextures();
  57778. if (this._scene) {
  57779. var index_1 = this._scene.postProcesses.indexOf(this);
  57780. if (index_1 !== -1) {
  57781. this._scene.postProcesses.splice(index_1, 1);
  57782. }
  57783. }
  57784. else {
  57785. var index_2 = this._engine.postProcesses.indexOf(this);
  57786. if (index_2 !== -1) {
  57787. this._engine.postProcesses.splice(index_2, 1);
  57788. }
  57789. }
  57790. if (!camera) {
  57791. return;
  57792. }
  57793. camera.detachPostProcess(this);
  57794. var index = camera._postProcesses.indexOf(this);
  57795. if (index === 0 && camera._postProcesses.length > 0) {
  57796. this._camera._postProcesses[0].markTextureDirty();
  57797. }
  57798. this.onActivateObservable.clear();
  57799. this.onAfterRenderObservable.clear();
  57800. this.onApplyObservable.clear();
  57801. this.onBeforeRenderObservable.clear();
  57802. this.onSizeChangedObservable.clear();
  57803. };
  57804. return PostProcess;
  57805. }());
  57806. BABYLON.PostProcess = PostProcess;
  57807. })(BABYLON || (BABYLON = {}));
  57808. //# sourceMappingURL=babylon.postProcess.js.map
  57809. var BABYLON;
  57810. (function (BABYLON) {
  57811. var PassPostProcess = /** @class */ (function (_super) {
  57812. __extends(PassPostProcess, _super);
  57813. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  57814. if (camera === void 0) { camera = null; }
  57815. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  57816. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType) || this;
  57817. }
  57818. return PassPostProcess;
  57819. }(BABYLON.PostProcess));
  57820. BABYLON.PassPostProcess = PassPostProcess;
  57821. })(BABYLON || (BABYLON = {}));
  57822. //# sourceMappingURL=babylon.passPostProcess.js.map
  57823. var __assign = (this && this.__assign) || Object.assign || function(t) {
  57824. for (var s, i = 1, n = arguments.length; i < n; i++) {
  57825. s = arguments[i];
  57826. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  57827. t[p] = s[p];
  57828. }
  57829. return t;
  57830. };
  57831. var BABYLON;
  57832. (function (BABYLON) {
  57833. /**
  57834. * Default implementation of @see IShadowGenerator.
  57835. * This is the main object responsible of generating shadows in the framework.
  57836. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  57837. */
  57838. var ShadowGenerator = /** @class */ (function () {
  57839. /**
  57840. * Creates a ShadowGenerator object.
  57841. * A ShadowGenerator is the required tool to use the shadows.
  57842. * Each light casting shadows needs to use its own ShadowGenerator.
  57843. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  57844. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  57845. * @param light The light object generating the shadows.
  57846. * @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.
  57847. */
  57848. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  57849. this._bias = 0.00005;
  57850. this._blurBoxOffset = 1;
  57851. this._blurScale = 2;
  57852. this._blurKernel = 1;
  57853. this._useKernelBlur = false;
  57854. this._filter = ShadowGenerator.FILTER_NONE;
  57855. this._darkness = 0;
  57856. this._transparencyShadow = false;
  57857. /**
  57858. * Controls the extent to which the shadows fade out at the edge of the frustum
  57859. * Used only by directionals and spots
  57860. */
  57861. this.frustumEdgeFalloff = 0;
  57862. /**
  57863. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  57864. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  57865. * It might on the other hand introduce peter panning.
  57866. */
  57867. this.forceBackFacesOnly = false;
  57868. this._lightDirection = BABYLON.Vector3.Zero();
  57869. this._viewMatrix = BABYLON.Matrix.Zero();
  57870. this._projectionMatrix = BABYLON.Matrix.Zero();
  57871. this._transformMatrix = BABYLON.Matrix.Zero();
  57872. this._currentFaceIndex = 0;
  57873. this._currentFaceIndexCache = 0;
  57874. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  57875. this._mapSize = mapSize;
  57876. this._light = light;
  57877. this._scene = light.getScene();
  57878. light._shadowGenerator = this;
  57879. // Texture type fallback from float to int if not supported.
  57880. var caps = this._scene.getEngine().getCaps();
  57881. if (!useFullFloatFirst) {
  57882. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  57883. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  57884. }
  57885. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  57886. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  57887. }
  57888. else {
  57889. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  57890. }
  57891. }
  57892. else {
  57893. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  57894. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  57895. }
  57896. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  57897. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  57898. }
  57899. else {
  57900. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  57901. }
  57902. }
  57903. this._initializeGenerator();
  57904. }
  57905. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  57906. /**
  57907. * Shadow generator mode None: no filtering applied.
  57908. */
  57909. get: function () {
  57910. return ShadowGenerator._FILTER_NONE;
  57911. },
  57912. enumerable: true,
  57913. configurable: true
  57914. });
  57915. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  57916. /**
  57917. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  57918. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  57919. */
  57920. get: function () {
  57921. return ShadowGenerator._FILTER_POISSONSAMPLING;
  57922. },
  57923. enumerable: true,
  57924. configurable: true
  57925. });
  57926. Object.defineProperty(ShadowGenerator, "FILTER_EXPONENTIALSHADOWMAP", {
  57927. /**
  57928. * Shadow generator mode ESM: Exponential Shadow Mapping.
  57929. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  57930. */
  57931. get: function () {
  57932. return ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP;
  57933. },
  57934. enumerable: true,
  57935. configurable: true
  57936. });
  57937. Object.defineProperty(ShadowGenerator, "FILTER_BLUREXPONENTIALSHADOWMAP", {
  57938. /**
  57939. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  57940. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  57941. */
  57942. get: function () {
  57943. return ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP;
  57944. },
  57945. enumerable: true,
  57946. configurable: true
  57947. });
  57948. Object.defineProperty(ShadowGenerator, "FILTER_CLOSEEXPONENTIALSHADOWMAP", {
  57949. /**
  57950. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  57951. * edge artifacts on steep falloff.
  57952. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  57953. */
  57954. get: function () {
  57955. return ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP;
  57956. },
  57957. enumerable: true,
  57958. configurable: true
  57959. });
  57960. Object.defineProperty(ShadowGenerator, "FILTER_BLURCLOSEEXPONENTIALSHADOWMAP", {
  57961. /**
  57962. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  57963. * edge artifacts on steep falloff.
  57964. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  57965. */
  57966. get: function () {
  57967. return ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  57968. },
  57969. enumerable: true,
  57970. configurable: true
  57971. });
  57972. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  57973. /**
  57974. * Gets the bias: offset applied on the depth preventing acnea.
  57975. */
  57976. get: function () {
  57977. return this._bias;
  57978. },
  57979. /**
  57980. * Sets the bias: offset applied on the depth preventing acnea.
  57981. */
  57982. set: function (bias) {
  57983. this._bias = bias;
  57984. },
  57985. enumerable: true,
  57986. configurable: true
  57987. });
  57988. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  57989. /**
  57990. * Gets the blur box offset: offset applied during the blur pass.
  57991. * Only usefull if useKernelBlur = false
  57992. */
  57993. get: function () {
  57994. return this._blurBoxOffset;
  57995. },
  57996. /**
  57997. * Sets the blur box offset: offset applied during the blur pass.
  57998. * Only usefull if useKernelBlur = false
  57999. */
  58000. set: function (value) {
  58001. if (this._blurBoxOffset === value) {
  58002. return;
  58003. }
  58004. this._blurBoxOffset = value;
  58005. this._disposeBlurPostProcesses();
  58006. },
  58007. enumerable: true,
  58008. configurable: true
  58009. });
  58010. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  58011. /**
  58012. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  58013. * 2 means half of the size.
  58014. */
  58015. get: function () {
  58016. return this._blurScale;
  58017. },
  58018. /**
  58019. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  58020. * 2 means half of the size.
  58021. */
  58022. set: function (value) {
  58023. if (this._blurScale === value) {
  58024. return;
  58025. }
  58026. this._blurScale = value;
  58027. this._disposeBlurPostProcesses();
  58028. },
  58029. enumerable: true,
  58030. configurable: true
  58031. });
  58032. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  58033. /**
  58034. * Gets the blur kernel: kernel size of the blur pass.
  58035. * Only usefull if useKernelBlur = true
  58036. */
  58037. get: function () {
  58038. return this._blurKernel;
  58039. },
  58040. /**
  58041. * Sets the blur kernel: kernel size of the blur pass.
  58042. * Only usefull if useKernelBlur = true
  58043. */
  58044. set: function (value) {
  58045. if (this._blurKernel === value) {
  58046. return;
  58047. }
  58048. this._blurKernel = value;
  58049. this._disposeBlurPostProcesses();
  58050. },
  58051. enumerable: true,
  58052. configurable: true
  58053. });
  58054. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  58055. /**
  58056. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  58057. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  58058. */
  58059. get: function () {
  58060. return this._useKernelBlur;
  58061. },
  58062. /**
  58063. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  58064. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  58065. */
  58066. set: function (value) {
  58067. if (this._useKernelBlur === value) {
  58068. return;
  58069. }
  58070. this._useKernelBlur = value;
  58071. this._disposeBlurPostProcesses();
  58072. },
  58073. enumerable: true,
  58074. configurable: true
  58075. });
  58076. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  58077. /**
  58078. * Gets the depth scale used in ESM mode.
  58079. */
  58080. get: function () {
  58081. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  58082. },
  58083. /**
  58084. * Sets the depth scale used in ESM mode.
  58085. * This can override the scale stored on the light.
  58086. */
  58087. set: function (value) {
  58088. this._depthScale = value;
  58089. },
  58090. enumerable: true,
  58091. configurable: true
  58092. });
  58093. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  58094. /**
  58095. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  58096. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  58097. */
  58098. get: function () {
  58099. return this._filter;
  58100. },
  58101. /**
  58102. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  58103. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  58104. */
  58105. set: function (value) {
  58106. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  58107. if (this._light.needCube()) {
  58108. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  58109. this.useExponentialShadowMap = true;
  58110. return;
  58111. }
  58112. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  58113. this.useCloseExponentialShadowMap = true;
  58114. return;
  58115. }
  58116. }
  58117. if (this._filter === value) {
  58118. return;
  58119. }
  58120. this._filter = value;
  58121. this._disposeBlurPostProcesses();
  58122. this._applyFilterValues();
  58123. this._light._markMeshesAsLightDirty();
  58124. },
  58125. enumerable: true,
  58126. configurable: true
  58127. });
  58128. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  58129. /**
  58130. * Gets if the current filter is set to Poisson Sampling aka PCF.
  58131. */
  58132. get: function () {
  58133. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  58134. },
  58135. /**
  58136. * Sets the current filter to Poisson Sampling aka PCF.
  58137. */
  58138. set: function (value) {
  58139. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  58140. return;
  58141. }
  58142. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  58143. },
  58144. enumerable: true,
  58145. configurable: true
  58146. });
  58147. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  58148. /**
  58149. * Gets if the current filter is set to VSM.
  58150. * DEPRECATED. Should use useExponentialShadowMap instead.
  58151. */
  58152. get: function () {
  58153. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  58154. return this.useExponentialShadowMap;
  58155. },
  58156. /**
  58157. * Sets the current filter is to VSM.
  58158. * DEPRECATED. Should use useExponentialShadowMap instead.
  58159. */
  58160. set: function (value) {
  58161. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  58162. this.useExponentialShadowMap = value;
  58163. },
  58164. enumerable: true,
  58165. configurable: true
  58166. });
  58167. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  58168. /**
  58169. * Gets if the current filter is set to blurred VSM.
  58170. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  58171. */
  58172. get: function () {
  58173. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  58174. return this.useBlurExponentialShadowMap;
  58175. },
  58176. /**
  58177. * Sets the current filter is to blurred VSM.
  58178. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  58179. */
  58180. set: function (value) {
  58181. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  58182. this.useBlurExponentialShadowMap = value;
  58183. },
  58184. enumerable: true,
  58185. configurable: true
  58186. });
  58187. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  58188. /**
  58189. * Gets if the current filter is set to ESM.
  58190. */
  58191. get: function () {
  58192. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  58193. },
  58194. /**
  58195. * Sets the current filter is to ESM.
  58196. */
  58197. set: function (value) {
  58198. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  58199. return;
  58200. }
  58201. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  58202. },
  58203. enumerable: true,
  58204. configurable: true
  58205. });
  58206. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  58207. /**
  58208. * Gets if the current filter is set to filtered ESM.
  58209. */
  58210. get: function () {
  58211. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  58212. },
  58213. /**
  58214. * Gets if the current filter is set to filtered ESM.
  58215. */
  58216. set: function (value) {
  58217. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  58218. return;
  58219. }
  58220. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  58221. },
  58222. enumerable: true,
  58223. configurable: true
  58224. });
  58225. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  58226. /**
  58227. * Gets if the current filter is set to "close ESM" (using the inverse of the
  58228. * exponential to prevent steep falloff artifacts).
  58229. */
  58230. get: function () {
  58231. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  58232. },
  58233. /**
  58234. * Sets the current filter to "close ESM" (using the inverse of the
  58235. * exponential to prevent steep falloff artifacts).
  58236. */
  58237. set: function (value) {
  58238. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  58239. return;
  58240. }
  58241. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  58242. },
  58243. enumerable: true,
  58244. configurable: true
  58245. });
  58246. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  58247. /**
  58248. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  58249. * exponential to prevent steep falloff artifacts).
  58250. */
  58251. get: function () {
  58252. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  58253. },
  58254. /**
  58255. * Sets the current filter to fileterd "close ESM" (using the inverse of the
  58256. * exponential to prevent steep falloff artifacts).
  58257. */
  58258. set: function (value) {
  58259. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  58260. return;
  58261. }
  58262. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  58263. },
  58264. enumerable: true,
  58265. configurable: true
  58266. });
  58267. /**
  58268. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  58269. * 0 means strongest and 1 would means no shadow.
  58270. * @returns the darkness.
  58271. */
  58272. ShadowGenerator.prototype.getDarkness = function () {
  58273. return this._darkness;
  58274. };
  58275. /**
  58276. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  58277. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  58278. * @returns the shadow generator allowing fluent coding.
  58279. */
  58280. ShadowGenerator.prototype.setDarkness = function (darkness) {
  58281. if (darkness >= 1.0)
  58282. this._darkness = 1.0;
  58283. else if (darkness <= 0.0)
  58284. this._darkness = 0.0;
  58285. else
  58286. this._darkness = darkness;
  58287. return this;
  58288. };
  58289. /**
  58290. * Sets the ability to have transparent shadow (boolean).
  58291. * @param transparent True if transparent else False
  58292. * @returns the shadow generator allowing fluent coding
  58293. */
  58294. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  58295. this._transparencyShadow = transparent;
  58296. return this;
  58297. };
  58298. /**
  58299. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  58300. * @returns The render target texture if present otherwise, null
  58301. */
  58302. ShadowGenerator.prototype.getShadowMap = function () {
  58303. return this._shadowMap;
  58304. };
  58305. /**
  58306. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  58307. * @returns The render target texture if the shadow map is present otherwise, null
  58308. */
  58309. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  58310. if (this._shadowMap2) {
  58311. return this._shadowMap2;
  58312. }
  58313. return this._shadowMap;
  58314. };
  58315. /**
  58316. * Helper function to add a mesh and its descendants to the list of shadow casters.
  58317. * @param mesh Mesh to add
  58318. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  58319. * @returns the Shadow Generator itself
  58320. */
  58321. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  58322. if (includeDescendants === void 0) { includeDescendants = true; }
  58323. if (!this._shadowMap) {
  58324. return this;
  58325. }
  58326. if (!this._shadowMap.renderList) {
  58327. this._shadowMap.renderList = [];
  58328. }
  58329. this._shadowMap.renderList.push(mesh);
  58330. if (includeDescendants) {
  58331. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  58332. }
  58333. return this;
  58334. var _a;
  58335. };
  58336. /**
  58337. * Helper function to remove a mesh and its descendants from the list of shadow casters
  58338. * @param mesh Mesh to remove
  58339. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  58340. * @returns the Shadow Generator itself
  58341. */
  58342. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  58343. if (includeDescendants === void 0) { includeDescendants = true; }
  58344. if (!this._shadowMap || !this._shadowMap.renderList) {
  58345. return this;
  58346. }
  58347. var index = this._shadowMap.renderList.indexOf(mesh);
  58348. if (index !== -1) {
  58349. this._shadowMap.renderList.splice(index, 1);
  58350. }
  58351. if (includeDescendants) {
  58352. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  58353. var child = _a[_i];
  58354. this.removeShadowCaster(child);
  58355. }
  58356. }
  58357. return this;
  58358. };
  58359. /**
  58360. * Returns the associated light object.
  58361. * @returns the light generating the shadow
  58362. */
  58363. ShadowGenerator.prototype.getLight = function () {
  58364. return this._light;
  58365. };
  58366. ShadowGenerator.prototype._initializeGenerator = function () {
  58367. this._light._markMeshesAsLightDirty();
  58368. this._initializeShadowMap();
  58369. };
  58370. ShadowGenerator.prototype._initializeShadowMap = function () {
  58371. var _this = this;
  58372. // Render target
  58373. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  58374. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58375. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58376. this._shadowMap.anisotropicFilteringLevel = 1;
  58377. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  58378. this._shadowMap.renderParticles = false;
  58379. this._shadowMap.ignoreCameraViewport = true;
  58380. // Record Face Index before render.
  58381. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  58382. _this._currentFaceIndex = faceIndex;
  58383. });
  58384. // Custom render function.
  58385. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  58386. // Blur if required afer render.
  58387. this._shadowMap.onAfterUnbindObservable.add(function () {
  58388. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  58389. return;
  58390. }
  58391. var shadowMap = _this.getShadowMapForRendering();
  58392. if (shadowMap) {
  58393. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  58394. }
  58395. });
  58396. // Clear according to the chosen filter.
  58397. this._shadowMap.onClearObservable.add(function (engine) {
  58398. if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  58399. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true);
  58400. }
  58401. else {
  58402. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  58403. }
  58404. });
  58405. };
  58406. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  58407. var _this = this;
  58408. var engine = this._scene.getEngine();
  58409. var targetSize = this._mapSize / this.blurScale;
  58410. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  58411. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  58412. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58413. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58414. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  58415. }
  58416. if (this.useKernelBlur) {
  58417. 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);
  58418. this._kernelBlurXPostprocess.width = targetSize;
  58419. this._kernelBlurXPostprocess.height = targetSize;
  58420. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  58421. effect.setTexture("textureSampler", _this._shadowMap);
  58422. });
  58423. 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);
  58424. this._kernelBlurXPostprocess.autoClear = false;
  58425. this._kernelBlurYPostprocess.autoClear = false;
  58426. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  58427. this._kernelBlurXPostprocess.packedFloat = true;
  58428. this._kernelBlurYPostprocess.packedFloat = true;
  58429. }
  58430. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  58431. }
  58432. else {
  58433. 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);
  58434. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  58435. effect.setFloat2("screenSize", targetSize, targetSize);
  58436. effect.setTexture("textureSampler", _this._shadowMap);
  58437. });
  58438. this._boxBlurPostprocess.autoClear = false;
  58439. this._blurPostProcesses = [this._boxBlurPostprocess];
  58440. }
  58441. };
  58442. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  58443. var index;
  58444. var engine = this._scene.getEngine();
  58445. if (depthOnlySubMeshes.length) {
  58446. engine.setColorWrite(false);
  58447. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  58448. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  58449. }
  58450. engine.setColorWrite(true);
  58451. }
  58452. for (index = 0; index < opaqueSubMeshes.length; index++) {
  58453. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  58454. }
  58455. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  58456. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  58457. }
  58458. if (this._transparencyShadow) {
  58459. for (index = 0; index < transparentSubMeshes.length; index++) {
  58460. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  58461. }
  58462. }
  58463. };
  58464. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  58465. var _this = this;
  58466. var mesh = subMesh.getRenderingMesh();
  58467. var scene = this._scene;
  58468. var engine = scene.getEngine();
  58469. var material = subMesh.getMaterial();
  58470. if (!material) {
  58471. return;
  58472. }
  58473. // Culling
  58474. engine.setState(material.backFaceCulling);
  58475. // Managing instances
  58476. var batch = mesh._getInstancesRenderList(subMesh._id);
  58477. if (batch.mustReturn) {
  58478. return;
  58479. }
  58480. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  58481. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  58482. engine.enableEffect(this._effect);
  58483. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  58484. this._effect.setFloat2("biasAndScale", this.bias, this.depthScale);
  58485. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  58486. this._effect.setVector3("lightPosition", this.getLight().position);
  58487. if (scene.activeCamera) {
  58488. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  58489. }
  58490. // Alpha test
  58491. if (material && material.needAlphaTesting()) {
  58492. var alphaTexture = material.getAlphaTestTexture();
  58493. if (alphaTexture) {
  58494. this._effect.setTexture("diffuseSampler", alphaTexture);
  58495. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  58496. }
  58497. }
  58498. // Bones
  58499. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  58500. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  58501. }
  58502. if (this.forceBackFacesOnly) {
  58503. engine.setState(true, 0, false, true);
  58504. }
  58505. // Draw
  58506. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  58507. if (this.forceBackFacesOnly) {
  58508. engine.setState(true, 0, false, false);
  58509. }
  58510. }
  58511. else {
  58512. // Need to reset refresh rate of the shadowMap
  58513. if (this._shadowMap) {
  58514. this._shadowMap.resetRefreshCounter();
  58515. }
  58516. }
  58517. };
  58518. ShadowGenerator.prototype._applyFilterValues = function () {
  58519. if (!this._shadowMap) {
  58520. return;
  58521. }
  58522. if (this.filter === ShadowGenerator.FILTER_NONE) {
  58523. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  58524. }
  58525. else {
  58526. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  58527. }
  58528. };
  58529. /**
  58530. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  58531. * @param onCompiled Callback triggered at the and of the effects compilation
  58532. * @param options Sets of optional options forcing the compilation with different modes
  58533. */
  58534. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  58535. var _this = this;
  58536. var localOptions = __assign({ useInstances: false }, options);
  58537. var shadowMap = this.getShadowMap();
  58538. if (!shadowMap) {
  58539. if (onCompiled) {
  58540. onCompiled(this);
  58541. }
  58542. return;
  58543. }
  58544. var renderList = shadowMap.renderList;
  58545. if (!renderList) {
  58546. if (onCompiled) {
  58547. onCompiled(this);
  58548. }
  58549. return;
  58550. }
  58551. var subMeshes = new Array();
  58552. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  58553. var mesh = renderList_1[_i];
  58554. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  58555. }
  58556. if (subMeshes.length === 0) {
  58557. if (onCompiled) {
  58558. onCompiled(this);
  58559. }
  58560. return;
  58561. }
  58562. var currentIndex = 0;
  58563. var checkReady = function () {
  58564. if (!_this._scene || !_this._scene.getEngine()) {
  58565. return;
  58566. }
  58567. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  58568. currentIndex++;
  58569. if (currentIndex >= subMeshes.length) {
  58570. if (onCompiled) {
  58571. onCompiled(_this);
  58572. }
  58573. return;
  58574. }
  58575. }
  58576. setTimeout(checkReady, 16);
  58577. };
  58578. checkReady();
  58579. };
  58580. /**
  58581. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  58582. * @param options Sets of optional options forcing the compilation with different modes
  58583. * @returns A promise that resolves when the compilation completes
  58584. */
  58585. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  58586. var _this = this;
  58587. return new Promise(function (resolve) {
  58588. _this.forceCompilation(function () {
  58589. resolve();
  58590. }, options);
  58591. });
  58592. };
  58593. /**
  58594. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  58595. * @param subMesh The submesh we want to render in the shadow map
  58596. * @param useInstances Defines wether will draw in the map using instances
  58597. * @returns true if ready otherwise, false
  58598. */
  58599. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  58600. var defines = [];
  58601. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  58602. defines.push("#define FLOAT");
  58603. }
  58604. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  58605. defines.push("#define ESM");
  58606. }
  58607. var attribs = [BABYLON.VertexBuffer.PositionKind];
  58608. var mesh = subMesh.getMesh();
  58609. var material = subMesh.getMaterial();
  58610. // Alpha test
  58611. if (material && material.needAlphaTesting()) {
  58612. var alphaTexture = material.getAlphaTestTexture();
  58613. if (alphaTexture) {
  58614. defines.push("#define ALPHATEST");
  58615. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  58616. attribs.push(BABYLON.VertexBuffer.UVKind);
  58617. defines.push("#define UV1");
  58618. }
  58619. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  58620. if (alphaTexture.coordinatesIndex === 1) {
  58621. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  58622. defines.push("#define UV2");
  58623. }
  58624. }
  58625. }
  58626. }
  58627. // Bones
  58628. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  58629. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  58630. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  58631. if (mesh.numBoneInfluencers > 4) {
  58632. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  58633. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  58634. }
  58635. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  58636. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  58637. }
  58638. else {
  58639. defines.push("#define NUM_BONE_INFLUENCERS 0");
  58640. }
  58641. // Instances
  58642. if (useInstances) {
  58643. defines.push("#define INSTANCES");
  58644. attribs.push("world0");
  58645. attribs.push("world1");
  58646. attribs.push("world2");
  58647. attribs.push("world3");
  58648. }
  58649. // Get correct effect
  58650. var join = defines.join("\n");
  58651. if (this._cachedDefines !== join) {
  58652. this._cachedDefines = join;
  58653. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues", "biasAndScale"], ["diffuseSampler"], join);
  58654. }
  58655. if (!this._effect.isReady()) {
  58656. return false;
  58657. }
  58658. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  58659. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  58660. this._initializeBlurRTTAndPostProcesses();
  58661. }
  58662. }
  58663. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  58664. return false;
  58665. }
  58666. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  58667. return false;
  58668. }
  58669. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  58670. return false;
  58671. }
  58672. return true;
  58673. };
  58674. /**
  58675. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  58676. * @param defines Defines of the material we want to update
  58677. * @param lightIndex Index of the light in the enabled light list of the material
  58678. */
  58679. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  58680. var scene = this._scene;
  58681. var light = this._light;
  58682. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  58683. return;
  58684. }
  58685. defines["SHADOW" + lightIndex] = true;
  58686. if (this.usePoissonSampling) {
  58687. defines["SHADOWPCF" + lightIndex] = true;
  58688. }
  58689. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  58690. defines["SHADOWESM" + lightIndex] = true;
  58691. }
  58692. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  58693. defines["SHADOWCLOSEESM" + lightIndex] = true;
  58694. }
  58695. if (light.needCube()) {
  58696. defines["SHADOWCUBE" + lightIndex] = true;
  58697. }
  58698. };
  58699. /**
  58700. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  58701. * defined in the generator but impacting the effect).
  58702. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  58703. * @param effect The effect we are binfing the information for
  58704. */
  58705. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  58706. var light = this._light;
  58707. var scene = this._scene;
  58708. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  58709. return;
  58710. }
  58711. var camera = scene.activeCamera;
  58712. if (!camera) {
  58713. return;
  58714. }
  58715. var shadowMap = this.getShadowMap();
  58716. if (!shadowMap) {
  58717. return;
  58718. }
  58719. if (!light.needCube()) {
  58720. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  58721. }
  58722. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  58723. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  58724. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  58725. };
  58726. /**
  58727. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  58728. * (eq to shadow prjection matrix * light transform matrix)
  58729. * @returns The transform matrix used to create the shadow map
  58730. */
  58731. ShadowGenerator.prototype.getTransformMatrix = function () {
  58732. var scene = this._scene;
  58733. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  58734. return this._transformMatrix;
  58735. }
  58736. this._currentRenderID = scene.getRenderId();
  58737. this._currentFaceIndexCache = this._currentFaceIndex;
  58738. var lightPosition = this._light.position;
  58739. if (this._light.computeTransformedInformation()) {
  58740. lightPosition = this._light.transformedPosition;
  58741. }
  58742. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  58743. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  58744. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  58745. }
  58746. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  58747. this._cachedPosition = lightPosition.clone();
  58748. this._cachedDirection = this._lightDirection.clone();
  58749. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  58750. var shadowMap = this.getShadowMap();
  58751. if (shadowMap) {
  58752. var renderList = shadowMap.renderList;
  58753. if (renderList) {
  58754. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  58755. }
  58756. }
  58757. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  58758. }
  58759. return this._transformMatrix;
  58760. };
  58761. /**
  58762. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  58763. * Cube and 2D textures for instance.
  58764. */
  58765. ShadowGenerator.prototype.recreateShadowMap = function () {
  58766. var shadowMap = this._shadowMap;
  58767. if (!shadowMap) {
  58768. return;
  58769. }
  58770. // Track render list.
  58771. var renderList = shadowMap.renderList;
  58772. // Clean up existing data.
  58773. this._disposeRTTandPostProcesses();
  58774. // Reinitializes.
  58775. this._initializeGenerator();
  58776. // Reaffect the filter to ensure a correct fallback if necessary.
  58777. this.filter = this.filter;
  58778. // Reaffect the filter.
  58779. this._applyFilterValues();
  58780. // Reaffect Render List.
  58781. this._shadowMap.renderList = renderList;
  58782. };
  58783. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  58784. if (this._shadowMap2) {
  58785. this._shadowMap2.dispose();
  58786. this._shadowMap2 = null;
  58787. }
  58788. if (this._boxBlurPostprocess) {
  58789. this._boxBlurPostprocess.dispose();
  58790. this._boxBlurPostprocess = null;
  58791. }
  58792. if (this._kernelBlurXPostprocess) {
  58793. this._kernelBlurXPostprocess.dispose();
  58794. this._kernelBlurXPostprocess = null;
  58795. }
  58796. if (this._kernelBlurYPostprocess) {
  58797. this._kernelBlurYPostprocess.dispose();
  58798. this._kernelBlurYPostprocess = null;
  58799. }
  58800. this._blurPostProcesses = [];
  58801. };
  58802. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  58803. if (this._shadowMap) {
  58804. this._shadowMap.dispose();
  58805. this._shadowMap = null;
  58806. }
  58807. this._disposeBlurPostProcesses();
  58808. };
  58809. /**
  58810. * Disposes the ShadowGenerator.
  58811. * Returns nothing.
  58812. */
  58813. ShadowGenerator.prototype.dispose = function () {
  58814. this._disposeRTTandPostProcesses();
  58815. if (this._light) {
  58816. this._light._shadowGenerator = null;
  58817. this._light._markMeshesAsLightDirty();
  58818. }
  58819. };
  58820. /**
  58821. * Serializes the shadow generator setup to a json object.
  58822. * @returns The serialized JSON object
  58823. */
  58824. ShadowGenerator.prototype.serialize = function () {
  58825. var serializationObject = {};
  58826. var shadowMap = this.getShadowMap();
  58827. if (!shadowMap) {
  58828. return serializationObject;
  58829. }
  58830. serializationObject.lightId = this._light.id;
  58831. serializationObject.mapSize = shadowMap.getRenderSize();
  58832. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  58833. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  58834. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  58835. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  58836. serializationObject.usePoissonSampling = this.usePoissonSampling;
  58837. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  58838. serializationObject.depthScale = this.depthScale;
  58839. serializationObject.darkness = this.getDarkness();
  58840. serializationObject.blurBoxOffset = this.blurBoxOffset;
  58841. serializationObject.blurKernel = this.blurKernel;
  58842. serializationObject.blurScale = this.blurScale;
  58843. serializationObject.useKernelBlur = this.useKernelBlur;
  58844. serializationObject.transparencyShadow = this._transparencyShadow;
  58845. serializationObject.renderList = [];
  58846. if (shadowMap.renderList) {
  58847. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  58848. var mesh = shadowMap.renderList[meshIndex];
  58849. serializationObject.renderList.push(mesh.id);
  58850. }
  58851. }
  58852. return serializationObject;
  58853. };
  58854. /**
  58855. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  58856. * @param parsedShadowGenerator The JSON object to parse
  58857. * @param scene The scene to create the shadow map for
  58858. * @returns The parsed shadow generator
  58859. */
  58860. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  58861. //casting to point light, as light is missing the position attr and typescript complains.
  58862. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  58863. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  58864. var shadowMap = shadowGenerator.getShadowMap();
  58865. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  58866. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  58867. meshes.forEach(function (mesh) {
  58868. if (!shadowMap) {
  58869. return;
  58870. }
  58871. if (!shadowMap.renderList) {
  58872. shadowMap.renderList = [];
  58873. }
  58874. shadowMap.renderList.push(mesh);
  58875. });
  58876. }
  58877. if (parsedShadowGenerator.usePoissonSampling) {
  58878. shadowGenerator.usePoissonSampling = true;
  58879. }
  58880. else if (parsedShadowGenerator.useExponentialShadowMap) {
  58881. shadowGenerator.useExponentialShadowMap = true;
  58882. }
  58883. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  58884. shadowGenerator.useBlurExponentialShadowMap = true;
  58885. }
  58886. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  58887. shadowGenerator.useCloseExponentialShadowMap = true;
  58888. }
  58889. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  58890. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  58891. }
  58892. else if (parsedShadowGenerator.useVarianceShadowMap) {
  58893. shadowGenerator.useExponentialShadowMap = true;
  58894. }
  58895. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  58896. shadowGenerator.useBlurExponentialShadowMap = true;
  58897. }
  58898. if (parsedShadowGenerator.depthScale) {
  58899. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  58900. }
  58901. if (parsedShadowGenerator.blurScale) {
  58902. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  58903. }
  58904. if (parsedShadowGenerator.blurBoxOffset) {
  58905. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  58906. }
  58907. if (parsedShadowGenerator.useKernelBlur) {
  58908. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  58909. }
  58910. if (parsedShadowGenerator.blurKernel) {
  58911. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  58912. }
  58913. if (parsedShadowGenerator.bias !== undefined) {
  58914. shadowGenerator.bias = parsedShadowGenerator.bias;
  58915. }
  58916. if (parsedShadowGenerator.darkness) {
  58917. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  58918. }
  58919. if (parsedShadowGenerator.transparencyShadow) {
  58920. shadowGenerator.setTransparencyShadow(true);
  58921. }
  58922. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  58923. return shadowGenerator;
  58924. };
  58925. ShadowGenerator._FILTER_NONE = 0;
  58926. ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP = 1;
  58927. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  58928. ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  58929. ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  58930. ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  58931. return ShadowGenerator;
  58932. }());
  58933. BABYLON.ShadowGenerator = ShadowGenerator;
  58934. })(BABYLON || (BABYLON = {}));
  58935. //# sourceMappingURL=babylon.shadowGenerator.js.map
  58936. var BABYLON;
  58937. (function (BABYLON) {
  58938. var DefaultLoadingScreen = /** @class */ (function () {
  58939. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  58940. if (_loadingText === void 0) { _loadingText = ""; }
  58941. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  58942. var _this = this;
  58943. this._renderingCanvas = _renderingCanvas;
  58944. this._loadingText = _loadingText;
  58945. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  58946. // Resize
  58947. this._resizeLoadingUI = function () {
  58948. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  58949. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  58950. if (!_this._loadingDiv) {
  58951. return;
  58952. }
  58953. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  58954. _this._loadingDiv.style.left = canvasRect.left + "px";
  58955. _this._loadingDiv.style.top = canvasRect.top + "px";
  58956. _this._loadingDiv.style.width = canvasRect.width + "px";
  58957. _this._loadingDiv.style.height = canvasRect.height + "px";
  58958. };
  58959. }
  58960. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  58961. if (this._loadingDiv) {
  58962. // Do not add a loading screen if there is already one
  58963. return;
  58964. }
  58965. this._loadingDiv = document.createElement("div");
  58966. this._loadingDiv.id = "babylonjsLoadingDiv";
  58967. this._loadingDiv.style.opacity = "0";
  58968. this._loadingDiv.style.transition = "opacity 1.5s ease";
  58969. this._loadingDiv.style.pointerEvents = "none";
  58970. // Loading text
  58971. this._loadingTextDiv = document.createElement("div");
  58972. this._loadingTextDiv.style.position = "absolute";
  58973. this._loadingTextDiv.style.left = "0";
  58974. this._loadingTextDiv.style.top = "50%";
  58975. this._loadingTextDiv.style.marginTop = "80px";
  58976. this._loadingTextDiv.style.width = "100%";
  58977. this._loadingTextDiv.style.height = "20px";
  58978. this._loadingTextDiv.style.fontFamily = "Arial";
  58979. this._loadingTextDiv.style.fontSize = "14px";
  58980. this._loadingTextDiv.style.color = "white";
  58981. this._loadingTextDiv.style.textAlign = "center";
  58982. this._loadingTextDiv.innerHTML = "Loading";
  58983. this._loadingDiv.appendChild(this._loadingTextDiv);
  58984. //set the predefined text
  58985. this._loadingTextDiv.innerHTML = this._loadingText;
  58986. // Generating keyframes
  58987. var style = document.createElement('style');
  58988. style.type = 'text/css';
  58989. 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 }";
  58990. style.innerHTML = keyFrames;
  58991. document.getElementsByTagName('head')[0].appendChild(style);
  58992. // Loading img
  58993. var imgBack = new Image();
  58994. 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";
  58995. imgBack.style.position = "absolute";
  58996. imgBack.style.left = "50%";
  58997. imgBack.style.top = "50%";
  58998. imgBack.style.marginLeft = "-60px";
  58999. imgBack.style.marginTop = "-60px";
  59000. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  59001. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  59002. imgBack.style.transformOrigin = "50% 50%";
  59003. imgBack.style.webkitTransformOrigin = "50% 50%";
  59004. this._loadingDiv.appendChild(imgBack);
  59005. this._resizeLoadingUI();
  59006. window.addEventListener("resize", this._resizeLoadingUI);
  59007. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  59008. document.body.appendChild(this._loadingDiv);
  59009. this._loadingDiv.style.opacity = "1";
  59010. };
  59011. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  59012. var _this = this;
  59013. if (!this._loadingDiv) {
  59014. return;
  59015. }
  59016. var onTransitionEnd = function () {
  59017. if (!_this._loadingDiv) {
  59018. return;
  59019. }
  59020. document.body.removeChild(_this._loadingDiv);
  59021. window.removeEventListener("resize", _this._resizeLoadingUI);
  59022. _this._loadingDiv = null;
  59023. };
  59024. this._loadingDiv.style.opacity = "0";
  59025. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  59026. };
  59027. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  59028. set: function (text) {
  59029. this._loadingText = text;
  59030. if (this._loadingTextDiv) {
  59031. this._loadingTextDiv.innerHTML = this._loadingText;
  59032. }
  59033. },
  59034. enumerable: true,
  59035. configurable: true
  59036. });
  59037. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  59038. get: function () {
  59039. return this._loadingDivBackgroundColor;
  59040. },
  59041. set: function (color) {
  59042. this._loadingDivBackgroundColor = color;
  59043. if (!this._loadingDiv) {
  59044. return;
  59045. }
  59046. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  59047. },
  59048. enumerable: true,
  59049. configurable: true
  59050. });
  59051. return DefaultLoadingScreen;
  59052. }());
  59053. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  59054. })(BABYLON || (BABYLON = {}));
  59055. //# sourceMappingURL=babylon.loadingScreen.js.map
  59056. var BABYLON;
  59057. (function (BABYLON) {
  59058. var SceneLoaderProgressEvent = /** @class */ (function () {
  59059. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  59060. this.lengthComputable = lengthComputable;
  59061. this.loaded = loaded;
  59062. this.total = total;
  59063. }
  59064. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  59065. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  59066. };
  59067. return SceneLoaderProgressEvent;
  59068. }());
  59069. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  59070. var SceneLoader = /** @class */ (function () {
  59071. function SceneLoader() {
  59072. }
  59073. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  59074. get: function () {
  59075. return 0;
  59076. },
  59077. enumerable: true,
  59078. configurable: true
  59079. });
  59080. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  59081. get: function () {
  59082. return 1;
  59083. },
  59084. enumerable: true,
  59085. configurable: true
  59086. });
  59087. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  59088. get: function () {
  59089. return 2;
  59090. },
  59091. enumerable: true,
  59092. configurable: true
  59093. });
  59094. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  59095. get: function () {
  59096. return 3;
  59097. },
  59098. enumerable: true,
  59099. configurable: true
  59100. });
  59101. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  59102. get: function () {
  59103. return SceneLoader._ForceFullSceneLoadingForIncremental;
  59104. },
  59105. set: function (value) {
  59106. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  59107. },
  59108. enumerable: true,
  59109. configurable: true
  59110. });
  59111. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  59112. get: function () {
  59113. return SceneLoader._ShowLoadingScreen;
  59114. },
  59115. set: function (value) {
  59116. SceneLoader._ShowLoadingScreen = value;
  59117. },
  59118. enumerable: true,
  59119. configurable: true
  59120. });
  59121. Object.defineProperty(SceneLoader, "loggingLevel", {
  59122. get: function () {
  59123. return SceneLoader._loggingLevel;
  59124. },
  59125. set: function (value) {
  59126. SceneLoader._loggingLevel = value;
  59127. },
  59128. enumerable: true,
  59129. configurable: true
  59130. });
  59131. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  59132. get: function () {
  59133. return SceneLoader._CleanBoneMatrixWeights;
  59134. },
  59135. set: function (value) {
  59136. SceneLoader._CleanBoneMatrixWeights = value;
  59137. },
  59138. enumerable: true,
  59139. configurable: true
  59140. });
  59141. SceneLoader._getDefaultPlugin = function () {
  59142. return SceneLoader._registeredPlugins[".babylon"];
  59143. };
  59144. SceneLoader._getPluginForExtension = function (extension) {
  59145. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  59146. if (registeredPlugin) {
  59147. return registeredPlugin;
  59148. }
  59149. BABYLON.Tools.Warn("Unable to find a plugin to load " + extension + " files. Trying to use .babylon default plugin.");
  59150. return SceneLoader._getDefaultPlugin();
  59151. };
  59152. SceneLoader._getPluginForDirectLoad = function (data) {
  59153. for (var extension in SceneLoader._registeredPlugins) {
  59154. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  59155. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  59156. return SceneLoader._registeredPlugins[extension];
  59157. }
  59158. }
  59159. return SceneLoader._getDefaultPlugin();
  59160. };
  59161. SceneLoader._getPluginForFilename = function (sceneFilename) {
  59162. if (sceneFilename.name) {
  59163. sceneFilename = sceneFilename.name;
  59164. }
  59165. var queryStringPosition = sceneFilename.indexOf("?");
  59166. if (queryStringPosition !== -1) {
  59167. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  59168. }
  59169. var dotPosition = sceneFilename.lastIndexOf(".");
  59170. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  59171. return SceneLoader._getPluginForExtension(extension);
  59172. };
  59173. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  59174. SceneLoader._getDirectLoad = function (sceneFilename) {
  59175. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  59176. return sceneFilename.substr(5);
  59177. }
  59178. return null;
  59179. };
  59180. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  59181. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  59182. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  59183. var plugin;
  59184. if (registeredPlugin.plugin.createPlugin) {
  59185. plugin = registeredPlugin.plugin.createPlugin();
  59186. }
  59187. else {
  59188. plugin = registeredPlugin.plugin;
  59189. }
  59190. var useArrayBuffer = registeredPlugin.isBinary;
  59191. var database;
  59192. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  59193. var dataCallback = function (data, responseURL) {
  59194. if (scene.isDisposed) {
  59195. onError("Scene has been disposed");
  59196. return;
  59197. }
  59198. scene.database = database;
  59199. onSuccess(plugin, data, responseURL);
  59200. };
  59201. var request = null;
  59202. var pluginDisposed = false;
  59203. var onDisposeObservable = plugin.onDisposeObservable;
  59204. if (onDisposeObservable) {
  59205. onDisposeObservable.add(function () {
  59206. pluginDisposed = true;
  59207. if (request) {
  59208. request.abort();
  59209. request = null;
  59210. }
  59211. onDispose();
  59212. });
  59213. }
  59214. var manifestChecked = function () {
  59215. if (pluginDisposed) {
  59216. return;
  59217. }
  59218. var url = rootUrl + sceneFilename;
  59219. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  59220. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  59221. } : undefined, database, useArrayBuffer, function (request, exception) {
  59222. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  59223. });
  59224. };
  59225. if (directLoad) {
  59226. dataCallback(directLoad);
  59227. return plugin;
  59228. }
  59229. if (rootUrl.indexOf("file:") === -1) {
  59230. if (scene.getEngine().enableOfflineSupport) {
  59231. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  59232. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  59233. }
  59234. else {
  59235. manifestChecked();
  59236. }
  59237. }
  59238. else {
  59239. var fileOrString = sceneFilename;
  59240. if (fileOrString.name) {
  59241. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  59242. }
  59243. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  59244. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  59245. }
  59246. else {
  59247. onError("Unable to find file named " + sceneFilename);
  59248. }
  59249. }
  59250. return plugin;
  59251. };
  59252. // Public functions
  59253. SceneLoader.GetPluginForExtension = function (extension) {
  59254. return SceneLoader._getPluginForExtension(extension).plugin;
  59255. };
  59256. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  59257. return !!SceneLoader._registeredPlugins[extension];
  59258. };
  59259. SceneLoader.RegisterPlugin = function (plugin) {
  59260. if (typeof plugin.extensions === "string") {
  59261. var extension = plugin.extensions;
  59262. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  59263. plugin: plugin,
  59264. isBinary: false
  59265. };
  59266. }
  59267. else {
  59268. var extensions = plugin.extensions;
  59269. Object.keys(extensions).forEach(function (extension) {
  59270. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  59271. plugin: plugin,
  59272. isBinary: extensions[extension].isBinary
  59273. };
  59274. });
  59275. }
  59276. };
  59277. /**
  59278. * Import meshes into a scene
  59279. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  59280. * @param rootUrl a string that defines the root url for scene and resources
  59281. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  59282. * @param scene the instance of BABYLON.Scene to append to
  59283. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  59284. * @param onProgress a callback with a progress event for each file being loaded
  59285. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  59286. * @param pluginExtension the extension used to determine the plugin
  59287. * @returns The loaded plugin
  59288. */
  59289. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  59290. if (onSuccess === void 0) { onSuccess = null; }
  59291. if (onProgress === void 0) { onProgress = null; }
  59292. if (onError === void 0) { onError = null; }
  59293. if (pluginExtension === void 0) { pluginExtension = null; }
  59294. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  59295. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  59296. return null;
  59297. }
  59298. var loadingToken = {};
  59299. scene._addPendingData(loadingToken);
  59300. var disposeHandler = function () {
  59301. scene._removePendingData(loadingToken);
  59302. };
  59303. var errorHandler = function (message, exception) {
  59304. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  59305. if (onError) {
  59306. onError(scene, errorMessage, exception);
  59307. }
  59308. else {
  59309. BABYLON.Tools.Error(errorMessage);
  59310. // should the exception be thrown?
  59311. }
  59312. disposeHandler();
  59313. };
  59314. var progressHandler = onProgress ? function (event) {
  59315. try {
  59316. onProgress(event);
  59317. }
  59318. catch (e) {
  59319. errorHandler("Error in onProgress callback", e);
  59320. }
  59321. } : undefined;
  59322. var successHandler = function (meshes, particleSystems, skeletons) {
  59323. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  59324. if (onSuccess) {
  59325. try {
  59326. onSuccess(meshes, particleSystems, skeletons);
  59327. }
  59328. catch (e) {
  59329. errorHandler("Error in onSuccess callback", e);
  59330. }
  59331. }
  59332. scene._removePendingData(loadingToken);
  59333. };
  59334. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  59335. if (plugin.rewriteRootURL) {
  59336. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  59337. }
  59338. if (sceneFilename === "") {
  59339. if (sceneFilename === "") {
  59340. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  59341. }
  59342. }
  59343. if (plugin.importMesh) {
  59344. var syncedPlugin = plugin;
  59345. var meshes = new Array();
  59346. var particleSystems = new Array();
  59347. var skeletons = new Array();
  59348. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  59349. return;
  59350. }
  59351. scene.loadingPluginName = plugin.name;
  59352. successHandler(meshes, particleSystems, skeletons);
  59353. }
  59354. else {
  59355. var asyncedPlugin = plugin;
  59356. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, progressHandler).then(function (result) {
  59357. scene.loadingPluginName = plugin.name;
  59358. successHandler(result.meshes, result.particleSystems, result.skeletons);
  59359. }).catch(function (error) {
  59360. errorHandler(error.message, error);
  59361. });
  59362. }
  59363. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  59364. };
  59365. /**
  59366. * Import meshes into a scene
  59367. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  59368. * @param rootUrl a string that defines the root url for scene and resources
  59369. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  59370. * @param scene the instance of BABYLON.Scene to append to
  59371. * @param onProgress a callback with a progress event for each file being loaded
  59372. * @param pluginExtension the extension used to determine the plugin
  59373. * @returns The loaded list of imported meshes, particleSystems, and skeletons
  59374. */
  59375. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  59376. if (onProgress === void 0) { onProgress = null; }
  59377. if (pluginExtension === void 0) { pluginExtension = null; }
  59378. return new Promise(function (resolve, reject) {
  59379. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  59380. resolve({
  59381. meshes: meshes,
  59382. particleSystems: particleSystems,
  59383. skeletons: skeletons
  59384. });
  59385. }, onProgress, function (scene, message, exception) {
  59386. reject(exception || new Error(message));
  59387. });
  59388. });
  59389. };
  59390. /**
  59391. * Load a scene
  59392. * @param rootUrl a string that defines the root url for scene and resources
  59393. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  59394. * @param engine is the instance of BABYLON.Engine to use to create the scene
  59395. * @param onSuccess a callback with the scene when import succeeds
  59396. * @param onProgress a callback with a progress event for each file being loaded
  59397. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  59398. * @param pluginExtension the extension used to determine the plugin
  59399. * @returns The loaded plugin
  59400. */
  59401. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  59402. if (onSuccess === void 0) { onSuccess = null; }
  59403. if (onProgress === void 0) { onProgress = null; }
  59404. if (onError === void 0) { onError = null; }
  59405. if (pluginExtension === void 0) { pluginExtension = null; }
  59406. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  59407. };
  59408. /**
  59409. * Load a scene
  59410. * @param rootUrl a string that defines the root url for scene and resources
  59411. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  59412. * @param engine is the instance of BABYLON.Engine to use to create the scene
  59413. * @param onProgress a callback with a progress event for each file being loaded
  59414. * @param pluginExtension the extension used to determine the plugin
  59415. * @returns The loaded scene
  59416. */
  59417. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  59418. if (onProgress === void 0) { onProgress = null; }
  59419. if (pluginExtension === void 0) { pluginExtension = null; }
  59420. return new Promise(function (resolve, reject) {
  59421. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  59422. resolve(scene);
  59423. }, onProgress, function (scene, message, exception) {
  59424. reject(exception || new Error(message));
  59425. }, pluginExtension);
  59426. });
  59427. };
  59428. /**
  59429. * Append a scene
  59430. * @param rootUrl a string that defines the root url for scene and resources
  59431. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  59432. * @param scene is the instance of BABYLON.Scene to append to
  59433. * @param onSuccess a callback with the scene when import succeeds
  59434. * @param onProgress a callback with a progress event for each file being loaded
  59435. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  59436. * @param pluginExtension the extension used to determine the plugin
  59437. * @returns The loaded plugin
  59438. */
  59439. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  59440. if (onSuccess === void 0) { onSuccess = null; }
  59441. if (onProgress === void 0) { onProgress = null; }
  59442. if (onError === void 0) { onError = null; }
  59443. if (pluginExtension === void 0) { pluginExtension = null; }
  59444. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  59445. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  59446. return null;
  59447. }
  59448. if (SceneLoader.ShowLoadingScreen) {
  59449. scene.getEngine().displayLoadingUI();
  59450. }
  59451. var loadingToken = {};
  59452. scene._addPendingData(loadingToken);
  59453. var disposeHandler = function () {
  59454. scene._removePendingData(loadingToken);
  59455. scene.getEngine().hideLoadingUI();
  59456. };
  59457. var errorHandler = function (message, exception) {
  59458. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  59459. if (onError) {
  59460. onError(scene, errorMessage, exception);
  59461. }
  59462. else {
  59463. BABYLON.Tools.Error(errorMessage);
  59464. // should the exception be thrown?
  59465. }
  59466. disposeHandler();
  59467. };
  59468. var progressHandler = onProgress ? function (event) {
  59469. try {
  59470. onProgress(event);
  59471. }
  59472. catch (e) {
  59473. errorHandler("Error in onProgress callback", e);
  59474. }
  59475. } : undefined;
  59476. var successHandler = function () {
  59477. if (onSuccess) {
  59478. try {
  59479. onSuccess(scene);
  59480. }
  59481. catch (e) {
  59482. errorHandler("Error in onSuccess callback", e);
  59483. }
  59484. }
  59485. scene._removePendingData(loadingToken);
  59486. };
  59487. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  59488. if (sceneFilename === "") {
  59489. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  59490. }
  59491. if (plugin.load) {
  59492. var syncedPlugin = plugin;
  59493. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  59494. return;
  59495. }
  59496. scene.loadingPluginName = plugin.name;
  59497. successHandler();
  59498. }
  59499. else {
  59500. var asyncedPlugin = plugin;
  59501. asyncedPlugin.loadAsync(scene, data, rootUrl, progressHandler).then(function () {
  59502. scene.loadingPluginName = plugin.name;
  59503. successHandler();
  59504. }).catch(function (error) {
  59505. errorHandler(error.message, error);
  59506. });
  59507. }
  59508. if (SceneLoader.ShowLoadingScreen) {
  59509. scene.executeWhenReady(function () {
  59510. scene.getEngine().hideLoadingUI();
  59511. });
  59512. }
  59513. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  59514. };
  59515. /**
  59516. * Append a scene
  59517. * @param rootUrl a string that defines the root url for scene and resources
  59518. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  59519. * @param scene is the instance of BABYLON.Scene to append to
  59520. * @param onProgress a callback with a progress event for each file being loaded
  59521. * @param pluginExtension the extension used to determine the plugin
  59522. * @returns The given scene
  59523. */
  59524. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  59525. if (onProgress === void 0) { onProgress = null; }
  59526. if (pluginExtension === void 0) { pluginExtension = null; }
  59527. return new Promise(function (resolve, reject) {
  59528. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  59529. resolve(scene);
  59530. }, onProgress, function (scene, message, exception) {
  59531. reject(exception || new Error(message));
  59532. }, pluginExtension);
  59533. });
  59534. };
  59535. /**
  59536. * Load a scene into an asset container
  59537. * @param rootUrl a string that defines the root url for scene and resources
  59538. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  59539. * @param scene is the instance of BABYLON.Scene to append to
  59540. * @param onSuccess a callback with the scene when import succeeds
  59541. * @param onProgress a callback with a progress event for each file being loaded
  59542. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  59543. * @param pluginExtension the extension used to determine the plugin
  59544. * @returns The loaded plugin
  59545. */
  59546. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  59547. if (onSuccess === void 0) { onSuccess = null; }
  59548. if (onProgress === void 0) { onProgress = null; }
  59549. if (onError === void 0) { onError = null; }
  59550. if (pluginExtension === void 0) { pluginExtension = null; }
  59551. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  59552. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  59553. return null;
  59554. }
  59555. var loadingToken = {};
  59556. scene._addPendingData(loadingToken);
  59557. var disposeHandler = function () {
  59558. scene._removePendingData(loadingToken);
  59559. };
  59560. var errorHandler = function (message, exception) {
  59561. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  59562. if (onError) {
  59563. onError(scene, errorMessage, exception);
  59564. }
  59565. else {
  59566. BABYLON.Tools.Error(errorMessage);
  59567. // should the exception be thrown?
  59568. }
  59569. disposeHandler();
  59570. };
  59571. var progressHandler = onProgress ? function (event) {
  59572. try {
  59573. onProgress(event);
  59574. }
  59575. catch (e) {
  59576. errorHandler("Error in onProgress callback", e);
  59577. }
  59578. } : undefined;
  59579. var successHandler = function (assets) {
  59580. if (onSuccess) {
  59581. try {
  59582. onSuccess(assets);
  59583. }
  59584. catch (e) {
  59585. errorHandler("Error in onSuccess callback", e);
  59586. }
  59587. }
  59588. scene._removePendingData(loadingToken);
  59589. };
  59590. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  59591. if (plugin.loadAssetContainer) {
  59592. var syncedPlugin = plugin;
  59593. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, rootUrl, errorHandler);
  59594. if (!assetContainer) {
  59595. return;
  59596. }
  59597. scene.loadingPluginName = plugin.name;
  59598. successHandler(assetContainer);
  59599. }
  59600. else if (plugin.loadAssetContainerAsync) {
  59601. var asyncedPlugin = plugin;
  59602. asyncedPlugin.loadAssetContainerAsync(scene, data, rootUrl, progressHandler).then(function (assetContainer) {
  59603. scene.loadingPluginName = plugin.name;
  59604. successHandler(assetContainer);
  59605. }).catch(function (error) {
  59606. errorHandler(error.message, error);
  59607. });
  59608. }
  59609. else {
  59610. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  59611. }
  59612. if (SceneLoader.ShowLoadingScreen) {
  59613. scene.executeWhenReady(function () {
  59614. scene.getEngine().hideLoadingUI();
  59615. });
  59616. }
  59617. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  59618. };
  59619. /**
  59620. * Load a scene into an asset container
  59621. * @param rootUrl a string that defines the root url for scene and resources
  59622. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  59623. * @param scene is the instance of BABYLON.Scene to append to
  59624. * @param onProgress a callback with a progress event for each file being loaded
  59625. * @param pluginExtension the extension used to determine the plugin
  59626. * @returns The loaded asset container
  59627. */
  59628. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  59629. if (onProgress === void 0) { onProgress = null; }
  59630. if (pluginExtension === void 0) { pluginExtension = null; }
  59631. return new Promise(function (resolve, reject) {
  59632. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  59633. resolve(assetContainer);
  59634. }, onProgress, function (scene, message, exception) {
  59635. reject(exception || new Error(message));
  59636. }, pluginExtension);
  59637. });
  59638. };
  59639. // Flags
  59640. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  59641. SceneLoader._ShowLoadingScreen = true;
  59642. SceneLoader._CleanBoneMatrixWeights = false;
  59643. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  59644. // Members
  59645. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  59646. SceneLoader._registeredPlugins = {};
  59647. return SceneLoader;
  59648. }());
  59649. BABYLON.SceneLoader = SceneLoader;
  59650. ;
  59651. })(BABYLON || (BABYLON = {}));
  59652. //# sourceMappingURL=babylon.sceneLoader.js.map
  59653. var BABYLON;
  59654. (function (BABYLON) {
  59655. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  59656. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  59657. var parsedMaterial = parsedData.materials[index];
  59658. if (parsedMaterial.id === id) {
  59659. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  59660. }
  59661. }
  59662. return null;
  59663. };
  59664. var isDescendantOf = function (mesh, names, hierarchyIds) {
  59665. for (var i in names) {
  59666. if (mesh.name === names[i]) {
  59667. hierarchyIds.push(mesh.id);
  59668. return true;
  59669. }
  59670. }
  59671. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  59672. hierarchyIds.push(mesh.id);
  59673. return true;
  59674. }
  59675. return false;
  59676. };
  59677. var logOperation = function (operation, producer) {
  59678. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  59679. };
  59680. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  59681. if (addToScene === void 0) { addToScene = false; }
  59682. var container = new BABYLON.AssetContainer(scene);
  59683. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  59684. // when SceneLoader.debugLogging = true (default), or exception encountered.
  59685. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  59686. // and avoid problems with multiple concurrent .babylon loads.
  59687. var log = "importScene has failed JSON parse";
  59688. try {
  59689. var parsedData = JSON.parse(data);
  59690. log = "";
  59691. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  59692. var index;
  59693. var cache;
  59694. // Lights
  59695. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  59696. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  59697. var parsedLight = parsedData.lights[index];
  59698. var light = BABYLON.Light.Parse(parsedLight, scene);
  59699. if (light) {
  59700. container.lights.push(light);
  59701. log += (index === 0 ? "\n\tLights:" : "");
  59702. log += "\n\t\t" + light.toString(fullDetails);
  59703. }
  59704. }
  59705. }
  59706. // Animations
  59707. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  59708. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  59709. var parsedAnimation = parsedData.animations[index];
  59710. var animation = BABYLON.Animation.Parse(parsedAnimation);
  59711. scene.animations.push(animation);
  59712. container.animations.push(animation);
  59713. log += (index === 0 ? "\n\tAnimations:" : "");
  59714. log += "\n\t\t" + animation.toString(fullDetails);
  59715. }
  59716. }
  59717. // Materials
  59718. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  59719. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  59720. var parsedMaterial = parsedData.materials[index];
  59721. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  59722. container.materials.push(mat);
  59723. log += (index === 0 ? "\n\tMaterials:" : "");
  59724. log += "\n\t\t" + mat.toString(fullDetails);
  59725. }
  59726. }
  59727. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  59728. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  59729. var parsedMultiMaterial = parsedData.multiMaterials[index];
  59730. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  59731. container.multiMaterials.push(mmat);
  59732. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  59733. log += "\n\t\t" + mmat.toString(fullDetails);
  59734. }
  59735. }
  59736. // Morph targets
  59737. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  59738. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  59739. var managerData = _a[_i];
  59740. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  59741. }
  59742. }
  59743. // Skeletons
  59744. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  59745. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  59746. var parsedSkeleton = parsedData.skeletons[index];
  59747. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  59748. container.skeletons.push(skeleton);
  59749. log += (index === 0 ? "\n\tSkeletons:" : "");
  59750. log += "\n\t\t" + skeleton.toString(fullDetails);
  59751. }
  59752. }
  59753. // Geometries
  59754. var geometries = parsedData.geometries;
  59755. if (geometries !== undefined && geometries !== null) {
  59756. var addedGeometry = new Array();
  59757. // Boxes
  59758. var boxes = geometries.boxes;
  59759. if (boxes !== undefined && boxes !== null) {
  59760. for (index = 0, cache = boxes.length; index < cache; index++) {
  59761. var parsedBox = boxes[index];
  59762. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  59763. }
  59764. }
  59765. // Spheres
  59766. var spheres = geometries.spheres;
  59767. if (spheres !== undefined && spheres !== null) {
  59768. for (index = 0, cache = spheres.length; index < cache; index++) {
  59769. var parsedSphere = spheres[index];
  59770. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  59771. }
  59772. }
  59773. // Cylinders
  59774. var cylinders = geometries.cylinders;
  59775. if (cylinders !== undefined && cylinders !== null) {
  59776. for (index = 0, cache = cylinders.length; index < cache; index++) {
  59777. var parsedCylinder = cylinders[index];
  59778. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  59779. }
  59780. }
  59781. // Toruses
  59782. var toruses = geometries.toruses;
  59783. if (toruses !== undefined && toruses !== null) {
  59784. for (index = 0, cache = toruses.length; index < cache; index++) {
  59785. var parsedTorus = toruses[index];
  59786. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  59787. }
  59788. }
  59789. // Grounds
  59790. var grounds = geometries.grounds;
  59791. if (grounds !== undefined && grounds !== null) {
  59792. for (index = 0, cache = grounds.length; index < cache; index++) {
  59793. var parsedGround = grounds[index];
  59794. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  59795. }
  59796. }
  59797. // Planes
  59798. var planes = geometries.planes;
  59799. if (planes !== undefined && planes !== null) {
  59800. for (index = 0, cache = planes.length; index < cache; index++) {
  59801. var parsedPlane = planes[index];
  59802. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  59803. }
  59804. }
  59805. // TorusKnots
  59806. var torusKnots = geometries.torusKnots;
  59807. if (torusKnots !== undefined && torusKnots !== null) {
  59808. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  59809. var parsedTorusKnot = torusKnots[index];
  59810. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  59811. }
  59812. }
  59813. // VertexData
  59814. var vertexData = geometries.vertexData;
  59815. if (vertexData !== undefined && vertexData !== null) {
  59816. for (index = 0, cache = vertexData.length; index < cache; index++) {
  59817. var parsedVertexData = vertexData[index];
  59818. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  59819. }
  59820. }
  59821. addedGeometry.forEach(function (g) {
  59822. if (g) {
  59823. container.geometries.push(g);
  59824. }
  59825. });
  59826. }
  59827. // Transform nodes
  59828. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  59829. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  59830. var parsedTransformNode = parsedData.transformNodes[index];
  59831. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  59832. container.transformNodes.push(node);
  59833. }
  59834. }
  59835. // Meshes
  59836. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  59837. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  59838. var parsedMesh = parsedData.meshes[index];
  59839. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  59840. container.meshes.push(mesh);
  59841. log += (index === 0 ? "\n\tMeshes:" : "");
  59842. log += "\n\t\t" + mesh.toString(fullDetails);
  59843. }
  59844. }
  59845. // Cameras
  59846. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  59847. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  59848. var parsedCamera = parsedData.cameras[index];
  59849. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  59850. container.cameras.push(camera);
  59851. log += (index === 0 ? "\n\tCameras:" : "");
  59852. log += "\n\t\t" + camera.toString(fullDetails);
  59853. }
  59854. }
  59855. // Browsing all the graph to connect the dots
  59856. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  59857. var camera = scene.cameras[index];
  59858. if (camera._waitingParentId) {
  59859. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  59860. camera._waitingParentId = null;
  59861. }
  59862. }
  59863. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  59864. var light_1 = scene.lights[index];
  59865. if (light_1 && light_1._waitingParentId) {
  59866. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  59867. light_1._waitingParentId = null;
  59868. }
  59869. }
  59870. // Sounds
  59871. // TODO: add sound
  59872. var loadedSounds = [];
  59873. var loadedSound;
  59874. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  59875. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  59876. var parsedSound = parsedData.sounds[index];
  59877. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  59878. if (!parsedSound.url)
  59879. parsedSound.url = parsedSound.name;
  59880. if (!loadedSounds[parsedSound.url]) {
  59881. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  59882. loadedSounds[parsedSound.url] = loadedSound;
  59883. container.sounds.push(loadedSound);
  59884. }
  59885. else {
  59886. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  59887. }
  59888. }
  59889. else {
  59890. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  59891. }
  59892. }
  59893. }
  59894. loadedSounds = [];
  59895. // Connect parents & children and parse actions
  59896. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  59897. var transformNode = scene.transformNodes[index];
  59898. if (transformNode._waitingParentId) {
  59899. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  59900. transformNode._waitingParentId = null;
  59901. }
  59902. }
  59903. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  59904. var mesh = scene.meshes[index];
  59905. if (mesh._waitingParentId) {
  59906. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  59907. mesh._waitingParentId = null;
  59908. }
  59909. if (mesh._waitingActions) {
  59910. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  59911. mesh._waitingActions = null;
  59912. }
  59913. }
  59914. // freeze world matrix application
  59915. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  59916. var currentMesh = scene.meshes[index];
  59917. if (currentMesh._waitingFreezeWorldMatrix) {
  59918. currentMesh.freezeWorldMatrix();
  59919. currentMesh._waitingFreezeWorldMatrix = null;
  59920. }
  59921. else {
  59922. currentMesh.computeWorldMatrix(true);
  59923. }
  59924. }
  59925. // Particles Systems
  59926. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  59927. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  59928. var parsedParticleSystem = parsedData.particleSystems[index];
  59929. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  59930. container.particleSystems.push(ps);
  59931. }
  59932. }
  59933. // Lens flares
  59934. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  59935. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  59936. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  59937. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  59938. container.lensFlareSystems.push(lf);
  59939. }
  59940. }
  59941. // Shadows
  59942. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  59943. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  59944. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  59945. var sg = BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  59946. container.shadowGenerators.push(sg);
  59947. }
  59948. }
  59949. // Lights exclusions / inclusions
  59950. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  59951. var light_2 = scene.lights[index];
  59952. // Excluded check
  59953. if (light_2._excludedMeshesIds.length > 0) {
  59954. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  59955. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  59956. if (excludedMesh) {
  59957. light_2.excludedMeshes.push(excludedMesh);
  59958. }
  59959. }
  59960. light_2._excludedMeshesIds = [];
  59961. }
  59962. // Included check
  59963. if (light_2._includedOnlyMeshesIds.length > 0) {
  59964. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  59965. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  59966. if (includedOnlyMesh) {
  59967. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  59968. }
  59969. }
  59970. light_2._includedOnlyMeshesIds = [];
  59971. }
  59972. }
  59973. // Actions (scene)
  59974. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  59975. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  59976. }
  59977. if (!addToScene) {
  59978. container.removeAllFromScene();
  59979. }
  59980. }
  59981. catch (err) {
  59982. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  59983. if (onError) {
  59984. onError(msg, err);
  59985. }
  59986. else {
  59987. BABYLON.Tools.Log(msg);
  59988. throw err;
  59989. }
  59990. }
  59991. finally {
  59992. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  59993. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  59994. }
  59995. }
  59996. return container;
  59997. };
  59998. BABYLON.SceneLoader.RegisterPlugin({
  59999. name: "babylon.js",
  60000. extensions: ".babylon",
  60001. canDirectLoad: function (data) {
  60002. if (data.indexOf("babylon") !== -1) {
  60003. return true;
  60004. }
  60005. return false;
  60006. },
  60007. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  60008. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  60009. // when SceneLoader.debugLogging = true (default), or exception encountered.
  60010. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  60011. // and avoid problems with multiple concurrent .babylon loads.
  60012. var log = "importMesh has failed JSON parse";
  60013. try {
  60014. var parsedData = JSON.parse(data);
  60015. log = "";
  60016. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  60017. if (!meshesNames) {
  60018. meshesNames = null;
  60019. }
  60020. else if (!Array.isArray(meshesNames)) {
  60021. meshesNames = [meshesNames];
  60022. }
  60023. var hierarchyIds = new Array();
  60024. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  60025. var loadedSkeletonsIds = [];
  60026. var loadedMaterialsIds = [];
  60027. var index;
  60028. var cache;
  60029. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  60030. var parsedMesh = parsedData.meshes[index];
  60031. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  60032. if (meshesNames !== null) {
  60033. // Remove found mesh name from list.
  60034. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  60035. }
  60036. //Geometry?
  60037. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  60038. //does the file contain geometries?
  60039. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  60040. //find the correct geometry and add it to the scene
  60041. var found = false;
  60042. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  60043. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  60044. return;
  60045. }
  60046. else {
  60047. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  60048. if (parsedGeometryData.id === parsedMesh.geometryId) {
  60049. switch (geometryType) {
  60050. case "boxes":
  60051. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  60052. break;
  60053. case "spheres":
  60054. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  60055. break;
  60056. case "cylinders":
  60057. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  60058. break;
  60059. case "toruses":
  60060. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  60061. break;
  60062. case "grounds":
  60063. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  60064. break;
  60065. case "planes":
  60066. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  60067. break;
  60068. case "torusKnots":
  60069. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  60070. break;
  60071. case "vertexData":
  60072. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  60073. break;
  60074. }
  60075. found = true;
  60076. }
  60077. });
  60078. }
  60079. });
  60080. if (found === false) {
  60081. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  60082. }
  60083. }
  60084. }
  60085. // Material ?
  60086. if (parsedMesh.materialId) {
  60087. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  60088. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  60089. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  60090. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  60091. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  60092. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  60093. var subMatId = parsedMultiMaterial.materials[matIndex];
  60094. loadedMaterialsIds.push(subMatId);
  60095. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  60096. if (mat) {
  60097. log += "\n\tMaterial " + mat.toString(fullDetails);
  60098. }
  60099. }
  60100. loadedMaterialsIds.push(parsedMultiMaterial.id);
  60101. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  60102. if (mmat) {
  60103. materialFound = true;
  60104. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  60105. }
  60106. break;
  60107. }
  60108. }
  60109. }
  60110. if (materialFound === false) {
  60111. loadedMaterialsIds.push(parsedMesh.materialId);
  60112. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  60113. if (!mat) {
  60114. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  60115. }
  60116. else {
  60117. log += "\n\tMaterial " + mat.toString(fullDetails);
  60118. }
  60119. }
  60120. }
  60121. // Skeleton ?
  60122. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  60123. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  60124. if (skeletonAlreadyLoaded === false) {
  60125. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  60126. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  60127. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  60128. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  60129. skeletons.push(skeleton);
  60130. loadedSkeletonsIds.push(parsedSkeleton.id);
  60131. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  60132. }
  60133. }
  60134. }
  60135. }
  60136. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  60137. meshes.push(mesh);
  60138. log += "\n\tMesh " + mesh.toString(fullDetails);
  60139. }
  60140. }
  60141. // Connecting parents
  60142. var currentMesh;
  60143. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  60144. currentMesh = scene.meshes[index];
  60145. if (currentMesh._waitingParentId) {
  60146. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  60147. currentMesh._waitingParentId = null;
  60148. }
  60149. }
  60150. // freeze and compute world matrix application
  60151. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  60152. currentMesh = scene.meshes[index];
  60153. if (currentMesh._waitingFreezeWorldMatrix) {
  60154. currentMesh.freezeWorldMatrix();
  60155. currentMesh._waitingFreezeWorldMatrix = null;
  60156. }
  60157. else {
  60158. currentMesh.computeWorldMatrix(true);
  60159. }
  60160. }
  60161. }
  60162. // Particles
  60163. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  60164. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  60165. var parsedParticleSystem = parsedData.particleSystems[index];
  60166. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  60167. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  60168. }
  60169. }
  60170. }
  60171. return true;
  60172. }
  60173. catch (err) {
  60174. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  60175. if (onError) {
  60176. onError(msg, err);
  60177. }
  60178. else {
  60179. BABYLON.Tools.Log(msg);
  60180. throw err;
  60181. }
  60182. }
  60183. finally {
  60184. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  60185. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  60186. }
  60187. }
  60188. return false;
  60189. },
  60190. load: function (scene, data, rootUrl, onError) {
  60191. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  60192. // when SceneLoader.debugLogging = true (default), or exception encountered.
  60193. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  60194. // and avoid problems with multiple concurrent .babylon loads.
  60195. var log = "importScene has failed JSON parse";
  60196. try {
  60197. var parsedData = JSON.parse(data);
  60198. log = "";
  60199. // Scene
  60200. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  60201. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  60202. }
  60203. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  60204. scene.autoClear = parsedData.autoClear;
  60205. }
  60206. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  60207. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  60208. }
  60209. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  60210. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  60211. }
  60212. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  60213. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  60214. }
  60215. // Fog
  60216. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  60217. scene.fogMode = parsedData.fogMode;
  60218. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  60219. scene.fogStart = parsedData.fogStart;
  60220. scene.fogEnd = parsedData.fogEnd;
  60221. scene.fogDensity = parsedData.fogDensity;
  60222. log += "\tFog mode for scene: ";
  60223. switch (scene.fogMode) {
  60224. // getters not compiling, so using hardcoded
  60225. case 1:
  60226. log += "exp\n";
  60227. break;
  60228. case 2:
  60229. log += "exp2\n";
  60230. break;
  60231. case 3:
  60232. log += "linear\n";
  60233. break;
  60234. }
  60235. }
  60236. //Physics
  60237. if (parsedData.physicsEnabled) {
  60238. var physicsPlugin;
  60239. if (parsedData.physicsEngine === "cannon") {
  60240. physicsPlugin = new BABYLON.CannonJSPlugin();
  60241. }
  60242. else if (parsedData.physicsEngine === "oimo") {
  60243. physicsPlugin = new BABYLON.OimoJSPlugin();
  60244. }
  60245. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  60246. //else - default engine, which is currently oimo
  60247. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  60248. scene.enablePhysics(physicsGravity, physicsPlugin);
  60249. }
  60250. // Metadata
  60251. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  60252. scene.metadata = parsedData.metadata;
  60253. }
  60254. //collisions, if defined. otherwise, default is true
  60255. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  60256. scene.collisionsEnabled = parsedData.collisionsEnabled;
  60257. }
  60258. scene.workerCollisions = !!parsedData.workerCollisions;
  60259. var container = loadAssetContainer(scene, data, rootUrl, onerror, true);
  60260. if (!container) {
  60261. return false;
  60262. }
  60263. if (parsedData.autoAnimate) {
  60264. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  60265. }
  60266. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  60267. scene.setActiveCameraByID(parsedData.activeCameraID);
  60268. }
  60269. // Environment texture
  60270. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  60271. scene.environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  60272. if (parsedData.createDefaultSkybox === true) {
  60273. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  60274. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  60275. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  60276. }
  60277. }
  60278. // Finish
  60279. return true;
  60280. }
  60281. catch (err) {
  60282. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  60283. if (onError) {
  60284. onError(msg, err);
  60285. }
  60286. else {
  60287. BABYLON.Tools.Log(msg);
  60288. throw err;
  60289. }
  60290. }
  60291. finally {
  60292. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  60293. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  60294. }
  60295. }
  60296. return false;
  60297. },
  60298. loadAssetContainer: function (scene, data, rootUrl, onError) {
  60299. var container = loadAssetContainer(scene, data, rootUrl, onerror);
  60300. return container;
  60301. }
  60302. });
  60303. })(BABYLON || (BABYLON = {}));
  60304. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  60305. var BABYLON;
  60306. (function (BABYLON) {
  60307. var FilesInput = /** @class */ (function () {
  60308. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  60309. this.onProcessFileCallback = function () { return true; };
  60310. this._engine = engine;
  60311. this._currentScene = scene;
  60312. this._sceneLoadedCallback = sceneLoadedCallback;
  60313. this._progressCallback = progressCallback;
  60314. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  60315. this._textureLoadingCallback = textureLoadingCallback;
  60316. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  60317. this._onReloadCallback = onReloadCallback;
  60318. this._errorCallback = errorCallback;
  60319. }
  60320. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  60321. var _this = this;
  60322. if (elementToMonitor) {
  60323. this._elementToMonitor = elementToMonitor;
  60324. this._dragEnterHandler = function (e) { _this.drag(e); };
  60325. this._dragOverHandler = function (e) { _this.drag(e); };
  60326. this._dropHandler = function (e) { _this.drop(e); };
  60327. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  60328. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  60329. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  60330. }
  60331. };
  60332. FilesInput.prototype.dispose = function () {
  60333. if (!this._elementToMonitor) {
  60334. return;
  60335. }
  60336. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  60337. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  60338. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  60339. };
  60340. FilesInput.prototype.renderFunction = function () {
  60341. if (this._additionalRenderLoopLogicCallback) {
  60342. this._additionalRenderLoopLogicCallback();
  60343. }
  60344. if (this._currentScene) {
  60345. if (this._textureLoadingCallback) {
  60346. var remaining = this._currentScene.getWaitingItemsCount();
  60347. if (remaining > 0) {
  60348. this._textureLoadingCallback(remaining);
  60349. }
  60350. }
  60351. this._currentScene.render();
  60352. }
  60353. };
  60354. FilesInput.prototype.drag = function (e) {
  60355. e.stopPropagation();
  60356. e.preventDefault();
  60357. };
  60358. FilesInput.prototype.drop = function (eventDrop) {
  60359. eventDrop.stopPropagation();
  60360. eventDrop.preventDefault();
  60361. this.loadFiles(eventDrop);
  60362. };
  60363. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  60364. var _this = this;
  60365. var reader = folder.createReader();
  60366. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  60367. reader.readEntries(function (entries) {
  60368. remaining.count += entries.length;
  60369. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  60370. var entry = entries_1[_i];
  60371. if (entry.isFile) {
  60372. entry.file(function (file) {
  60373. file.correctName = relativePath + file.name;
  60374. files.push(file);
  60375. if (--remaining.count === 0) {
  60376. callback();
  60377. }
  60378. });
  60379. }
  60380. else if (entry.isDirectory) {
  60381. _this._traverseFolder(entry, files, remaining, callback);
  60382. }
  60383. }
  60384. if (--remaining.count) {
  60385. callback();
  60386. }
  60387. });
  60388. };
  60389. FilesInput.prototype._processFiles = function (files) {
  60390. for (var i = 0; i < files.length; i++) {
  60391. var name = files[i].correctName.toLowerCase();
  60392. var extension = name.split('.').pop();
  60393. if (!this.onProcessFileCallback(files[i], name, extension)) {
  60394. continue;
  60395. }
  60396. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  60397. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  60398. this._sceneFileToLoad = files[i];
  60399. }
  60400. else {
  60401. FilesInput.FilesToLoad[name] = files[i];
  60402. }
  60403. }
  60404. };
  60405. FilesInput.prototype.loadFiles = function (event) {
  60406. var _this = this;
  60407. if (this._startingProcessingFilesCallback)
  60408. this._startingProcessingFilesCallback();
  60409. // Handling data transfer via drag'n'drop
  60410. if (event && event.dataTransfer && event.dataTransfer.files) {
  60411. this._filesToLoad = event.dataTransfer.files;
  60412. }
  60413. // Handling files from input files
  60414. if (event && event.target && event.target.files) {
  60415. this._filesToLoad = event.target.files;
  60416. }
  60417. if (this._filesToLoad && this._filesToLoad.length > 0) {
  60418. var files_1 = new Array();
  60419. var folders = [];
  60420. var items = event.dataTransfer ? event.dataTransfer.items : null;
  60421. for (var i = 0; i < this._filesToLoad.length; i++) {
  60422. var fileToLoad = this._filesToLoad[i];
  60423. var name_1 = fileToLoad.name.toLowerCase();
  60424. var entry = void 0;
  60425. fileToLoad.correctName = name_1;
  60426. if (items) {
  60427. var item = items[i];
  60428. if (item.getAsEntry) {
  60429. entry = item.getAsEntry();
  60430. }
  60431. else if (item.webkitGetAsEntry) {
  60432. entry = item.webkitGetAsEntry();
  60433. }
  60434. }
  60435. if (!entry) {
  60436. files_1.push(fileToLoad);
  60437. }
  60438. else {
  60439. if (entry.isDirectory) {
  60440. folders.push(entry);
  60441. }
  60442. else {
  60443. files_1.push(fileToLoad);
  60444. }
  60445. }
  60446. }
  60447. if (folders.length === 0) {
  60448. this._processFiles(files_1);
  60449. this._processReload();
  60450. }
  60451. else {
  60452. var remaining = { count: folders.length };
  60453. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  60454. var folder = folders_1[_i];
  60455. this._traverseFolder(folder, files_1, remaining, function () {
  60456. _this._processFiles(files_1);
  60457. if (remaining.count === 0) {
  60458. _this._processReload();
  60459. }
  60460. });
  60461. }
  60462. }
  60463. }
  60464. };
  60465. FilesInput.prototype._processReload = function () {
  60466. if (this._onReloadCallback) {
  60467. this._onReloadCallback(this._sceneFileToLoad);
  60468. }
  60469. else {
  60470. this.reload();
  60471. }
  60472. };
  60473. FilesInput.prototype.reload = function () {
  60474. var _this = this;
  60475. // If a scene file has been provided
  60476. if (this._sceneFileToLoad) {
  60477. if (this._currentScene) {
  60478. if (BABYLON.Tools.errorsCount > 0) {
  60479. BABYLON.Tools.ClearLogCache();
  60480. }
  60481. this._engine.stopRenderLoop();
  60482. this._currentScene.dispose();
  60483. }
  60484. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad, this._engine, function (progress) {
  60485. if (_this._progressCallback) {
  60486. _this._progressCallback(progress);
  60487. }
  60488. }).then(function (scene) {
  60489. _this._currentScene = scene;
  60490. if (_this._sceneLoadedCallback) {
  60491. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  60492. }
  60493. // Wait for textures and shaders to be ready
  60494. _this._currentScene.executeWhenReady(function () {
  60495. _this._engine.runRenderLoop(function () {
  60496. _this.renderFunction();
  60497. });
  60498. });
  60499. }).catch(function (error) {
  60500. if (_this._errorCallback) {
  60501. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  60502. }
  60503. });
  60504. }
  60505. else {
  60506. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  60507. }
  60508. };
  60509. FilesInput.FilesToLoad = {};
  60510. return FilesInput;
  60511. }());
  60512. BABYLON.FilesInput = FilesInput;
  60513. })(BABYLON || (BABYLON = {}));
  60514. //# sourceMappingURL=babylon.filesInput.js.map
  60515. var BABYLON;
  60516. (function (BABYLON) {
  60517. /**
  60518. * This class implement a typical dictionary using a string as key and the generic type T as value.
  60519. * The underlying implementation relies on an associative array to ensure the best performances.
  60520. * The value can be anything including 'null' but except 'undefined'
  60521. */
  60522. var StringDictionary = /** @class */ (function () {
  60523. function StringDictionary() {
  60524. this._count = 0;
  60525. this._data = {};
  60526. }
  60527. /**
  60528. * This will clear this dictionary and copy the content from the 'source' one.
  60529. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  60530. * @param source the dictionary to take the content from and copy to this dictionary
  60531. */
  60532. StringDictionary.prototype.copyFrom = function (source) {
  60533. var _this = this;
  60534. this.clear();
  60535. source.forEach(function (t, v) { return _this.add(t, v); });
  60536. };
  60537. /**
  60538. * Get a value based from its key
  60539. * @param key the given key to get the matching value from
  60540. * @return the value if found, otherwise undefined is returned
  60541. */
  60542. StringDictionary.prototype.get = function (key) {
  60543. var val = this._data[key];
  60544. if (val !== undefined) {
  60545. return val;
  60546. }
  60547. return undefined;
  60548. };
  60549. /**
  60550. * Get a value from its key or add it if it doesn't exist.
  60551. * This method will ensure you that a given key/data will be present in the dictionary.
  60552. * @param key the given key to get the matching value from
  60553. * @param factory the factory that will create the value if the key is not present in the dictionary.
  60554. * The factory will only be invoked if there's no data for the given key.
  60555. * @return the value corresponding to the key.
  60556. */
  60557. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  60558. var val = this.get(key);
  60559. if (val !== undefined) {
  60560. return val;
  60561. }
  60562. val = factory(key);
  60563. if (val) {
  60564. this.add(key, val);
  60565. }
  60566. return val;
  60567. };
  60568. /**
  60569. * Get a value from its key if present in the dictionary otherwise add it
  60570. * @param key the key to get the value from
  60571. * @param val if there's no such key/value pair in the dictionary add it with this value
  60572. * @return the value corresponding to the key
  60573. */
  60574. StringDictionary.prototype.getOrAdd = function (key, val) {
  60575. var curVal = this.get(key);
  60576. if (curVal !== undefined) {
  60577. return curVal;
  60578. }
  60579. this.add(key, val);
  60580. return val;
  60581. };
  60582. /**
  60583. * Check if there's a given key in the dictionary
  60584. * @param key the key to check for
  60585. * @return true if the key is present, false otherwise
  60586. */
  60587. StringDictionary.prototype.contains = function (key) {
  60588. return this._data[key] !== undefined;
  60589. };
  60590. /**
  60591. * Add a new key and its corresponding value
  60592. * @param key the key to add
  60593. * @param value the value corresponding to the key
  60594. * @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
  60595. */
  60596. StringDictionary.prototype.add = function (key, value) {
  60597. if (this._data[key] !== undefined) {
  60598. return false;
  60599. }
  60600. this._data[key] = value;
  60601. ++this._count;
  60602. return true;
  60603. };
  60604. StringDictionary.prototype.set = function (key, value) {
  60605. if (this._data[key] === undefined) {
  60606. return false;
  60607. }
  60608. this._data[key] = value;
  60609. return true;
  60610. };
  60611. /**
  60612. * Get the element of the given key and remove it from the dictionary
  60613. * @param key
  60614. */
  60615. StringDictionary.prototype.getAndRemove = function (key) {
  60616. var val = this.get(key);
  60617. if (val !== undefined) {
  60618. delete this._data[key];
  60619. --this._count;
  60620. return val;
  60621. }
  60622. return null;
  60623. };
  60624. /**
  60625. * Remove a key/value from the dictionary.
  60626. * @param key the key to remove
  60627. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  60628. */
  60629. StringDictionary.prototype.remove = function (key) {
  60630. if (this.contains(key)) {
  60631. delete this._data[key];
  60632. --this._count;
  60633. return true;
  60634. }
  60635. return false;
  60636. };
  60637. /**
  60638. * Clear the whole content of the dictionary
  60639. */
  60640. StringDictionary.prototype.clear = function () {
  60641. this._data = {};
  60642. this._count = 0;
  60643. };
  60644. Object.defineProperty(StringDictionary.prototype, "count", {
  60645. get: function () {
  60646. return this._count;
  60647. },
  60648. enumerable: true,
  60649. configurable: true
  60650. });
  60651. /**
  60652. * Execute a callback on each key/val of the dictionary.
  60653. * Note that you can remove any element in this dictionary in the callback implementation
  60654. * @param callback the callback to execute on a given key/value pair
  60655. */
  60656. StringDictionary.prototype.forEach = function (callback) {
  60657. for (var cur in this._data) {
  60658. var val = this._data[cur];
  60659. callback(cur, val);
  60660. }
  60661. };
  60662. /**
  60663. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  60664. * If the callback returns null or undefined the method will iterate to the next key/value pair
  60665. * Note that you can remove any element in this dictionary in the callback implementation
  60666. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  60667. */
  60668. StringDictionary.prototype.first = function (callback) {
  60669. for (var cur in this._data) {
  60670. var val = this._data[cur];
  60671. var res = callback(cur, val);
  60672. if (res) {
  60673. return res;
  60674. }
  60675. }
  60676. return null;
  60677. };
  60678. return StringDictionary;
  60679. }());
  60680. BABYLON.StringDictionary = StringDictionary;
  60681. })(BABYLON || (BABYLON = {}));
  60682. //# sourceMappingURL=babylon.stringDictionary.js.map
  60683. var BABYLON;
  60684. (function (BABYLON) {
  60685. var Tags = /** @class */ (function () {
  60686. function Tags() {
  60687. }
  60688. Tags.EnableFor = function (obj) {
  60689. obj._tags = obj._tags || {};
  60690. obj.hasTags = function () {
  60691. return Tags.HasTags(obj);
  60692. };
  60693. obj.addTags = function (tagsString) {
  60694. return Tags.AddTagsTo(obj, tagsString);
  60695. };
  60696. obj.removeTags = function (tagsString) {
  60697. return Tags.RemoveTagsFrom(obj, tagsString);
  60698. };
  60699. obj.matchesTagsQuery = function (tagsQuery) {
  60700. return Tags.MatchesQuery(obj, tagsQuery);
  60701. };
  60702. };
  60703. Tags.DisableFor = function (obj) {
  60704. delete obj._tags;
  60705. delete obj.hasTags;
  60706. delete obj.addTags;
  60707. delete obj.removeTags;
  60708. delete obj.matchesTagsQuery;
  60709. };
  60710. Tags.HasTags = function (obj) {
  60711. if (!obj._tags) {
  60712. return false;
  60713. }
  60714. return !BABYLON.Tools.IsEmpty(obj._tags);
  60715. };
  60716. Tags.GetTags = function (obj, asString) {
  60717. if (asString === void 0) { asString = true; }
  60718. if (!obj._tags) {
  60719. return null;
  60720. }
  60721. if (asString) {
  60722. var tagsArray = [];
  60723. for (var tag in obj._tags) {
  60724. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  60725. tagsArray.push(tag);
  60726. }
  60727. }
  60728. return tagsArray.join(" ");
  60729. }
  60730. else {
  60731. return obj._tags;
  60732. }
  60733. };
  60734. // the tags 'true' and 'false' are reserved and cannot be used as tags
  60735. // a tag cannot start with '||', '&&', and '!'
  60736. // it cannot contain whitespaces
  60737. Tags.AddTagsTo = function (obj, tagsString) {
  60738. if (!tagsString) {
  60739. return;
  60740. }
  60741. if (typeof tagsString !== "string") {
  60742. return;
  60743. }
  60744. var tags = tagsString.split(" ");
  60745. tags.forEach(function (tag, index, array) {
  60746. Tags._AddTagTo(obj, tag);
  60747. });
  60748. };
  60749. Tags._AddTagTo = function (obj, tag) {
  60750. tag = tag.trim();
  60751. if (tag === "" || tag === "true" || tag === "false") {
  60752. return;
  60753. }
  60754. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  60755. return;
  60756. }
  60757. Tags.EnableFor(obj);
  60758. obj._tags[tag] = true;
  60759. };
  60760. Tags.RemoveTagsFrom = function (obj, tagsString) {
  60761. if (!Tags.HasTags(obj)) {
  60762. return;
  60763. }
  60764. var tags = tagsString.split(" ");
  60765. for (var t in tags) {
  60766. Tags._RemoveTagFrom(obj, tags[t]);
  60767. }
  60768. };
  60769. Tags._RemoveTagFrom = function (obj, tag) {
  60770. delete obj._tags[tag];
  60771. };
  60772. Tags.MatchesQuery = function (obj, tagsQuery) {
  60773. if (tagsQuery === undefined) {
  60774. return true;
  60775. }
  60776. if (tagsQuery === "") {
  60777. return Tags.HasTags(obj);
  60778. }
  60779. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  60780. };
  60781. return Tags;
  60782. }());
  60783. BABYLON.Tags = Tags;
  60784. })(BABYLON || (BABYLON = {}));
  60785. //# sourceMappingURL=babylon.tags.js.map
  60786. var BABYLON;
  60787. (function (BABYLON) {
  60788. var AndOrNotEvaluator = /** @class */ (function () {
  60789. function AndOrNotEvaluator() {
  60790. }
  60791. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  60792. if (!query.match(/\([^\(\)]*\)/g)) {
  60793. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  60794. }
  60795. else {
  60796. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  60797. // remove parenthesis
  60798. r = r.slice(1, r.length - 1);
  60799. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  60800. });
  60801. }
  60802. if (query === "true") {
  60803. return true;
  60804. }
  60805. if (query === "false") {
  60806. return false;
  60807. }
  60808. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  60809. };
  60810. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  60811. evaluateCallback = evaluateCallback || (function (r) {
  60812. return r === "true" ? true : false;
  60813. });
  60814. var result;
  60815. var or = parenthesisContent.split("||");
  60816. for (var i in or) {
  60817. if (or.hasOwnProperty(i)) {
  60818. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  60819. var and = ori.split("&&");
  60820. if (and.length > 1) {
  60821. for (var j = 0; j < and.length; ++j) {
  60822. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  60823. if (andj !== "true" && andj !== "false") {
  60824. if (andj[0] === "!") {
  60825. result = !evaluateCallback(andj.substring(1));
  60826. }
  60827. else {
  60828. result = evaluateCallback(andj);
  60829. }
  60830. }
  60831. else {
  60832. result = andj === "true" ? true : false;
  60833. }
  60834. if (!result) {
  60835. ori = "false";
  60836. break;
  60837. }
  60838. }
  60839. }
  60840. if (result || ori === "true") {
  60841. result = true;
  60842. break;
  60843. }
  60844. // result equals false (or undefined)
  60845. if (ori !== "true" && ori !== "false") {
  60846. if (ori[0] === "!") {
  60847. result = !evaluateCallback(ori.substring(1));
  60848. }
  60849. else {
  60850. result = evaluateCallback(ori);
  60851. }
  60852. }
  60853. else {
  60854. result = ori === "true" ? true : false;
  60855. }
  60856. }
  60857. }
  60858. // the whole parenthesis scope is replaced by 'true' or 'false'
  60859. return result ? "true" : "false";
  60860. };
  60861. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  60862. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  60863. // remove whitespaces
  60864. r = r.replace(/[\s]/g, function () { return ""; });
  60865. return r.length % 2 ? "!" : "";
  60866. });
  60867. booleanString = booleanString.trim();
  60868. if (booleanString === "!true") {
  60869. booleanString = "false";
  60870. }
  60871. else if (booleanString === "!false") {
  60872. booleanString = "true";
  60873. }
  60874. return booleanString;
  60875. };
  60876. return AndOrNotEvaluator;
  60877. }());
  60878. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  60879. })(BABYLON || (BABYLON = {}));
  60880. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  60881. var BABYLON;
  60882. (function (BABYLON) {
  60883. var Database = /** @class */ (function () {
  60884. function Database(urlToScene, callbackManifestChecked) {
  60885. // Handling various flavors of prefixed version of IndexedDB
  60886. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  60887. this.callbackManifestChecked = callbackManifestChecked;
  60888. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  60889. this.db = null;
  60890. this._enableSceneOffline = false;
  60891. this._enableTexturesOffline = false;
  60892. this.manifestVersionFound = 0;
  60893. this.mustUpdateRessources = false;
  60894. this.hasReachedQuota = false;
  60895. if (!Database.IDBStorageEnabled) {
  60896. this.callbackManifestChecked(true);
  60897. }
  60898. else {
  60899. this.checkManifestFile();
  60900. }
  60901. }
  60902. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  60903. get: function () {
  60904. return this._enableSceneOffline;
  60905. },
  60906. enumerable: true,
  60907. configurable: true
  60908. });
  60909. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  60910. get: function () {
  60911. return this._enableTexturesOffline;
  60912. },
  60913. enumerable: true,
  60914. configurable: true
  60915. });
  60916. Database.prototype.checkManifestFile = function () {
  60917. var _this = this;
  60918. var noManifestFile = function () {
  60919. _this._enableSceneOffline = false;
  60920. _this._enableTexturesOffline = false;
  60921. _this.callbackManifestChecked(false);
  60922. };
  60923. var timeStampUsed = false;
  60924. var manifestURL = this.currentSceneUrl + ".manifest";
  60925. var xhr = new XMLHttpRequest();
  60926. if (navigator.onLine) {
  60927. // Adding a timestamp to by-pass browsers' cache
  60928. timeStampUsed = true;
  60929. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  60930. }
  60931. xhr.open("GET", manifestURL, true);
  60932. xhr.addEventListener("load", function () {
  60933. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  60934. try {
  60935. var manifestFile = JSON.parse(xhr.response);
  60936. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  60937. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  60938. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  60939. _this.manifestVersionFound = manifestFile.version;
  60940. }
  60941. if (_this.callbackManifestChecked) {
  60942. _this.callbackManifestChecked(true);
  60943. }
  60944. }
  60945. catch (ex) {
  60946. noManifestFile();
  60947. }
  60948. }
  60949. else {
  60950. noManifestFile();
  60951. }
  60952. }, false);
  60953. xhr.addEventListener("error", function (event) {
  60954. if (timeStampUsed) {
  60955. timeStampUsed = false;
  60956. // Let's retry without the timeStamp
  60957. // It could fail when coupled with HTML5 Offline API
  60958. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  60959. xhr.open("GET", retryManifestURL, true);
  60960. xhr.send();
  60961. }
  60962. else {
  60963. noManifestFile();
  60964. }
  60965. }, false);
  60966. try {
  60967. xhr.send();
  60968. }
  60969. catch (ex) {
  60970. BABYLON.Tools.Error("Error on XHR send request.");
  60971. this.callbackManifestChecked(false);
  60972. }
  60973. };
  60974. Database.prototype.openAsync = function (successCallback, errorCallback) {
  60975. var _this = this;
  60976. var handleError = function () {
  60977. _this.isSupported = false;
  60978. if (errorCallback)
  60979. errorCallback();
  60980. };
  60981. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  60982. // Your browser doesn't support IndexedDB
  60983. this.isSupported = false;
  60984. if (errorCallback)
  60985. errorCallback();
  60986. }
  60987. else {
  60988. // If the DB hasn't been opened or created yet
  60989. if (!this.db) {
  60990. this.hasReachedQuota = false;
  60991. this.isSupported = true;
  60992. var request = this.idbFactory.open("babylonjs", 1);
  60993. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  60994. request.onerror = function (event) {
  60995. handleError();
  60996. };
  60997. // executes when a version change transaction cannot complete due to other active transactions
  60998. request.onblocked = function (event) {
  60999. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  61000. handleError();
  61001. };
  61002. // DB has been opened successfully
  61003. request.onsuccess = function (event) {
  61004. _this.db = request.result;
  61005. successCallback();
  61006. };
  61007. // Initialization of the DB. Creating Scenes & Textures stores
  61008. request.onupgradeneeded = function (event) {
  61009. _this.db = (event.target).result;
  61010. if (_this.db) {
  61011. try {
  61012. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  61013. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  61014. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  61015. }
  61016. catch (ex) {
  61017. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  61018. handleError();
  61019. }
  61020. }
  61021. };
  61022. }
  61023. else {
  61024. if (successCallback)
  61025. successCallback();
  61026. }
  61027. }
  61028. };
  61029. Database.prototype.loadImageFromDB = function (url, image) {
  61030. var _this = this;
  61031. var completeURL = Database.ReturnFullUrlLocation(url);
  61032. var saveAndLoadImage = function () {
  61033. if (!_this.hasReachedQuota && _this.db !== null) {
  61034. // the texture is not yet in the DB, let's try to save it
  61035. _this._saveImageIntoDBAsync(completeURL, image);
  61036. }
  61037. else {
  61038. image.src = url;
  61039. }
  61040. };
  61041. if (!this.mustUpdateRessources) {
  61042. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  61043. }
  61044. else {
  61045. saveAndLoadImage();
  61046. }
  61047. };
  61048. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  61049. if (this.isSupported && this.db !== null) {
  61050. var texture;
  61051. var transaction = this.db.transaction(["textures"]);
  61052. transaction.onabort = function (event) {
  61053. image.src = url;
  61054. };
  61055. transaction.oncomplete = function (event) {
  61056. var blobTextureURL;
  61057. if (texture) {
  61058. var URL = window.URL || window.webkitURL;
  61059. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  61060. image.onerror = function () {
  61061. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  61062. image.src = url;
  61063. };
  61064. image.src = blobTextureURL;
  61065. }
  61066. else {
  61067. notInDBCallback();
  61068. }
  61069. };
  61070. var getRequest = transaction.objectStore("textures").get(url);
  61071. getRequest.onsuccess = function (event) {
  61072. texture = (event.target).result;
  61073. };
  61074. getRequest.onerror = function (event) {
  61075. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  61076. image.src = url;
  61077. };
  61078. }
  61079. else {
  61080. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  61081. image.src = url;
  61082. }
  61083. };
  61084. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  61085. var _this = this;
  61086. if (this.isSupported) {
  61087. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  61088. var generateBlobUrl = function () {
  61089. var blobTextureURL;
  61090. if (blob) {
  61091. var URL = window.URL || window.webkitURL;
  61092. try {
  61093. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  61094. }
  61095. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  61096. catch (ex) {
  61097. blobTextureURL = URL.createObjectURL(blob);
  61098. }
  61099. }
  61100. if (blobTextureURL) {
  61101. image.src = blobTextureURL;
  61102. }
  61103. };
  61104. if (Database.IsUASupportingBlobStorage) {
  61105. var xhr = new XMLHttpRequest(), blob;
  61106. xhr.open("GET", url, true);
  61107. xhr.responseType = "blob";
  61108. xhr.addEventListener("load", function () {
  61109. if (xhr.status === 200 && _this.db) {
  61110. // Blob as response (XHR2)
  61111. blob = xhr.response;
  61112. var transaction = _this.db.transaction(["textures"], "readwrite");
  61113. // the transaction could abort because of a QuotaExceededError error
  61114. transaction.onabort = function (event) {
  61115. try {
  61116. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  61117. var srcElement = (event.srcElement || event.target);
  61118. var error = srcElement.error;
  61119. if (error && error.name === "QuotaExceededError") {
  61120. _this.hasReachedQuota = true;
  61121. }
  61122. }
  61123. catch (ex) { }
  61124. generateBlobUrl();
  61125. };
  61126. transaction.oncomplete = function (event) {
  61127. generateBlobUrl();
  61128. };
  61129. var newTexture = { textureUrl: url, data: blob };
  61130. try {
  61131. // Put the blob into the dabase
  61132. var addRequest = transaction.objectStore("textures").put(newTexture);
  61133. addRequest.onsuccess = function (event) {
  61134. };
  61135. addRequest.onerror = function (event) {
  61136. generateBlobUrl();
  61137. };
  61138. }
  61139. catch (ex) {
  61140. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  61141. if (ex.code === 25) {
  61142. Database.IsUASupportingBlobStorage = false;
  61143. }
  61144. image.src = url;
  61145. }
  61146. }
  61147. else {
  61148. image.src = url;
  61149. }
  61150. }, false);
  61151. xhr.addEventListener("error", function (event) {
  61152. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  61153. image.src = url;
  61154. }, false);
  61155. xhr.send();
  61156. }
  61157. else {
  61158. image.src = url;
  61159. }
  61160. }
  61161. else {
  61162. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  61163. image.src = url;
  61164. }
  61165. };
  61166. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  61167. var _this = this;
  61168. var updateVersion = function () {
  61169. // the version is not yet in the DB or we need to update it
  61170. _this._saveVersionIntoDBAsync(url, versionLoaded);
  61171. };
  61172. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  61173. };
  61174. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  61175. var _this = this;
  61176. if (this.isSupported && this.db) {
  61177. var version;
  61178. try {
  61179. var transaction = this.db.transaction(["versions"]);
  61180. transaction.oncomplete = function (event) {
  61181. if (version) {
  61182. // If the version in the JSON file is > than the version in DB
  61183. if (_this.manifestVersionFound > version.data) {
  61184. _this.mustUpdateRessources = true;
  61185. updateInDBCallback();
  61186. }
  61187. else {
  61188. callback(version.data);
  61189. }
  61190. }
  61191. else {
  61192. _this.mustUpdateRessources = true;
  61193. updateInDBCallback();
  61194. }
  61195. };
  61196. transaction.onabort = function (event) {
  61197. callback(-1);
  61198. };
  61199. var getRequest = transaction.objectStore("versions").get(url);
  61200. getRequest.onsuccess = function (event) {
  61201. version = (event.target).result;
  61202. };
  61203. getRequest.onerror = function (event) {
  61204. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  61205. callback(-1);
  61206. };
  61207. }
  61208. catch (ex) {
  61209. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  61210. callback(-1);
  61211. }
  61212. }
  61213. else {
  61214. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  61215. callback(-1);
  61216. }
  61217. };
  61218. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  61219. var _this = this;
  61220. if (this.isSupported && !this.hasReachedQuota && this.db) {
  61221. try {
  61222. // Open a transaction to the database
  61223. var transaction = this.db.transaction(["versions"], "readwrite");
  61224. // the transaction could abort because of a QuotaExceededError error
  61225. transaction.onabort = function (event) {
  61226. try {
  61227. var error = event.srcElement['error'];
  61228. if (error && error.name === "QuotaExceededError") {
  61229. _this.hasReachedQuota = true;
  61230. }
  61231. }
  61232. catch (ex) { }
  61233. callback(-1);
  61234. };
  61235. transaction.oncomplete = function (event) {
  61236. callback(_this.manifestVersionFound);
  61237. };
  61238. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  61239. // Put the scene into the database
  61240. var addRequest = transaction.objectStore("versions").put(newVersion);
  61241. addRequest.onsuccess = function (event) {
  61242. };
  61243. addRequest.onerror = function (event) {
  61244. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  61245. };
  61246. }
  61247. catch (ex) {
  61248. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  61249. callback(-1);
  61250. }
  61251. }
  61252. else {
  61253. callback(-1);
  61254. }
  61255. };
  61256. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  61257. var _this = this;
  61258. var completeUrl = Database.ReturnFullUrlLocation(url);
  61259. var saveAndLoadFile = function () {
  61260. // the scene is not yet in the DB, let's try to save it
  61261. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  61262. };
  61263. this._checkVersionFromDB(completeUrl, function (version) {
  61264. if (version !== -1) {
  61265. if (!_this.mustUpdateRessources) {
  61266. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  61267. }
  61268. else {
  61269. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  61270. }
  61271. }
  61272. else {
  61273. if (errorCallback) {
  61274. errorCallback();
  61275. }
  61276. }
  61277. });
  61278. };
  61279. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  61280. if (this.isSupported && this.db) {
  61281. var targetStore;
  61282. if (url.indexOf(".babylon") !== -1) {
  61283. targetStore = "scenes";
  61284. }
  61285. else {
  61286. targetStore = "textures";
  61287. }
  61288. var file;
  61289. var transaction = this.db.transaction([targetStore]);
  61290. transaction.oncomplete = function (event) {
  61291. if (file) {
  61292. callback(file.data);
  61293. }
  61294. else {
  61295. notInDBCallback();
  61296. }
  61297. };
  61298. transaction.onabort = function (event) {
  61299. notInDBCallback();
  61300. };
  61301. var getRequest = transaction.objectStore(targetStore).get(url);
  61302. getRequest.onsuccess = function (event) {
  61303. file = (event.target).result;
  61304. };
  61305. getRequest.onerror = function (event) {
  61306. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  61307. notInDBCallback();
  61308. };
  61309. }
  61310. else {
  61311. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  61312. callback();
  61313. }
  61314. };
  61315. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  61316. var _this = this;
  61317. if (this.isSupported) {
  61318. var targetStore;
  61319. if (url.indexOf(".babylon") !== -1) {
  61320. targetStore = "scenes";
  61321. }
  61322. else {
  61323. targetStore = "textures";
  61324. }
  61325. // Create XHR
  61326. var xhr = new XMLHttpRequest();
  61327. var fileData;
  61328. xhr.open("GET", url, true);
  61329. if (useArrayBuffer) {
  61330. xhr.responseType = "arraybuffer";
  61331. }
  61332. if (progressCallback) {
  61333. xhr.onprogress = progressCallback;
  61334. }
  61335. xhr.addEventListener("load", function () {
  61336. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  61337. // Blob as response (XHR2)
  61338. //fileData = xhr.responseText;
  61339. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  61340. if (!_this.hasReachedQuota && _this.db) {
  61341. // Open a transaction to the database
  61342. var transaction = _this.db.transaction([targetStore], "readwrite");
  61343. // the transaction could abort because of a QuotaExceededError error
  61344. transaction.onabort = function (event) {
  61345. try {
  61346. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  61347. var error = event.srcElement['error'];
  61348. if (error && error.name === "QuotaExceededError") {
  61349. _this.hasReachedQuota = true;
  61350. }
  61351. }
  61352. catch (ex) { }
  61353. callback(fileData);
  61354. };
  61355. transaction.oncomplete = function (event) {
  61356. callback(fileData);
  61357. };
  61358. var newFile;
  61359. if (targetStore === "scenes") {
  61360. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  61361. }
  61362. else {
  61363. newFile = { textureUrl: url, data: fileData };
  61364. }
  61365. try {
  61366. // Put the scene into the database
  61367. var addRequest = transaction.objectStore(targetStore).put(newFile);
  61368. addRequest.onsuccess = function (event) {
  61369. };
  61370. addRequest.onerror = function (event) {
  61371. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  61372. };
  61373. }
  61374. catch (ex) {
  61375. callback(fileData);
  61376. }
  61377. }
  61378. else {
  61379. callback(fileData);
  61380. }
  61381. }
  61382. else {
  61383. callback();
  61384. }
  61385. }, false);
  61386. xhr.addEventListener("error", function (event) {
  61387. BABYLON.Tools.Error("error on XHR request.");
  61388. callback();
  61389. }, false);
  61390. xhr.send();
  61391. }
  61392. else {
  61393. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  61394. callback();
  61395. }
  61396. };
  61397. Database.IsUASupportingBlobStorage = true;
  61398. Database.IDBStorageEnabled = true;
  61399. Database.parseURL = function (url) {
  61400. var a = document.createElement('a');
  61401. a.href = url;
  61402. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  61403. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  61404. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  61405. return absLocation;
  61406. };
  61407. Database.ReturnFullUrlLocation = function (url) {
  61408. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  61409. return (Database.parseURL(window.location.href) + url);
  61410. }
  61411. else {
  61412. return url;
  61413. }
  61414. };
  61415. return Database;
  61416. }());
  61417. BABYLON.Database = Database;
  61418. })(BABYLON || (BABYLON = {}));
  61419. //# sourceMappingURL=babylon.database.js.map
  61420. var BABYLON;
  61421. (function (BABYLON) {
  61422. var FresnelParameters = /** @class */ (function () {
  61423. function FresnelParameters() {
  61424. this._isEnabled = true;
  61425. this.leftColor = BABYLON.Color3.White();
  61426. this.rightColor = BABYLON.Color3.Black();
  61427. this.bias = 0;
  61428. this.power = 1;
  61429. }
  61430. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  61431. get: function () {
  61432. return this._isEnabled;
  61433. },
  61434. set: function (value) {
  61435. if (this._isEnabled === value) {
  61436. return;
  61437. }
  61438. this._isEnabled = value;
  61439. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  61440. },
  61441. enumerable: true,
  61442. configurable: true
  61443. });
  61444. FresnelParameters.prototype.clone = function () {
  61445. var newFresnelParameters = new FresnelParameters();
  61446. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  61447. return newFresnelParameters;
  61448. };
  61449. FresnelParameters.prototype.serialize = function () {
  61450. var serializationObject = {};
  61451. serializationObject.isEnabled = this.isEnabled;
  61452. serializationObject.leftColor = this.leftColor;
  61453. serializationObject.rightColor = this.rightColor;
  61454. serializationObject.bias = this.bias;
  61455. serializationObject.power = this.power;
  61456. return serializationObject;
  61457. };
  61458. FresnelParameters.Parse = function (parsedFresnelParameters) {
  61459. var fresnelParameters = new FresnelParameters();
  61460. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  61461. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  61462. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  61463. fresnelParameters.bias = parsedFresnelParameters.bias;
  61464. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  61465. return fresnelParameters;
  61466. };
  61467. return FresnelParameters;
  61468. }());
  61469. BABYLON.FresnelParameters = FresnelParameters;
  61470. })(BABYLON || (BABYLON = {}));
  61471. //# sourceMappingURL=babylon.fresnelParameters.js.map
  61472. var BABYLON;
  61473. (function (BABYLON) {
  61474. var MultiMaterial = /** @class */ (function (_super) {
  61475. __extends(MultiMaterial, _super);
  61476. function MultiMaterial(name, scene) {
  61477. var _this = _super.call(this, name, scene, true) || this;
  61478. scene.multiMaterials.push(_this);
  61479. _this.subMaterials = new Array();
  61480. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  61481. return _this;
  61482. }
  61483. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  61484. get: function () {
  61485. return this._subMaterials;
  61486. },
  61487. set: function (value) {
  61488. this._subMaterials = value;
  61489. this._hookArray(value);
  61490. },
  61491. enumerable: true,
  61492. configurable: true
  61493. });
  61494. MultiMaterial.prototype._hookArray = function (array) {
  61495. var _this = this;
  61496. var oldPush = array.push;
  61497. array.push = function () {
  61498. var items = [];
  61499. for (var _i = 0; _i < arguments.length; _i++) {
  61500. items[_i] = arguments[_i];
  61501. }
  61502. var result = oldPush.apply(array, items);
  61503. _this._markAllSubMeshesAsTexturesDirty();
  61504. return result;
  61505. };
  61506. var oldSplice = array.splice;
  61507. array.splice = function (index, deleteCount) {
  61508. var deleted = oldSplice.apply(array, [index, deleteCount]);
  61509. _this._markAllSubMeshesAsTexturesDirty();
  61510. return deleted;
  61511. };
  61512. };
  61513. // Properties
  61514. MultiMaterial.prototype.getSubMaterial = function (index) {
  61515. if (index < 0 || index >= this.subMaterials.length) {
  61516. return this.getScene().defaultMaterial;
  61517. }
  61518. return this.subMaterials[index];
  61519. };
  61520. MultiMaterial.prototype.getActiveTextures = function () {
  61521. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  61522. if (subMaterial) {
  61523. return subMaterial.getActiveTextures();
  61524. }
  61525. else {
  61526. return [];
  61527. }
  61528. }));
  61529. var _a;
  61530. };
  61531. // Methods
  61532. MultiMaterial.prototype.getClassName = function () {
  61533. return "MultiMaterial";
  61534. };
  61535. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  61536. for (var index = 0; index < this.subMaterials.length; index++) {
  61537. var subMaterial = this.subMaterials[index];
  61538. if (subMaterial) {
  61539. if (subMaterial.storeEffectOnSubMeshes) {
  61540. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  61541. return false;
  61542. }
  61543. continue;
  61544. }
  61545. if (!subMaterial.isReady(mesh)) {
  61546. return false;
  61547. }
  61548. }
  61549. }
  61550. return true;
  61551. };
  61552. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  61553. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  61554. for (var index = 0; index < this.subMaterials.length; index++) {
  61555. var subMaterial = null;
  61556. var current = this.subMaterials[index];
  61557. if (cloneChildren && current) {
  61558. subMaterial = current.clone(name + "-" + current.name);
  61559. }
  61560. else {
  61561. subMaterial = this.subMaterials[index];
  61562. }
  61563. newMultiMaterial.subMaterials.push(subMaterial);
  61564. }
  61565. return newMultiMaterial;
  61566. };
  61567. MultiMaterial.prototype.serialize = function () {
  61568. var serializationObject = {};
  61569. serializationObject.name = this.name;
  61570. serializationObject.id = this.id;
  61571. if (BABYLON.Tags) {
  61572. serializationObject.tags = BABYLON.Tags.GetTags(this);
  61573. }
  61574. serializationObject.materials = [];
  61575. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  61576. var subMat = this.subMaterials[matIndex];
  61577. if (subMat) {
  61578. serializationObject.materials.push(subMat.id);
  61579. }
  61580. else {
  61581. serializationObject.materials.push(null);
  61582. }
  61583. }
  61584. return serializationObject;
  61585. };
  61586. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  61587. var scene = this.getScene();
  61588. if (!scene) {
  61589. return;
  61590. }
  61591. var index = scene.multiMaterials.indexOf(this);
  61592. if (index >= 0) {
  61593. scene.multiMaterials.splice(index, 1);
  61594. }
  61595. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  61596. };
  61597. return MultiMaterial;
  61598. }(BABYLON.Material));
  61599. BABYLON.MultiMaterial = MultiMaterial;
  61600. })(BABYLON || (BABYLON = {}));
  61601. //# sourceMappingURL=babylon.multiMaterial.js.map
  61602. var BABYLON;
  61603. (function (BABYLON) {
  61604. var FreeCameraTouchInput = /** @class */ (function () {
  61605. function FreeCameraTouchInput() {
  61606. this._offsetX = null;
  61607. this._offsetY = null;
  61608. this._pointerPressed = new Array();
  61609. this.touchAngularSensibility = 200000.0;
  61610. this.touchMoveSensibility = 250.0;
  61611. }
  61612. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  61613. var _this = this;
  61614. var previousPosition = null;
  61615. if (this._pointerInput === undefined) {
  61616. this._onLostFocus = function (evt) {
  61617. _this._offsetX = null;
  61618. _this._offsetY = null;
  61619. };
  61620. this._pointerInput = function (p, s) {
  61621. var evt = p.event;
  61622. if (evt.pointerType === "mouse") {
  61623. return;
  61624. }
  61625. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  61626. if (!noPreventDefault) {
  61627. evt.preventDefault();
  61628. }
  61629. _this._pointerPressed.push(evt.pointerId);
  61630. if (_this._pointerPressed.length !== 1) {
  61631. return;
  61632. }
  61633. previousPosition = {
  61634. x: evt.clientX,
  61635. y: evt.clientY
  61636. };
  61637. }
  61638. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  61639. if (!noPreventDefault) {
  61640. evt.preventDefault();
  61641. }
  61642. var index = _this._pointerPressed.indexOf(evt.pointerId);
  61643. if (index === -1) {
  61644. return;
  61645. }
  61646. _this._pointerPressed.splice(index, 1);
  61647. if (index != 0) {
  61648. return;
  61649. }
  61650. previousPosition = null;
  61651. _this._offsetX = null;
  61652. _this._offsetY = null;
  61653. }
  61654. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  61655. if (!noPreventDefault) {
  61656. evt.preventDefault();
  61657. }
  61658. if (!previousPosition) {
  61659. return;
  61660. }
  61661. var index = _this._pointerPressed.indexOf(evt.pointerId);
  61662. if (index != 0) {
  61663. return;
  61664. }
  61665. _this._offsetX = evt.clientX - previousPosition.x;
  61666. _this._offsetY = -(evt.clientY - previousPosition.y);
  61667. }
  61668. };
  61669. }
  61670. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  61671. if (this._onLostFocus) {
  61672. element.addEventListener("blur", this._onLostFocus);
  61673. }
  61674. };
  61675. FreeCameraTouchInput.prototype.detachControl = function (element) {
  61676. if (this._pointerInput && element) {
  61677. if (this._observer) {
  61678. this.camera.getScene().onPointerObservable.remove(this._observer);
  61679. this._observer = null;
  61680. }
  61681. if (this._onLostFocus) {
  61682. element.removeEventListener("blur", this._onLostFocus);
  61683. this._onLostFocus = null;
  61684. }
  61685. this._pointerPressed = [];
  61686. this._offsetX = null;
  61687. this._offsetY = null;
  61688. }
  61689. };
  61690. FreeCameraTouchInput.prototype.checkInputs = function () {
  61691. if (this._offsetX && this._offsetY) {
  61692. var camera = this.camera;
  61693. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  61694. if (this._pointerPressed.length > 1) {
  61695. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  61696. }
  61697. else {
  61698. var speed = camera._computeLocalCameraSpeed();
  61699. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  61700. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  61701. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  61702. }
  61703. }
  61704. };
  61705. FreeCameraTouchInput.prototype.getClassName = function () {
  61706. return "FreeCameraTouchInput";
  61707. };
  61708. FreeCameraTouchInput.prototype.getSimpleName = function () {
  61709. return "touch";
  61710. };
  61711. __decorate([
  61712. BABYLON.serialize()
  61713. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  61714. __decorate([
  61715. BABYLON.serialize()
  61716. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  61717. return FreeCameraTouchInput;
  61718. }());
  61719. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  61720. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  61721. })(BABYLON || (BABYLON = {}));
  61722. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  61723. var BABYLON;
  61724. (function (BABYLON) {
  61725. // We're mainly based on the logic defined into the FreeCamera code
  61726. var TouchCamera = /** @class */ (function (_super) {
  61727. __extends(TouchCamera, _super);
  61728. //-- end properties for backward compatibility for inputs
  61729. function TouchCamera(name, position, scene) {
  61730. var _this = _super.call(this, name, position, scene) || this;
  61731. _this.inputs.addTouch();
  61732. _this._setupInputs();
  61733. return _this;
  61734. }
  61735. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  61736. //-- Begin properties for backward compatibility for inputs
  61737. get: function () {
  61738. var touch = this.inputs.attached["touch"];
  61739. if (touch)
  61740. return touch.touchAngularSensibility;
  61741. return 0;
  61742. },
  61743. set: function (value) {
  61744. var touch = this.inputs.attached["touch"];
  61745. if (touch)
  61746. touch.touchAngularSensibility = value;
  61747. },
  61748. enumerable: true,
  61749. configurable: true
  61750. });
  61751. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  61752. get: function () {
  61753. var touch = this.inputs.attached["touch"];
  61754. if (touch)
  61755. return touch.touchMoveSensibility;
  61756. return 0;
  61757. },
  61758. set: function (value) {
  61759. var touch = this.inputs.attached["touch"];
  61760. if (touch)
  61761. touch.touchMoveSensibility = value;
  61762. },
  61763. enumerable: true,
  61764. configurable: true
  61765. });
  61766. TouchCamera.prototype.getClassName = function () {
  61767. return "TouchCamera";
  61768. };
  61769. TouchCamera.prototype._setupInputs = function () {
  61770. var mouse = this.inputs.attached["mouse"];
  61771. if (mouse) {
  61772. mouse.touchEnabled = false;
  61773. }
  61774. };
  61775. return TouchCamera;
  61776. }(BABYLON.FreeCamera));
  61777. BABYLON.TouchCamera = TouchCamera;
  61778. })(BABYLON || (BABYLON = {}));
  61779. //# sourceMappingURL=babylon.touchCamera.js.map
  61780. var BABYLON;
  61781. (function (BABYLON) {
  61782. var ProceduralTexture = /** @class */ (function (_super) {
  61783. __extends(ProceduralTexture, _super);
  61784. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  61785. if (fallbackTexture === void 0) { fallbackTexture = null; }
  61786. if (generateMipMaps === void 0) { generateMipMaps = true; }
  61787. if (isCube === void 0) { isCube = false; }
  61788. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  61789. _this.isCube = isCube;
  61790. _this.isEnabled = true;
  61791. _this._currentRefreshId = -1;
  61792. _this._refreshRate = 1;
  61793. _this._vertexBuffers = {};
  61794. _this._uniforms = new Array();
  61795. _this._samplers = new Array();
  61796. _this._textures = {};
  61797. _this._floats = {};
  61798. _this._floatsArrays = {};
  61799. _this._colors3 = {};
  61800. _this._colors4 = {};
  61801. _this._vectors2 = {};
  61802. _this._vectors3 = {};
  61803. _this._matrices = {};
  61804. _this._fallbackTextureUsed = false;
  61805. scene._proceduralTextures.push(_this);
  61806. _this._engine = scene.getEngine();
  61807. _this.name = name;
  61808. _this.isRenderTarget = true;
  61809. _this._size = size;
  61810. _this._generateMipMaps = generateMipMaps;
  61811. _this.setFragment(fragment);
  61812. _this._fallbackTexture = fallbackTexture;
  61813. if (isCube) {
  61814. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  61815. _this.setFloat("face", 0);
  61816. }
  61817. else {
  61818. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  61819. }
  61820. // VBO
  61821. var vertices = [];
  61822. vertices.push(1, 1);
  61823. vertices.push(-1, 1);
  61824. vertices.push(-1, -1);
  61825. vertices.push(1, -1);
  61826. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  61827. _this._createIndexBuffer();
  61828. return _this;
  61829. }
  61830. ProceduralTexture.prototype._createIndexBuffer = function () {
  61831. var engine = this._engine;
  61832. // Indices
  61833. var indices = [];
  61834. indices.push(0);
  61835. indices.push(1);
  61836. indices.push(2);
  61837. indices.push(0);
  61838. indices.push(2);
  61839. indices.push(3);
  61840. this._indexBuffer = engine.createIndexBuffer(indices);
  61841. };
  61842. ProceduralTexture.prototype._rebuild = function () {
  61843. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  61844. if (vb) {
  61845. vb._rebuild();
  61846. }
  61847. this._createIndexBuffer();
  61848. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  61849. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  61850. }
  61851. };
  61852. ProceduralTexture.prototype.reset = function () {
  61853. if (this._effect === undefined) {
  61854. return;
  61855. }
  61856. var engine = this._engine;
  61857. engine._releaseEffect(this._effect);
  61858. };
  61859. ProceduralTexture.prototype.isReady = function () {
  61860. var _this = this;
  61861. var engine = this._engine;
  61862. var shaders;
  61863. if (!this._fragment) {
  61864. return false;
  61865. }
  61866. if (this._fallbackTextureUsed) {
  61867. return true;
  61868. }
  61869. if (this._fragment.fragmentElement !== undefined) {
  61870. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  61871. }
  61872. else {
  61873. shaders = { vertex: "procedural", fragment: this._fragment };
  61874. }
  61875. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  61876. _this.releaseInternalTexture();
  61877. if (_this._fallbackTexture) {
  61878. _this._texture = _this._fallbackTexture._texture;
  61879. if (_this._texture) {
  61880. _this._texture.incrementReferences();
  61881. }
  61882. }
  61883. _this._fallbackTextureUsed = true;
  61884. });
  61885. return this._effect.isReady();
  61886. };
  61887. ProceduralTexture.prototype.resetRefreshCounter = function () {
  61888. this._currentRefreshId = -1;
  61889. };
  61890. ProceduralTexture.prototype.setFragment = function (fragment) {
  61891. this._fragment = fragment;
  61892. };
  61893. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  61894. get: function () {
  61895. return this._refreshRate;
  61896. },
  61897. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  61898. set: function (value) {
  61899. this._refreshRate = value;
  61900. this.resetRefreshCounter();
  61901. },
  61902. enumerable: true,
  61903. configurable: true
  61904. });
  61905. ProceduralTexture.prototype._shouldRender = function () {
  61906. if (!this.isEnabled || !this.isReady() || !this._texture) {
  61907. return false;
  61908. }
  61909. if (this._fallbackTextureUsed) {
  61910. return false;
  61911. }
  61912. if (this._currentRefreshId === -1) {
  61913. this._currentRefreshId = 1;
  61914. return true;
  61915. }
  61916. if (this.refreshRate === this._currentRefreshId) {
  61917. this._currentRefreshId = 1;
  61918. return true;
  61919. }
  61920. this._currentRefreshId++;
  61921. return false;
  61922. };
  61923. ProceduralTexture.prototype.getRenderSize = function () {
  61924. return this._size;
  61925. };
  61926. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  61927. if (this._fallbackTextureUsed) {
  61928. return;
  61929. }
  61930. this.releaseInternalTexture();
  61931. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  61932. };
  61933. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  61934. if (this._uniforms.indexOf(uniformName) === -1) {
  61935. this._uniforms.push(uniformName);
  61936. }
  61937. };
  61938. ProceduralTexture.prototype.setTexture = function (name, texture) {
  61939. if (this._samplers.indexOf(name) === -1) {
  61940. this._samplers.push(name);
  61941. }
  61942. this._textures[name] = texture;
  61943. return this;
  61944. };
  61945. ProceduralTexture.prototype.setFloat = function (name, value) {
  61946. this._checkUniform(name);
  61947. this._floats[name] = value;
  61948. return this;
  61949. };
  61950. ProceduralTexture.prototype.setFloats = function (name, value) {
  61951. this._checkUniform(name);
  61952. this._floatsArrays[name] = value;
  61953. return this;
  61954. };
  61955. ProceduralTexture.prototype.setColor3 = function (name, value) {
  61956. this._checkUniform(name);
  61957. this._colors3[name] = value;
  61958. return this;
  61959. };
  61960. ProceduralTexture.prototype.setColor4 = function (name, value) {
  61961. this._checkUniform(name);
  61962. this._colors4[name] = value;
  61963. return this;
  61964. };
  61965. ProceduralTexture.prototype.setVector2 = function (name, value) {
  61966. this._checkUniform(name);
  61967. this._vectors2[name] = value;
  61968. return this;
  61969. };
  61970. ProceduralTexture.prototype.setVector3 = function (name, value) {
  61971. this._checkUniform(name);
  61972. this._vectors3[name] = value;
  61973. return this;
  61974. };
  61975. ProceduralTexture.prototype.setMatrix = function (name, value) {
  61976. this._checkUniform(name);
  61977. this._matrices[name] = value;
  61978. return this;
  61979. };
  61980. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  61981. var scene = this.getScene();
  61982. if (!scene) {
  61983. return;
  61984. }
  61985. var engine = this._engine;
  61986. // Render
  61987. engine.enableEffect(this._effect);
  61988. engine.setState(false);
  61989. // Texture
  61990. for (var name in this._textures) {
  61991. this._effect.setTexture(name, this._textures[name]);
  61992. }
  61993. // Float
  61994. for (name in this._floats) {
  61995. this._effect.setFloat(name, this._floats[name]);
  61996. }
  61997. // Floats
  61998. for (name in this._floatsArrays) {
  61999. this._effect.setArray(name, this._floatsArrays[name]);
  62000. }
  62001. // Color3
  62002. for (name in this._colors3) {
  62003. this._effect.setColor3(name, this._colors3[name]);
  62004. }
  62005. // Color4
  62006. for (name in this._colors4) {
  62007. var color = this._colors4[name];
  62008. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  62009. }
  62010. // Vector2
  62011. for (name in this._vectors2) {
  62012. this._effect.setVector2(name, this._vectors2[name]);
  62013. }
  62014. // Vector3
  62015. for (name in this._vectors3) {
  62016. this._effect.setVector3(name, this._vectors3[name]);
  62017. }
  62018. // Matrix
  62019. for (name in this._matrices) {
  62020. this._effect.setMatrix(name, this._matrices[name]);
  62021. }
  62022. if (!this._texture) {
  62023. return;
  62024. }
  62025. if (this.isCube) {
  62026. for (var face = 0; face < 6; face++) {
  62027. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  62028. // VBOs
  62029. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  62030. this._effect.setFloat("face", face);
  62031. // Clear
  62032. engine.clear(scene.clearColor, true, true, true);
  62033. // Draw order
  62034. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  62035. // Mipmaps
  62036. if (face === 5) {
  62037. engine.generateMipMapsForCubemap(this._texture);
  62038. }
  62039. }
  62040. }
  62041. else {
  62042. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  62043. // VBOs
  62044. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  62045. // Clear
  62046. engine.clear(scene.clearColor, true, true, true);
  62047. // Draw order
  62048. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  62049. }
  62050. // Unbind
  62051. engine.unBindFramebuffer(this._texture, this.isCube);
  62052. if (this.onGenerated) {
  62053. this.onGenerated();
  62054. }
  62055. };
  62056. ProceduralTexture.prototype.clone = function () {
  62057. var textureSize = this.getSize();
  62058. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  62059. // Base texture
  62060. newTexture.hasAlpha = this.hasAlpha;
  62061. newTexture.level = this.level;
  62062. // RenderTarget Texture
  62063. newTexture.coordinatesMode = this.coordinatesMode;
  62064. return newTexture;
  62065. };
  62066. ProceduralTexture.prototype.dispose = function () {
  62067. var scene = this.getScene();
  62068. if (!scene) {
  62069. return;
  62070. }
  62071. var index = scene._proceduralTextures.indexOf(this);
  62072. if (index >= 0) {
  62073. scene._proceduralTextures.splice(index, 1);
  62074. }
  62075. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  62076. if (vertexBuffer) {
  62077. vertexBuffer.dispose();
  62078. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  62079. }
  62080. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  62081. this._indexBuffer = null;
  62082. }
  62083. _super.prototype.dispose.call(this);
  62084. };
  62085. return ProceduralTexture;
  62086. }(BABYLON.Texture));
  62087. BABYLON.ProceduralTexture = ProceduralTexture;
  62088. })(BABYLON || (BABYLON = {}));
  62089. //# sourceMappingURL=babylon.proceduralTexture.js.map
  62090. var BABYLON;
  62091. (function (BABYLON) {
  62092. var CustomProceduralTexture = /** @class */ (function (_super) {
  62093. __extends(CustomProceduralTexture, _super);
  62094. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  62095. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  62096. _this._animate = true;
  62097. _this._time = 0;
  62098. _this._texturePath = texturePath;
  62099. //Try to load json
  62100. _this.loadJson(texturePath);
  62101. _this.refreshRate = 1;
  62102. return _this;
  62103. }
  62104. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  62105. var _this = this;
  62106. var noConfigFile = function () {
  62107. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  62108. try {
  62109. _this.setFragment(_this._texturePath);
  62110. }
  62111. catch (ex) {
  62112. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  62113. }
  62114. };
  62115. var configFileUrl = jsonUrl + "/config.json";
  62116. var xhr = new XMLHttpRequest();
  62117. xhr.open("GET", configFileUrl, true);
  62118. xhr.addEventListener("load", function () {
  62119. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  62120. try {
  62121. _this._config = JSON.parse(xhr.response);
  62122. _this.updateShaderUniforms();
  62123. _this.updateTextures();
  62124. _this.setFragment(_this._texturePath + "/custom");
  62125. _this._animate = _this._config.animate;
  62126. _this.refreshRate = _this._config.refreshrate;
  62127. }
  62128. catch (ex) {
  62129. noConfigFile();
  62130. }
  62131. }
  62132. else {
  62133. noConfigFile();
  62134. }
  62135. }, false);
  62136. xhr.addEventListener("error", function () {
  62137. noConfigFile();
  62138. }, false);
  62139. try {
  62140. xhr.send();
  62141. }
  62142. catch (ex) {
  62143. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  62144. }
  62145. };
  62146. CustomProceduralTexture.prototype.isReady = function () {
  62147. if (!_super.prototype.isReady.call(this)) {
  62148. return false;
  62149. }
  62150. for (var name in this._textures) {
  62151. var texture = this._textures[name];
  62152. if (!texture.isReady()) {
  62153. return false;
  62154. }
  62155. }
  62156. return true;
  62157. };
  62158. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  62159. var scene = this.getScene();
  62160. if (this._animate && scene) {
  62161. this._time += scene.getAnimationRatio() * 0.03;
  62162. this.updateShaderUniforms();
  62163. }
  62164. _super.prototype.render.call(this, useCameraPostProcess);
  62165. };
  62166. CustomProceduralTexture.prototype.updateTextures = function () {
  62167. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  62168. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  62169. }
  62170. };
  62171. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  62172. if (this._config) {
  62173. for (var j = 0; j < this._config.uniforms.length; j++) {
  62174. var uniform = this._config.uniforms[j];
  62175. switch (uniform.type) {
  62176. case "float":
  62177. this.setFloat(uniform.name, uniform.value);
  62178. break;
  62179. case "color3":
  62180. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  62181. break;
  62182. case "color4":
  62183. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  62184. break;
  62185. case "vector2":
  62186. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  62187. break;
  62188. case "vector3":
  62189. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  62190. break;
  62191. }
  62192. }
  62193. }
  62194. this.setFloat("time", this._time);
  62195. };
  62196. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  62197. get: function () {
  62198. return this._animate;
  62199. },
  62200. set: function (value) {
  62201. this._animate = value;
  62202. },
  62203. enumerable: true,
  62204. configurable: true
  62205. });
  62206. return CustomProceduralTexture;
  62207. }(BABYLON.ProceduralTexture));
  62208. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  62209. })(BABYLON || (BABYLON = {}));
  62210. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  62211. var BABYLON;
  62212. (function (BABYLON) {
  62213. var FreeCameraGamepadInput = /** @class */ (function () {
  62214. function FreeCameraGamepadInput() {
  62215. this.gamepadAngularSensibility = 200;
  62216. this.gamepadMoveSensibility = 40;
  62217. // private members
  62218. this._cameraTransform = BABYLON.Matrix.Identity();
  62219. this._deltaTransform = BABYLON.Vector3.Zero();
  62220. this._vector3 = BABYLON.Vector3.Zero();
  62221. this._vector2 = BABYLON.Vector2.Zero();
  62222. }
  62223. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  62224. var _this = this;
  62225. var manager = this.camera.getScene().gamepadManager;
  62226. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  62227. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  62228. // prioritize XBOX gamepads.
  62229. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  62230. _this.gamepad = gamepad;
  62231. }
  62232. }
  62233. });
  62234. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  62235. if (_this.gamepad === gamepad) {
  62236. _this.gamepad = null;
  62237. }
  62238. });
  62239. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  62240. };
  62241. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  62242. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  62243. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  62244. this.gamepad = null;
  62245. };
  62246. FreeCameraGamepadInput.prototype.checkInputs = function () {
  62247. if (this.gamepad && this.gamepad.leftStick) {
  62248. var camera = this.camera;
  62249. var LSValues = this.gamepad.leftStick;
  62250. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  62251. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  62252. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  62253. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  62254. var RSValues = this.gamepad.rightStick;
  62255. if (RSValues) {
  62256. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  62257. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  62258. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  62259. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  62260. }
  62261. else {
  62262. RSValues = { x: 0, y: 0 };
  62263. }
  62264. if (!camera.rotationQuaternion) {
  62265. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  62266. }
  62267. else {
  62268. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  62269. }
  62270. var speed = camera._computeLocalCameraSpeed() * 50.0;
  62271. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  62272. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  62273. camera.cameraDirection.addInPlace(this._deltaTransform);
  62274. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  62275. camera.cameraRotation.addInPlace(this._vector2);
  62276. }
  62277. };
  62278. FreeCameraGamepadInput.prototype.getClassName = function () {
  62279. return "FreeCameraGamepadInput";
  62280. };
  62281. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  62282. return "gamepad";
  62283. };
  62284. __decorate([
  62285. BABYLON.serialize()
  62286. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  62287. __decorate([
  62288. BABYLON.serialize()
  62289. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  62290. return FreeCameraGamepadInput;
  62291. }());
  62292. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  62293. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  62294. })(BABYLON || (BABYLON = {}));
  62295. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  62296. var BABYLON;
  62297. (function (BABYLON) {
  62298. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  62299. function ArcRotateCameraGamepadInput() {
  62300. this.gamepadRotationSensibility = 80;
  62301. this.gamepadMoveSensibility = 40;
  62302. }
  62303. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  62304. var _this = this;
  62305. var manager = this.camera.getScene().gamepadManager;
  62306. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  62307. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  62308. // prioritize XBOX gamepads.
  62309. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  62310. _this.gamepad = gamepad;
  62311. }
  62312. }
  62313. });
  62314. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  62315. if (_this.gamepad === gamepad) {
  62316. _this.gamepad = null;
  62317. }
  62318. });
  62319. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  62320. };
  62321. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  62322. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  62323. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  62324. this.gamepad = null;
  62325. };
  62326. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  62327. if (this.gamepad) {
  62328. var camera = this.camera;
  62329. var RSValues = this.gamepad.rightStick;
  62330. if (RSValues) {
  62331. if (RSValues.x != 0) {
  62332. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  62333. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  62334. camera.inertialAlphaOffset += normalizedRX;
  62335. }
  62336. }
  62337. if (RSValues.y != 0) {
  62338. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  62339. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  62340. camera.inertialBetaOffset += normalizedRY;
  62341. }
  62342. }
  62343. }
  62344. var LSValues = this.gamepad.leftStick;
  62345. if (LSValues && LSValues.y != 0) {
  62346. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  62347. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  62348. this.camera.inertialRadiusOffset -= normalizedLY;
  62349. }
  62350. }
  62351. }
  62352. };
  62353. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  62354. return "ArcRotateCameraGamepadInput";
  62355. };
  62356. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  62357. return "gamepad";
  62358. };
  62359. __decorate([
  62360. BABYLON.serialize()
  62361. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  62362. __decorate([
  62363. BABYLON.serialize()
  62364. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  62365. return ArcRotateCameraGamepadInput;
  62366. }());
  62367. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  62368. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  62369. })(BABYLON || (BABYLON = {}));
  62370. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  62371. var BABYLON;
  62372. (function (BABYLON) {
  62373. var GamepadManager = /** @class */ (function () {
  62374. function GamepadManager(_scene) {
  62375. var _this = this;
  62376. this._scene = _scene;
  62377. this._babylonGamepads = [];
  62378. this._oneGamepadConnected = false;
  62379. this._isMonitoring = false;
  62380. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  62381. if (!BABYLON.Tools.IsWindowObjectExist()) {
  62382. this._gamepadEventSupported = false;
  62383. }
  62384. else {
  62385. this._gamepadEventSupported = 'GamepadEvent' in window;
  62386. this._gamepadSupport = (navigator.getGamepads ||
  62387. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  62388. }
  62389. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  62390. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  62391. for (var i in _this._babylonGamepads) {
  62392. var gamepad = _this._babylonGamepads[i];
  62393. if (gamepad && gamepad._isConnected) {
  62394. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  62395. }
  62396. }
  62397. });
  62398. this._onGamepadConnectedEvent = function (evt) {
  62399. var gamepad = evt.gamepad;
  62400. if (gamepad.index in _this._babylonGamepads) {
  62401. if (_this._babylonGamepads[gamepad.index].isConnected) {
  62402. return;
  62403. }
  62404. }
  62405. var newGamepad;
  62406. if (_this._babylonGamepads[gamepad.index]) {
  62407. newGamepad = _this._babylonGamepads[gamepad.index];
  62408. newGamepad.browserGamepad = gamepad;
  62409. newGamepad._isConnected = true;
  62410. }
  62411. else {
  62412. newGamepad = _this._addNewGamepad(gamepad);
  62413. }
  62414. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  62415. _this._startMonitoringGamepads();
  62416. };
  62417. this._onGamepadDisconnectedEvent = function (evt) {
  62418. var gamepad = evt.gamepad;
  62419. // Remove the gamepad from the list of gamepads to monitor.
  62420. for (var i in _this._babylonGamepads) {
  62421. if (_this._babylonGamepads[i].index === gamepad.index) {
  62422. var disconnectedGamepad = _this._babylonGamepads[i];
  62423. disconnectedGamepad._isConnected = false;
  62424. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  62425. break;
  62426. }
  62427. }
  62428. };
  62429. if (this._gamepadSupport) {
  62430. //first add already-connected gamepads
  62431. this._updateGamepadObjects();
  62432. if (this._babylonGamepads.length) {
  62433. this._startMonitoringGamepads();
  62434. }
  62435. // Checking if the gamepad connected event is supported (like in Firefox)
  62436. if (this._gamepadEventSupported) {
  62437. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  62438. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  62439. }
  62440. else {
  62441. this._startMonitoringGamepads();
  62442. }
  62443. }
  62444. }
  62445. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  62446. get: function () {
  62447. return this._babylonGamepads;
  62448. },
  62449. enumerable: true,
  62450. configurable: true
  62451. });
  62452. GamepadManager.prototype.getGamepadByType = function (type) {
  62453. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  62454. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  62455. var gamepad = _a[_i];
  62456. if (gamepad && gamepad.type === type) {
  62457. return gamepad;
  62458. }
  62459. }
  62460. return null;
  62461. };
  62462. GamepadManager.prototype.dispose = function () {
  62463. if (this._gamepadEventSupported) {
  62464. if (this._onGamepadConnectedEvent) {
  62465. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  62466. }
  62467. if (this._onGamepadDisconnectedEvent) {
  62468. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  62469. }
  62470. this._onGamepadConnectedEvent = null;
  62471. this._onGamepadDisconnectedEvent = null;
  62472. }
  62473. this._babylonGamepads.forEach(function (gamepad) {
  62474. gamepad.dispose();
  62475. });
  62476. this.onGamepadConnectedObservable.clear();
  62477. this.onGamepadDisconnectedObservable.clear();
  62478. this._oneGamepadConnected = false;
  62479. this._stopMonitoringGamepads();
  62480. this._babylonGamepads = [];
  62481. };
  62482. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  62483. if (!this._oneGamepadConnected) {
  62484. this._oneGamepadConnected = true;
  62485. }
  62486. var newGamepad;
  62487. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  62488. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  62489. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  62490. }
  62491. else if (gamepad.pose) {
  62492. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  62493. }
  62494. else {
  62495. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  62496. }
  62497. this._babylonGamepads[newGamepad.index] = newGamepad;
  62498. return newGamepad;
  62499. };
  62500. GamepadManager.prototype._startMonitoringGamepads = function () {
  62501. if (!this._isMonitoring) {
  62502. this._isMonitoring = true;
  62503. //back-comp
  62504. if (!this._scene) {
  62505. this._checkGamepadsStatus();
  62506. }
  62507. }
  62508. };
  62509. GamepadManager.prototype._stopMonitoringGamepads = function () {
  62510. this._isMonitoring = false;
  62511. };
  62512. GamepadManager.prototype._checkGamepadsStatus = function () {
  62513. var _this = this;
  62514. // Hack to be compatible Chrome
  62515. this._updateGamepadObjects();
  62516. for (var i in this._babylonGamepads) {
  62517. var gamepad = this._babylonGamepads[i];
  62518. if (!gamepad || !gamepad.isConnected) {
  62519. continue;
  62520. }
  62521. gamepad.update();
  62522. }
  62523. if (this._isMonitoring && !this._scene) {
  62524. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  62525. }
  62526. };
  62527. // This function is called only on Chrome, which does not properly support
  62528. // connection/disconnection events and forces you to recopy again the gamepad object
  62529. GamepadManager.prototype._updateGamepadObjects = function () {
  62530. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  62531. for (var i = 0; i < gamepads.length; i++) {
  62532. if (gamepads[i]) {
  62533. if (!this._babylonGamepads[gamepads[i].index]) {
  62534. var newGamepad = this._addNewGamepad(gamepads[i]);
  62535. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  62536. }
  62537. else {
  62538. // Forced to copy again this object for Chrome for unknown reason
  62539. this._babylonGamepads[i].browserGamepad = gamepads[i];
  62540. if (!this._babylonGamepads[i].isConnected) {
  62541. this._babylonGamepads[i]._isConnected = true;
  62542. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  62543. }
  62544. }
  62545. }
  62546. }
  62547. };
  62548. return GamepadManager;
  62549. }());
  62550. BABYLON.GamepadManager = GamepadManager;
  62551. })(BABYLON || (BABYLON = {}));
  62552. //# sourceMappingURL=babylon.gamepadManager.js.map
  62553. var BABYLON;
  62554. (function (BABYLON) {
  62555. var StickValues = /** @class */ (function () {
  62556. function StickValues(x, y) {
  62557. this.x = x;
  62558. this.y = y;
  62559. }
  62560. return StickValues;
  62561. }());
  62562. BABYLON.StickValues = StickValues;
  62563. var Gamepad = /** @class */ (function () {
  62564. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  62565. if (leftStickX === void 0) { leftStickX = 0; }
  62566. if (leftStickY === void 0) { leftStickY = 1; }
  62567. if (rightStickX === void 0) { rightStickX = 2; }
  62568. if (rightStickY === void 0) { rightStickY = 3; }
  62569. this.id = id;
  62570. this.index = index;
  62571. this.browserGamepad = browserGamepad;
  62572. this._isConnected = true;
  62573. this._invertLeftStickY = false;
  62574. this.type = Gamepad.GAMEPAD;
  62575. this._leftStickAxisX = leftStickX;
  62576. this._leftStickAxisY = leftStickY;
  62577. this._rightStickAxisX = rightStickX;
  62578. this._rightStickAxisY = rightStickY;
  62579. if (this.browserGamepad.axes.length >= 2) {
  62580. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  62581. }
  62582. if (this.browserGamepad.axes.length >= 4) {
  62583. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  62584. }
  62585. }
  62586. Object.defineProperty(Gamepad.prototype, "isConnected", {
  62587. get: function () {
  62588. return this._isConnected;
  62589. },
  62590. enumerable: true,
  62591. configurable: true
  62592. });
  62593. Gamepad.prototype.onleftstickchanged = function (callback) {
  62594. this._onleftstickchanged = callback;
  62595. };
  62596. Gamepad.prototype.onrightstickchanged = function (callback) {
  62597. this._onrightstickchanged = callback;
  62598. };
  62599. Object.defineProperty(Gamepad.prototype, "leftStick", {
  62600. get: function () {
  62601. return this._leftStick;
  62602. },
  62603. set: function (newValues) {
  62604. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  62605. this._onleftstickchanged(newValues);
  62606. }
  62607. this._leftStick = newValues;
  62608. },
  62609. enumerable: true,
  62610. configurable: true
  62611. });
  62612. Object.defineProperty(Gamepad.prototype, "rightStick", {
  62613. get: function () {
  62614. return this._rightStick;
  62615. },
  62616. set: function (newValues) {
  62617. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  62618. this._onrightstickchanged(newValues);
  62619. }
  62620. this._rightStick = newValues;
  62621. },
  62622. enumerable: true,
  62623. configurable: true
  62624. });
  62625. Gamepad.prototype.update = function () {
  62626. if (this._leftStick) {
  62627. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  62628. if (this._invertLeftStickY) {
  62629. this.leftStick.y *= -1;
  62630. }
  62631. }
  62632. if (this._rightStick) {
  62633. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  62634. }
  62635. };
  62636. Gamepad.prototype.dispose = function () {
  62637. };
  62638. Gamepad.GAMEPAD = 0;
  62639. Gamepad.GENERIC = 1;
  62640. Gamepad.XBOX = 2;
  62641. Gamepad.POSE_ENABLED = 3;
  62642. return Gamepad;
  62643. }());
  62644. BABYLON.Gamepad = Gamepad;
  62645. var GenericPad = /** @class */ (function (_super) {
  62646. __extends(GenericPad, _super);
  62647. function GenericPad(id, index, browserGamepad) {
  62648. var _this = _super.call(this, id, index, browserGamepad) || this;
  62649. _this.onButtonDownObservable = new BABYLON.Observable();
  62650. _this.onButtonUpObservable = new BABYLON.Observable();
  62651. _this.type = Gamepad.GENERIC;
  62652. _this._buttons = new Array(browserGamepad.buttons.length);
  62653. return _this;
  62654. }
  62655. GenericPad.prototype.onbuttondown = function (callback) {
  62656. this._onbuttondown = callback;
  62657. };
  62658. GenericPad.prototype.onbuttonup = function (callback) {
  62659. this._onbuttonup = callback;
  62660. };
  62661. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  62662. if (newValue !== currentValue) {
  62663. if (newValue === 1) {
  62664. if (this._onbuttondown) {
  62665. this._onbuttondown(buttonIndex);
  62666. }
  62667. this.onButtonDownObservable.notifyObservers(buttonIndex);
  62668. }
  62669. if (newValue === 0) {
  62670. if (this._onbuttonup) {
  62671. this._onbuttonup(buttonIndex);
  62672. }
  62673. this.onButtonUpObservable.notifyObservers(buttonIndex);
  62674. }
  62675. }
  62676. return newValue;
  62677. };
  62678. GenericPad.prototype.update = function () {
  62679. _super.prototype.update.call(this);
  62680. for (var index = 0; index < this._buttons.length; index++) {
  62681. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  62682. }
  62683. };
  62684. GenericPad.prototype.dispose = function () {
  62685. _super.prototype.dispose.call(this);
  62686. this.onButtonDownObservable.clear();
  62687. this.onButtonUpObservable.clear();
  62688. };
  62689. return GenericPad;
  62690. }(Gamepad));
  62691. BABYLON.GenericPad = GenericPad;
  62692. })(BABYLON || (BABYLON = {}));
  62693. //# sourceMappingURL=babylon.gamepad.js.map
  62694. var BABYLON;
  62695. (function (BABYLON) {
  62696. var Xbox360Button;
  62697. (function (Xbox360Button) {
  62698. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  62699. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  62700. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  62701. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  62702. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  62703. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  62704. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  62705. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  62706. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  62707. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  62708. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  62709. var Xbox360Dpad;
  62710. (function (Xbox360Dpad) {
  62711. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  62712. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  62713. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  62714. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  62715. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  62716. var Xbox360Pad = /** @class */ (function (_super) {
  62717. __extends(Xbox360Pad, _super);
  62718. function Xbox360Pad(id, index, gamepad, xboxOne) {
  62719. if (xboxOne === void 0) { xboxOne = false; }
  62720. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  62721. _this._leftTrigger = 0;
  62722. _this._rightTrigger = 0;
  62723. _this.onButtonDownObservable = new BABYLON.Observable();
  62724. _this.onButtonUpObservable = new BABYLON.Observable();
  62725. _this.onPadDownObservable = new BABYLON.Observable();
  62726. _this.onPadUpObservable = new BABYLON.Observable();
  62727. _this._buttonA = 0;
  62728. _this._buttonB = 0;
  62729. _this._buttonX = 0;
  62730. _this._buttonY = 0;
  62731. _this._buttonBack = 0;
  62732. _this._buttonStart = 0;
  62733. _this._buttonLB = 0;
  62734. _this._buttonRB = 0;
  62735. _this._buttonLeftStick = 0;
  62736. _this._buttonRightStick = 0;
  62737. _this._dPadUp = 0;
  62738. _this._dPadDown = 0;
  62739. _this._dPadLeft = 0;
  62740. _this._dPadRight = 0;
  62741. _this._isXboxOnePad = false;
  62742. _this.type = BABYLON.Gamepad.XBOX;
  62743. _this._isXboxOnePad = xboxOne;
  62744. return _this;
  62745. }
  62746. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  62747. this._onlefttriggerchanged = callback;
  62748. };
  62749. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  62750. this._onrighttriggerchanged = callback;
  62751. };
  62752. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  62753. get: function () {
  62754. return this._leftTrigger;
  62755. },
  62756. set: function (newValue) {
  62757. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  62758. this._onlefttriggerchanged(newValue);
  62759. }
  62760. this._leftTrigger = newValue;
  62761. },
  62762. enumerable: true,
  62763. configurable: true
  62764. });
  62765. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  62766. get: function () {
  62767. return this._rightTrigger;
  62768. },
  62769. set: function (newValue) {
  62770. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  62771. this._onrighttriggerchanged(newValue);
  62772. }
  62773. this._rightTrigger = newValue;
  62774. },
  62775. enumerable: true,
  62776. configurable: true
  62777. });
  62778. Xbox360Pad.prototype.onbuttondown = function (callback) {
  62779. this._onbuttondown = callback;
  62780. };
  62781. Xbox360Pad.prototype.onbuttonup = function (callback) {
  62782. this._onbuttonup = callback;
  62783. };
  62784. Xbox360Pad.prototype.ondpaddown = function (callback) {
  62785. this._ondpaddown = callback;
  62786. };
  62787. Xbox360Pad.prototype.ondpadup = function (callback) {
  62788. this._ondpadup = callback;
  62789. };
  62790. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  62791. if (newValue !== currentValue) {
  62792. if (newValue === 1) {
  62793. if (this._onbuttondown) {
  62794. this._onbuttondown(buttonType);
  62795. }
  62796. this.onButtonDownObservable.notifyObservers(buttonType);
  62797. }
  62798. if (newValue === 0) {
  62799. if (this._onbuttonup) {
  62800. this._onbuttonup(buttonType);
  62801. }
  62802. this.onButtonUpObservable.notifyObservers(buttonType);
  62803. }
  62804. }
  62805. return newValue;
  62806. };
  62807. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  62808. if (newValue !== currentValue) {
  62809. if (newValue === 1) {
  62810. if (this._ondpaddown) {
  62811. this._ondpaddown(buttonType);
  62812. }
  62813. this.onPadDownObservable.notifyObservers(buttonType);
  62814. }
  62815. if (newValue === 0) {
  62816. if (this._ondpadup) {
  62817. this._ondpadup(buttonType);
  62818. }
  62819. this.onPadUpObservable.notifyObservers(buttonType);
  62820. }
  62821. }
  62822. return newValue;
  62823. };
  62824. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  62825. get: function () {
  62826. return this._buttonA;
  62827. },
  62828. set: function (value) {
  62829. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  62830. },
  62831. enumerable: true,
  62832. configurable: true
  62833. });
  62834. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  62835. get: function () {
  62836. return this._buttonB;
  62837. },
  62838. set: function (value) {
  62839. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  62840. },
  62841. enumerable: true,
  62842. configurable: true
  62843. });
  62844. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  62845. get: function () {
  62846. return this._buttonX;
  62847. },
  62848. set: function (value) {
  62849. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  62850. },
  62851. enumerable: true,
  62852. configurable: true
  62853. });
  62854. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  62855. get: function () {
  62856. return this._buttonY;
  62857. },
  62858. set: function (value) {
  62859. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  62860. },
  62861. enumerable: true,
  62862. configurable: true
  62863. });
  62864. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  62865. get: function () {
  62866. return this._buttonStart;
  62867. },
  62868. set: function (value) {
  62869. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  62870. },
  62871. enumerable: true,
  62872. configurable: true
  62873. });
  62874. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  62875. get: function () {
  62876. return this._buttonBack;
  62877. },
  62878. set: function (value) {
  62879. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  62880. },
  62881. enumerable: true,
  62882. configurable: true
  62883. });
  62884. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  62885. get: function () {
  62886. return this._buttonLB;
  62887. },
  62888. set: function (value) {
  62889. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  62890. },
  62891. enumerable: true,
  62892. configurable: true
  62893. });
  62894. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  62895. get: function () {
  62896. return this._buttonRB;
  62897. },
  62898. set: function (value) {
  62899. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  62900. },
  62901. enumerable: true,
  62902. configurable: true
  62903. });
  62904. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  62905. get: function () {
  62906. return this._buttonLeftStick;
  62907. },
  62908. set: function (value) {
  62909. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  62910. },
  62911. enumerable: true,
  62912. configurable: true
  62913. });
  62914. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  62915. get: function () {
  62916. return this._buttonRightStick;
  62917. },
  62918. set: function (value) {
  62919. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  62920. },
  62921. enumerable: true,
  62922. configurable: true
  62923. });
  62924. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  62925. get: function () {
  62926. return this._dPadUp;
  62927. },
  62928. set: function (value) {
  62929. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  62930. },
  62931. enumerable: true,
  62932. configurable: true
  62933. });
  62934. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  62935. get: function () {
  62936. return this._dPadDown;
  62937. },
  62938. set: function (value) {
  62939. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  62940. },
  62941. enumerable: true,
  62942. configurable: true
  62943. });
  62944. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  62945. get: function () {
  62946. return this._dPadLeft;
  62947. },
  62948. set: function (value) {
  62949. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  62950. },
  62951. enumerable: true,
  62952. configurable: true
  62953. });
  62954. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  62955. get: function () {
  62956. return this._dPadRight;
  62957. },
  62958. set: function (value) {
  62959. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  62960. },
  62961. enumerable: true,
  62962. configurable: true
  62963. });
  62964. Xbox360Pad.prototype.update = function () {
  62965. _super.prototype.update.call(this);
  62966. if (this._isXboxOnePad) {
  62967. this.buttonA = this.browserGamepad.buttons[0].value;
  62968. this.buttonB = this.browserGamepad.buttons[1].value;
  62969. this.buttonX = this.browserGamepad.buttons[2].value;
  62970. this.buttonY = this.browserGamepad.buttons[3].value;
  62971. this.buttonLB = this.browserGamepad.buttons[4].value;
  62972. this.buttonRB = this.browserGamepad.buttons[5].value;
  62973. this.leftTrigger = this.browserGamepad.axes[2];
  62974. this.rightTrigger = this.browserGamepad.axes[5];
  62975. this.buttonBack = this.browserGamepad.buttons[9].value;
  62976. this.buttonStart = this.browserGamepad.buttons[8].value;
  62977. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  62978. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  62979. this.dPadUp = this.browserGamepad.buttons[11].value;
  62980. this.dPadDown = this.browserGamepad.buttons[12].value;
  62981. this.dPadLeft = this.browserGamepad.buttons[13].value;
  62982. this.dPadRight = this.browserGamepad.buttons[14].value;
  62983. }
  62984. else {
  62985. this.buttonA = this.browserGamepad.buttons[0].value;
  62986. this.buttonB = this.browserGamepad.buttons[1].value;
  62987. this.buttonX = this.browserGamepad.buttons[2].value;
  62988. this.buttonY = this.browserGamepad.buttons[3].value;
  62989. this.buttonLB = this.browserGamepad.buttons[4].value;
  62990. this.buttonRB = this.browserGamepad.buttons[5].value;
  62991. this.leftTrigger = this.browserGamepad.buttons[6].value;
  62992. this.rightTrigger = this.browserGamepad.buttons[7].value;
  62993. this.buttonBack = this.browserGamepad.buttons[8].value;
  62994. this.buttonStart = this.browserGamepad.buttons[9].value;
  62995. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  62996. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  62997. this.dPadUp = this.browserGamepad.buttons[12].value;
  62998. this.dPadDown = this.browserGamepad.buttons[13].value;
  62999. this.dPadLeft = this.browserGamepad.buttons[14].value;
  63000. this.dPadRight = this.browserGamepad.buttons[15].value;
  63001. }
  63002. };
  63003. Xbox360Pad.prototype.dispose = function () {
  63004. _super.prototype.dispose.call(this);
  63005. this.onButtonDownObservable.clear();
  63006. this.onButtonUpObservable.clear();
  63007. this.onPadDownObservable.clear();
  63008. this.onPadUpObservable.clear();
  63009. };
  63010. return Xbox360Pad;
  63011. }(BABYLON.Gamepad));
  63012. BABYLON.Xbox360Pad = Xbox360Pad;
  63013. })(BABYLON || (BABYLON = {}));
  63014. //# sourceMappingURL=babylon.xboxGamepad.js.map
  63015. var BABYLON;
  63016. (function (BABYLON) {
  63017. var PoseEnabledControllerType;
  63018. (function (PoseEnabledControllerType) {
  63019. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  63020. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  63021. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  63022. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  63023. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 4] = "GENERIC";
  63024. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  63025. var PoseEnabledControllerHelper = /** @class */ (function () {
  63026. function PoseEnabledControllerHelper() {
  63027. }
  63028. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  63029. // Oculus Touch
  63030. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  63031. return new BABYLON.OculusTouchController(vrGamepad);
  63032. }
  63033. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  63034. return new BABYLON.WindowsMotionController(vrGamepad);
  63035. }
  63036. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  63037. return new BABYLON.ViveController(vrGamepad);
  63038. }
  63039. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0) {
  63040. return new BABYLON.GearVRController(vrGamepad);
  63041. }
  63042. else {
  63043. return new BABYLON.GenericController(vrGamepad);
  63044. }
  63045. };
  63046. return PoseEnabledControllerHelper;
  63047. }());
  63048. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  63049. var PoseEnabledController = /** @class */ (function (_super) {
  63050. __extends(PoseEnabledController, _super);
  63051. function PoseEnabledController(browserGamepad) {
  63052. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  63053. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  63054. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  63055. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  63056. // Represents device position and rotation in babylon space
  63057. _this.devicePosition = BABYLON.Vector3.Zero();
  63058. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  63059. _this.deviceScaleFactor = 1;
  63060. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  63061. _this._deviceToWorld = BABYLON.Matrix.Identity();
  63062. _this._workingMatrix = BABYLON.Matrix.Identity();
  63063. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  63064. _this.controllerType = PoseEnabledControllerType.GENERIC;
  63065. _this.position = BABYLON.Vector3.Zero();
  63066. _this.rotationQuaternion = new BABYLON.Quaternion();
  63067. _this._calculatedPosition = BABYLON.Vector3.Zero();
  63068. _this._calculatedRotation = new BABYLON.Quaternion();
  63069. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  63070. return _this;
  63071. }
  63072. PoseEnabledController.prototype.update = function () {
  63073. _super.prototype.update.call(this);
  63074. var pose = this.browserGamepad.pose;
  63075. this.updateFromDevice(pose);
  63076. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  63077. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  63078. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  63079. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  63080. if (this._mesh) {
  63081. this._mesh.position.copyFrom(this.devicePosition);
  63082. if (this._mesh.rotationQuaternion) {
  63083. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  63084. }
  63085. }
  63086. };
  63087. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  63088. if (poseData) {
  63089. this.rawPose = poseData;
  63090. if (poseData.position) {
  63091. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  63092. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  63093. this._deviceRoomPosition.z *= -1;
  63094. }
  63095. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  63096. this._calculatedPosition.addInPlace(this.position);
  63097. }
  63098. var pose = this.rawPose;
  63099. if (poseData.orientation && pose.orientation) {
  63100. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  63101. if (this._mesh) {
  63102. if (this._mesh.getScene().useRightHandedSystem) {
  63103. this._deviceRoomRotationQuaternion.z *= -1;
  63104. this._deviceRoomRotationQuaternion.w *= -1;
  63105. }
  63106. else {
  63107. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  63108. }
  63109. }
  63110. // if the camera is set, rotate to the camera's rotation
  63111. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  63112. }
  63113. }
  63114. };
  63115. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  63116. if (this._mesh) {
  63117. this._mesh.parent = null;
  63118. }
  63119. this._mesh = mesh;
  63120. if (this._poseControlledCamera) {
  63121. this._mesh.parent = this._poseControlledCamera;
  63122. }
  63123. if (!this._mesh.rotationQuaternion) {
  63124. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  63125. }
  63126. };
  63127. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  63128. this._poseControlledCamera = camera;
  63129. if (this._mesh) {
  63130. this._mesh.parent = this._poseControlledCamera;
  63131. }
  63132. };
  63133. PoseEnabledController.prototype.dispose = function () {
  63134. if (this._mesh) {
  63135. this._mesh.dispose();
  63136. }
  63137. this._mesh = null;
  63138. _super.prototype.dispose.call(this);
  63139. };
  63140. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  63141. get: function () {
  63142. return this._mesh;
  63143. },
  63144. enumerable: true,
  63145. configurable: true
  63146. });
  63147. PoseEnabledController.prototype.getForwardRay = function (length) {
  63148. if (length === void 0) { length = 100; }
  63149. if (!this.mesh) {
  63150. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  63151. }
  63152. var m = this.mesh.getWorldMatrix();
  63153. var origin = m.getTranslation();
  63154. var forward = new BABYLON.Vector3(0, 0, -1);
  63155. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  63156. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  63157. return new BABYLON.Ray(origin, direction, length);
  63158. };
  63159. return PoseEnabledController;
  63160. }(BABYLON.Gamepad));
  63161. BABYLON.PoseEnabledController = PoseEnabledController;
  63162. })(BABYLON || (BABYLON = {}));
  63163. //# sourceMappingURL=babylon.poseEnabledController.js.map
  63164. var BABYLON;
  63165. (function (BABYLON) {
  63166. var WebVRController = /** @class */ (function (_super) {
  63167. __extends(WebVRController, _super);
  63168. function WebVRController(vrGamepad) {
  63169. var _this = _super.call(this, vrGamepad) || this;
  63170. // Observables
  63171. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  63172. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  63173. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  63174. _this.onPadStateChangedObservable = new BABYLON.Observable();
  63175. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  63176. _this.pad = { x: 0, y: 0 };
  63177. // avoid GC, store state in a tmp object
  63178. _this._changes = {
  63179. pressChanged: false,
  63180. touchChanged: false,
  63181. valueChanged: false,
  63182. changed: false
  63183. };
  63184. _this._buttons = new Array(vrGamepad.buttons.length);
  63185. _this.hand = vrGamepad.hand;
  63186. return _this;
  63187. }
  63188. WebVRController.prototype.onButtonStateChange = function (callback) {
  63189. this._onButtonStateChange = callback;
  63190. };
  63191. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  63192. get: function () {
  63193. return this._defaultModel;
  63194. },
  63195. enumerable: true,
  63196. configurable: true
  63197. });
  63198. WebVRController.prototype.update = function () {
  63199. _super.prototype.update.call(this);
  63200. for (var index = 0; index < this._buttons.length; index++) {
  63201. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  63202. }
  63203. ;
  63204. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  63205. this.pad.x = this.leftStick.x;
  63206. this.pad.y = this.leftStick.y;
  63207. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  63208. }
  63209. };
  63210. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  63211. if (!newState) {
  63212. newState = {
  63213. pressed: false,
  63214. touched: false,
  63215. value: 0
  63216. };
  63217. }
  63218. if (!currentState) {
  63219. this._buttons[buttonIndex] = {
  63220. pressed: newState.pressed,
  63221. touched: newState.touched,
  63222. value: newState.value
  63223. };
  63224. return;
  63225. }
  63226. this._checkChanges(newState, currentState);
  63227. if (this._changes.changed) {
  63228. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  63229. this.handleButtonChange(buttonIndex, newState, this._changes);
  63230. }
  63231. this._buttons[buttonIndex].pressed = newState.pressed;
  63232. this._buttons[buttonIndex].touched = newState.touched;
  63233. // oculus triggers are never 0, thou not touched.
  63234. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  63235. };
  63236. WebVRController.prototype._checkChanges = function (newState, currentState) {
  63237. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  63238. this._changes.touchChanged = newState.touched !== currentState.touched;
  63239. this._changes.valueChanged = newState.value !== currentState.value;
  63240. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  63241. return this._changes;
  63242. };
  63243. WebVRController.prototype.dispose = function () {
  63244. _super.prototype.dispose.call(this);
  63245. this.onTriggerStateChangedObservable.clear();
  63246. this.onMainButtonStateChangedObservable.clear();
  63247. this.onSecondaryButtonStateChangedObservable.clear();
  63248. this.onPadStateChangedObservable.clear();
  63249. this.onPadValuesChangedObservable.clear();
  63250. };
  63251. return WebVRController;
  63252. }(BABYLON.PoseEnabledController));
  63253. BABYLON.WebVRController = WebVRController;
  63254. })(BABYLON || (BABYLON = {}));
  63255. //# sourceMappingURL=babylon.webVRController.js.map
  63256. var BABYLON;
  63257. (function (BABYLON) {
  63258. var OculusTouchController = /** @class */ (function (_super) {
  63259. __extends(OculusTouchController, _super);
  63260. function OculusTouchController(vrGamepad) {
  63261. var _this = _super.call(this, vrGamepad) || this;
  63262. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  63263. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  63264. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  63265. return _this;
  63266. }
  63267. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  63268. var _this = this;
  63269. var meshName;
  63270. // Hand
  63271. if (this.hand === 'left') {
  63272. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  63273. }
  63274. else {
  63275. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  63276. }
  63277. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  63278. /*
  63279. Parent Mesh name: oculus_touch_left
  63280. - body
  63281. - trigger
  63282. - thumbstick
  63283. - grip
  63284. - button_y
  63285. - button_x
  63286. - button_enter
  63287. */
  63288. _this._defaultModel = newMeshes[1];
  63289. _this.attachToMesh(_this._defaultModel);
  63290. if (meshLoaded) {
  63291. meshLoaded(_this._defaultModel);
  63292. }
  63293. });
  63294. };
  63295. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  63296. // helper getters for left and right hand.
  63297. get: function () {
  63298. if (this.hand === 'right') {
  63299. return this.onMainButtonStateChangedObservable;
  63300. }
  63301. else {
  63302. throw new Error('No A button on left hand');
  63303. }
  63304. },
  63305. enumerable: true,
  63306. configurable: true
  63307. });
  63308. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  63309. get: function () {
  63310. if (this.hand === 'right') {
  63311. return this.onSecondaryButtonStateChangedObservable;
  63312. }
  63313. else {
  63314. throw new Error('No B button on left hand');
  63315. }
  63316. },
  63317. enumerable: true,
  63318. configurable: true
  63319. });
  63320. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  63321. get: function () {
  63322. if (this.hand === 'left') {
  63323. return this.onMainButtonStateChangedObservable;
  63324. }
  63325. else {
  63326. throw new Error('No X button on right hand');
  63327. }
  63328. },
  63329. enumerable: true,
  63330. configurable: true
  63331. });
  63332. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  63333. get: function () {
  63334. if (this.hand === 'left') {
  63335. return this.onSecondaryButtonStateChangedObservable;
  63336. }
  63337. else {
  63338. throw new Error('No Y button on right hand');
  63339. }
  63340. },
  63341. enumerable: true,
  63342. configurable: true
  63343. });
  63344. /*
  63345. 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  63346. 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  63347. 2) secondary trigger (same)
  63348. 3) A (right) X (left), touch, pressed = value
  63349. 4) B / Y
  63350. 5) thumb rest
  63351. */
  63352. OculusTouchController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  63353. var notifyObject = state; //{ state: state, changes: changes };
  63354. var triggerDirection = this.hand === 'right' ? -1 : 1;
  63355. switch (buttonIdx) {
  63356. case 0:
  63357. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  63358. return;
  63359. case 1:// index trigger
  63360. if (this._defaultModel) {
  63361. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  63362. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  63363. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  63364. }
  63365. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  63366. return;
  63367. case 2:// secondary trigger
  63368. if (this._defaultModel) {
  63369. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  63370. }
  63371. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  63372. return;
  63373. case 3:
  63374. if (this._defaultModel) {
  63375. if (notifyObject.pressed) {
  63376. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  63377. }
  63378. else {
  63379. (this._defaultModel.getChildren()[1]).position.y = 0;
  63380. }
  63381. }
  63382. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  63383. return;
  63384. case 4:
  63385. if (this._defaultModel) {
  63386. if (notifyObject.pressed) {
  63387. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  63388. }
  63389. else {
  63390. (this._defaultModel.getChildren()[2]).position.y = 0;
  63391. }
  63392. }
  63393. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  63394. return;
  63395. case 5:
  63396. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  63397. return;
  63398. }
  63399. };
  63400. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  63401. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  63402. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  63403. return OculusTouchController;
  63404. }(BABYLON.WebVRController));
  63405. BABYLON.OculusTouchController = OculusTouchController;
  63406. })(BABYLON || (BABYLON = {}));
  63407. //# sourceMappingURL=babylon.oculusTouchController.js.map
  63408. var BABYLON;
  63409. (function (BABYLON) {
  63410. var ViveController = /** @class */ (function (_super) {
  63411. __extends(ViveController, _super);
  63412. function ViveController(vrGamepad) {
  63413. var _this = _super.call(this, vrGamepad) || this;
  63414. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  63415. _this._invertLeftStickY = true;
  63416. return _this;
  63417. }
  63418. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  63419. var _this = this;
  63420. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  63421. /*
  63422. Parent Mesh name: ViveWand
  63423. - body
  63424. - r_gripper
  63425. - l_gripper
  63426. - menu_button
  63427. - system_button
  63428. - trackpad
  63429. - trigger
  63430. - LED
  63431. */
  63432. _this._defaultModel = newMeshes[1];
  63433. _this.attachToMesh(_this._defaultModel);
  63434. if (meshLoaded) {
  63435. meshLoaded(_this._defaultModel);
  63436. }
  63437. });
  63438. };
  63439. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  63440. get: function () {
  63441. return this.onMainButtonStateChangedObservable;
  63442. },
  63443. enumerable: true,
  63444. configurable: true
  63445. });
  63446. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  63447. get: function () {
  63448. return this.onMainButtonStateChangedObservable;
  63449. },
  63450. enumerable: true,
  63451. configurable: true
  63452. });
  63453. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  63454. get: function () {
  63455. return this.onSecondaryButtonStateChangedObservable;
  63456. },
  63457. enumerable: true,
  63458. configurable: true
  63459. });
  63460. /**
  63461. * Vive mapping:
  63462. * 0: touchpad
  63463. * 1: trigger
  63464. * 2: left AND right buttons
  63465. * 3: menu button
  63466. */
  63467. ViveController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  63468. var notifyObject = state; //{ state: state, changes: changes };
  63469. switch (buttonIdx) {
  63470. case 0:
  63471. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  63472. return;
  63473. case 1:// index trigger
  63474. if (this._defaultModel) {
  63475. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  63476. }
  63477. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  63478. return;
  63479. case 2:// left AND right button
  63480. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  63481. return;
  63482. case 3:
  63483. if (this._defaultModel) {
  63484. if (notifyObject.pressed) {
  63485. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  63486. }
  63487. else {
  63488. (this._defaultModel.getChildren()[2]).position.y = 0;
  63489. }
  63490. }
  63491. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  63492. return;
  63493. }
  63494. };
  63495. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  63496. ViveController.MODEL_FILENAME = 'wand.babylon';
  63497. return ViveController;
  63498. }(BABYLON.WebVRController));
  63499. BABYLON.ViveController = ViveController;
  63500. })(BABYLON || (BABYLON = {}));
  63501. //# sourceMappingURL=babylon.viveController.js.map
  63502. var BABYLON;
  63503. (function (BABYLON) {
  63504. var GenericController = /** @class */ (function (_super) {
  63505. __extends(GenericController, _super);
  63506. function GenericController(vrGamepad) {
  63507. return _super.call(this, vrGamepad) || this;
  63508. }
  63509. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  63510. var _this = this;
  63511. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  63512. _this._defaultModel = newMeshes[1];
  63513. _this.attachToMesh(_this._defaultModel);
  63514. if (meshLoaded) {
  63515. meshLoaded(_this._defaultModel);
  63516. }
  63517. });
  63518. };
  63519. GenericController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  63520. console.log("Button id: " + buttonIdx + "state: ");
  63521. console.dir(state);
  63522. };
  63523. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  63524. GenericController.MODEL_FILENAME = 'generic.babylon';
  63525. return GenericController;
  63526. }(BABYLON.WebVRController));
  63527. BABYLON.GenericController = GenericController;
  63528. })(BABYLON || (BABYLON = {}));
  63529. //# sourceMappingURL=babylon.genericController.js.map
  63530. var BABYLON;
  63531. (function (BABYLON) {
  63532. var LoadedMeshInfo = /** @class */ (function () {
  63533. function LoadedMeshInfo() {
  63534. this.buttonMeshes = {};
  63535. this.axisMeshes = {};
  63536. }
  63537. return LoadedMeshInfo;
  63538. }());
  63539. var WindowsMotionController = /** @class */ (function (_super) {
  63540. __extends(WindowsMotionController, _super);
  63541. function WindowsMotionController(vrGamepad) {
  63542. var _this = _super.call(this, vrGamepad) || this;
  63543. _this._mapping = {
  63544. // Semantic button names
  63545. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  63546. // A mapping of the button name to glTF model node name
  63547. // that should be transformed by button value.
  63548. buttonMeshNames: {
  63549. 'trigger': 'SELECT',
  63550. 'menu': 'MENU',
  63551. 'grip': 'GRASP',
  63552. 'thumbstick': 'THUMBSTICK_PRESS',
  63553. 'trackpad': 'TOUCHPAD_PRESS'
  63554. },
  63555. // This mapping is used to translate from the Motion Controller to Babylon semantics
  63556. buttonObservableNames: {
  63557. 'trigger': 'onTriggerStateChangedObservable',
  63558. 'menu': 'onSecondaryButtonStateChangedObservable',
  63559. 'grip': 'onMainButtonStateChangedObservable',
  63560. 'thumbstick': 'onPadStateChangedObservable',
  63561. 'trackpad': 'onTrackpadChangedObservable'
  63562. },
  63563. // A mapping of the axis name to glTF model node name
  63564. // that should be transformed by axis value.
  63565. // This array mirrors the browserGamepad.axes array, such that
  63566. // the mesh corresponding to axis 0 is in this array index 0.
  63567. axisMeshNames: [
  63568. 'THUMBSTICK_X',
  63569. 'THUMBSTICK_Y',
  63570. 'TOUCHPAD_TOUCH_X',
  63571. 'TOUCHPAD_TOUCH_Y'
  63572. ],
  63573. pointingPoseMeshName: 'POINTING_POSE'
  63574. };
  63575. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  63576. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  63577. _this.trackpad = { x: 0, y: 0 };
  63578. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  63579. _this._loadedMeshInfo = null;
  63580. return _this;
  63581. }
  63582. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  63583. get: function () {
  63584. return this.onTriggerStateChangedObservable;
  63585. },
  63586. enumerable: true,
  63587. configurable: true
  63588. });
  63589. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  63590. get: function () {
  63591. return this.onSecondaryButtonStateChangedObservable;
  63592. },
  63593. enumerable: true,
  63594. configurable: true
  63595. });
  63596. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  63597. get: function () {
  63598. return this.onMainButtonStateChangedObservable;
  63599. },
  63600. enumerable: true,
  63601. configurable: true
  63602. });
  63603. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  63604. get: function () {
  63605. return this.onPadStateChangedObservable;
  63606. },
  63607. enumerable: true,
  63608. configurable: true
  63609. });
  63610. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  63611. get: function () {
  63612. return this.onTrackpadChangedObservable;
  63613. },
  63614. enumerable: true,
  63615. configurable: true
  63616. });
  63617. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  63618. get: function () {
  63619. return this.onTrackpadValuesChangedObservable;
  63620. },
  63621. enumerable: true,
  63622. configurable: true
  63623. });
  63624. /**
  63625. * Called once per frame by the engine.
  63626. */
  63627. WindowsMotionController.prototype.update = function () {
  63628. _super.prototype.update.call(this);
  63629. // Only need to animate axes if there is a loaded mesh
  63630. if (this._loadedMeshInfo) {
  63631. if (this.browserGamepad.axes) {
  63632. if (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y) {
  63633. this.trackpad.x = this.browserGamepad["axes"][2];
  63634. this.trackpad.y = this.browserGamepad["axes"][3];
  63635. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  63636. }
  63637. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  63638. this.lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  63639. }
  63640. }
  63641. }
  63642. };
  63643. /**
  63644. * Called once for each button that changed state since the last frame
  63645. * @param buttonIdx Which button index changed
  63646. * @param state New state of the button
  63647. * @param changes Which properties on the state changed since last frame
  63648. */
  63649. WindowsMotionController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  63650. var buttonName = this._mapping.buttons[buttonIdx];
  63651. if (!buttonName) {
  63652. return;
  63653. }
  63654. // Only emit events for buttons that we know how to map from index to name
  63655. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  63656. if (observable) {
  63657. observable.notifyObservers(state);
  63658. }
  63659. this.lerpButtonTransform(buttonName, state.value);
  63660. };
  63661. WindowsMotionController.prototype.lerpButtonTransform = function (buttonName, buttonValue) {
  63662. // If there is no loaded mesh, there is nothing to transform.
  63663. if (!this._loadedMeshInfo) {
  63664. return;
  63665. }
  63666. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  63667. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  63668. return;
  63669. }
  63670. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  63671. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  63672. };
  63673. WindowsMotionController.prototype.lerpAxisTransform = function (axis, axisValue) {
  63674. if (!this._loadedMeshInfo) {
  63675. return;
  63676. }
  63677. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  63678. if (!meshInfo) {
  63679. return;
  63680. }
  63681. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  63682. return;
  63683. }
  63684. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  63685. var lerpValue = axisValue * 0.5 + 0.5;
  63686. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  63687. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  63688. };
  63689. /**
  63690. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  63691. * @param scene scene in which to add meshes
  63692. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  63693. */
  63694. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  63695. var _this = this;
  63696. if (forceDefault === void 0) { forceDefault = false; }
  63697. var path;
  63698. var filename;
  63699. // Checking if GLB loader is present
  63700. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  63701. // Determine the device specific folder based on the ID suffix
  63702. var device = 'default';
  63703. if (this.id && !forceDefault) {
  63704. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  63705. device = ((match && match[0]) || device);
  63706. }
  63707. // Hand
  63708. if (this.hand === 'left') {
  63709. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  63710. }
  63711. else {
  63712. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  63713. }
  63714. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  63715. }
  63716. else {
  63717. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  63718. path = BABYLON.GenericController.MODEL_BASE_URL;
  63719. filename = BABYLON.GenericController.MODEL_FILENAME;
  63720. }
  63721. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  63722. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  63723. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  63724. if (!_this._loadedMeshInfo) {
  63725. return;
  63726. }
  63727. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  63728. _this.attachToMesh(_this._defaultModel);
  63729. if (meshLoaded) {
  63730. meshLoaded(_this._defaultModel);
  63731. }
  63732. }, null, function (scene, message) {
  63733. BABYLON.Tools.Log(message);
  63734. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  63735. if (!forceDefault) {
  63736. _this.initControllerMesh(scene, meshLoaded, true);
  63737. }
  63738. });
  63739. };
  63740. /**
  63741. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  63742. * can be transformed by button presses and axes values, based on this._mapping.
  63743. *
  63744. * @param scene scene in which the meshes exist
  63745. * @param meshes list of meshes that make up the controller model to process
  63746. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  63747. */
  63748. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  63749. var loadedMeshInfo = null;
  63750. // Create a new mesh to contain the glTF hierarchy
  63751. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  63752. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  63753. var childMesh = null;
  63754. for (var i = 0; i < meshes.length; i++) {
  63755. var mesh = meshes[i];
  63756. if (!mesh.parent) {
  63757. // Exclude controller meshes from picking results
  63758. mesh.isPickable = false;
  63759. // Handle root node, attach to the new parentMesh
  63760. childMesh = mesh;
  63761. break;
  63762. }
  63763. }
  63764. if (childMesh) {
  63765. childMesh.setParent(parentMesh);
  63766. // Create our mesh info. Note that this method will always return non-null.
  63767. loadedMeshInfo = this.createMeshInfo(parentMesh);
  63768. }
  63769. else {
  63770. BABYLON.Tools.Warn('Could not find root node in model file.');
  63771. }
  63772. return loadedMeshInfo;
  63773. };
  63774. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  63775. var loadedMeshInfo = new LoadedMeshInfo();
  63776. var i;
  63777. loadedMeshInfo.rootNode = rootNode;
  63778. // Reset the caches
  63779. loadedMeshInfo.buttonMeshes = {};
  63780. loadedMeshInfo.axisMeshes = {};
  63781. // Button Meshes
  63782. for (i = 0; i < this._mapping.buttons.length; i++) {
  63783. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  63784. if (!buttonMeshName) {
  63785. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  63786. continue;
  63787. }
  63788. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  63789. if (!buttonMesh) {
  63790. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  63791. continue;
  63792. }
  63793. var buttonMeshInfo = {
  63794. index: i,
  63795. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  63796. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  63797. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  63798. };
  63799. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  63800. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  63801. }
  63802. else {
  63803. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  63804. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  63805. '(VALUE: ' + !!buttonMeshInfo.value +
  63806. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  63807. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  63808. ')');
  63809. }
  63810. }
  63811. // Axis Meshes
  63812. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  63813. var axisMeshName = this._mapping.axisMeshNames[i];
  63814. if (!axisMeshName) {
  63815. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  63816. continue;
  63817. }
  63818. var axisMesh = getChildByName(rootNode, axisMeshName);
  63819. if (!axisMesh) {
  63820. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  63821. continue;
  63822. }
  63823. var axisMeshInfo = {
  63824. index: i,
  63825. value: getImmediateChildByName(axisMesh, 'VALUE'),
  63826. min: getImmediateChildByName(axisMesh, 'MIN'),
  63827. max: getImmediateChildByName(axisMesh, 'MAX')
  63828. };
  63829. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  63830. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  63831. }
  63832. else {
  63833. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  63834. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  63835. '(VALUE: ' + !!axisMeshInfo.value +
  63836. ', MIN: ' + !!axisMeshInfo.min +
  63837. ', MAX:' + !!axisMeshInfo.max +
  63838. ')');
  63839. }
  63840. }
  63841. // Pointing Ray
  63842. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  63843. if (!loadedMeshInfo.pointingPoseNode) {
  63844. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  63845. }
  63846. return loadedMeshInfo;
  63847. // Look through all children recursively. This will return null if no mesh exists with the given name.
  63848. function getChildByName(node, name) {
  63849. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  63850. }
  63851. // Look through only immediate children. This will return null if no mesh exists with the given name.
  63852. function getImmediateChildByName(node, name) {
  63853. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  63854. }
  63855. };
  63856. WindowsMotionController.prototype.getForwardRay = function (length) {
  63857. if (length === void 0) { length = 100; }
  63858. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  63859. return _super.prototype.getForwardRay.call(this, length);
  63860. }
  63861. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  63862. var origin = m.getTranslation();
  63863. var forward = new BABYLON.Vector3(0, 0, -1);
  63864. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  63865. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  63866. return new BABYLON.Ray(origin, direction, length);
  63867. };
  63868. WindowsMotionController.prototype.dispose = function () {
  63869. _super.prototype.dispose.call(this);
  63870. this.onTrackpadChangedObservable.clear();
  63871. };
  63872. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  63873. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  63874. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  63875. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  63876. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  63877. return WindowsMotionController;
  63878. }(BABYLON.WebVRController));
  63879. BABYLON.WindowsMotionController = WindowsMotionController;
  63880. })(BABYLON || (BABYLON = {}));
  63881. //# sourceMappingURL=babylon.windowsMotionController.js.map
  63882. var BABYLON;
  63883. (function (BABYLON) {
  63884. var GearVRController = /** @class */ (function (_super) {
  63885. __extends(GearVRController, _super);
  63886. function GearVRController(vrGamepad) {
  63887. var _this = _super.call(this, vrGamepad) || this;
  63888. _this._buttonIndexToObservableNameMap = [
  63889. 'onTrackpadChangedObservable',
  63890. 'onTriggerStateChangedObservable' // Trigger
  63891. ];
  63892. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  63893. return _this;
  63894. }
  63895. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  63896. var _this = this;
  63897. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  63898. _this._defaultModel = newMeshes[1];
  63899. _this.attachToMesh(_this._defaultModel);
  63900. if (meshLoaded) {
  63901. meshLoaded(_this._defaultModel);
  63902. }
  63903. });
  63904. };
  63905. GearVRController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  63906. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  63907. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  63908. // Only emit events for buttons that we know how to map from index to observable
  63909. var observable = this[observableName];
  63910. if (observable) {
  63911. observable.notifyObservers(state);
  63912. }
  63913. }
  63914. };
  63915. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  63916. GearVRController.MODEL_FILENAME = 'generic.babylon';
  63917. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  63918. return GearVRController;
  63919. }(BABYLON.WebVRController));
  63920. BABYLON.GearVRController = GearVRController;
  63921. })(BABYLON || (BABYLON = {}));
  63922. //# sourceMappingURL=babylon.gearVRController.js.map
  63923. var BABYLON;
  63924. (function (BABYLON) {
  63925. var FollowCamera = /** @class */ (function (_super) {
  63926. __extends(FollowCamera, _super);
  63927. function FollowCamera(name, position, scene, lockedTarget) {
  63928. if (lockedTarget === void 0) { lockedTarget = null; }
  63929. var _this = _super.call(this, name, position, scene) || this;
  63930. _this.radius = 12;
  63931. _this.rotationOffset = 0;
  63932. _this.heightOffset = 4;
  63933. _this.cameraAcceleration = 0.05;
  63934. _this.maxCameraSpeed = 20;
  63935. _this.lockedTarget = lockedTarget;
  63936. return _this;
  63937. }
  63938. FollowCamera.prototype.getRadians = function (degrees) {
  63939. return degrees * Math.PI / 180;
  63940. };
  63941. FollowCamera.prototype.follow = function (cameraTarget) {
  63942. if (!cameraTarget)
  63943. return;
  63944. var yRotation;
  63945. if (cameraTarget.rotationQuaternion) {
  63946. var rotMatrix = new BABYLON.Matrix();
  63947. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  63948. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  63949. }
  63950. else {
  63951. yRotation = cameraTarget.rotation.y;
  63952. }
  63953. var radians = this.getRadians(this.rotationOffset) + yRotation;
  63954. var targetPosition = cameraTarget.getAbsolutePosition();
  63955. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  63956. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  63957. var dx = targetX - this.position.x;
  63958. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  63959. var dz = (targetZ) - this.position.z;
  63960. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  63961. var vy = dy * this.cameraAcceleration;
  63962. var vz = dz * this.cameraAcceleration * 2;
  63963. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  63964. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  63965. }
  63966. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  63967. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  63968. }
  63969. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  63970. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  63971. }
  63972. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  63973. this.setTarget(targetPosition);
  63974. };
  63975. FollowCamera.prototype._checkInputs = function () {
  63976. _super.prototype._checkInputs.call(this);
  63977. if (this.lockedTarget) {
  63978. this.follow(this.lockedTarget);
  63979. }
  63980. };
  63981. FollowCamera.prototype.getClassName = function () {
  63982. return "FollowCamera";
  63983. };
  63984. __decorate([
  63985. BABYLON.serialize()
  63986. ], FollowCamera.prototype, "radius", void 0);
  63987. __decorate([
  63988. BABYLON.serialize()
  63989. ], FollowCamera.prototype, "rotationOffset", void 0);
  63990. __decorate([
  63991. BABYLON.serialize()
  63992. ], FollowCamera.prototype, "heightOffset", void 0);
  63993. __decorate([
  63994. BABYLON.serialize()
  63995. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  63996. __decorate([
  63997. BABYLON.serialize()
  63998. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  63999. __decorate([
  64000. BABYLON.serializeAsMeshReference("lockedTargetId")
  64001. ], FollowCamera.prototype, "lockedTarget", void 0);
  64002. return FollowCamera;
  64003. }(BABYLON.TargetCamera));
  64004. BABYLON.FollowCamera = FollowCamera;
  64005. var ArcFollowCamera = /** @class */ (function (_super) {
  64006. __extends(ArcFollowCamera, _super);
  64007. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  64008. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  64009. _this.alpha = alpha;
  64010. _this.beta = beta;
  64011. _this.radius = radius;
  64012. _this.target = target;
  64013. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  64014. _this.follow();
  64015. return _this;
  64016. }
  64017. ArcFollowCamera.prototype.follow = function () {
  64018. if (!this.target) {
  64019. return;
  64020. }
  64021. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  64022. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  64023. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  64024. var targetPosition = this.target.getAbsolutePosition();
  64025. this.position = targetPosition.add(this._cartesianCoordinates);
  64026. this.setTarget(targetPosition);
  64027. };
  64028. ArcFollowCamera.prototype._checkInputs = function () {
  64029. _super.prototype._checkInputs.call(this);
  64030. this.follow();
  64031. };
  64032. ArcFollowCamera.prototype.getClassName = function () {
  64033. return "ArcFollowCamera";
  64034. };
  64035. return ArcFollowCamera;
  64036. }(BABYLON.TargetCamera));
  64037. BABYLON.ArcFollowCamera = ArcFollowCamera;
  64038. })(BABYLON || (BABYLON = {}));
  64039. //# sourceMappingURL=babylon.followCamera.js.map
  64040. var BABYLON;
  64041. (function (BABYLON) {
  64042. // We're mainly based on the logic defined into the FreeCamera code
  64043. var UniversalCamera = /** @class */ (function (_super) {
  64044. __extends(UniversalCamera, _super);
  64045. //-- end properties for backward compatibility for inputs
  64046. function UniversalCamera(name, position, scene) {
  64047. var _this = _super.call(this, name, position, scene) || this;
  64048. _this.inputs.addGamepad();
  64049. return _this;
  64050. }
  64051. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  64052. //-- Begin properties for backward compatibility for inputs
  64053. get: function () {
  64054. var gamepad = this.inputs.attached["gamepad"];
  64055. if (gamepad)
  64056. return gamepad.gamepadAngularSensibility;
  64057. return 0;
  64058. },
  64059. set: function (value) {
  64060. var gamepad = this.inputs.attached["gamepad"];
  64061. if (gamepad)
  64062. gamepad.gamepadAngularSensibility = value;
  64063. },
  64064. enumerable: true,
  64065. configurable: true
  64066. });
  64067. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  64068. get: function () {
  64069. var gamepad = this.inputs.attached["gamepad"];
  64070. if (gamepad)
  64071. return gamepad.gamepadMoveSensibility;
  64072. return 0;
  64073. },
  64074. set: function (value) {
  64075. var gamepad = this.inputs.attached["gamepad"];
  64076. if (gamepad)
  64077. gamepad.gamepadMoveSensibility = value;
  64078. },
  64079. enumerable: true,
  64080. configurable: true
  64081. });
  64082. UniversalCamera.prototype.getClassName = function () {
  64083. return "UniversalCamera";
  64084. };
  64085. return UniversalCamera;
  64086. }(BABYLON.TouchCamera));
  64087. BABYLON.UniversalCamera = UniversalCamera;
  64088. })(BABYLON || (BABYLON = {}));
  64089. //# sourceMappingURL=babylon.universalCamera.js.map
  64090. var BABYLON;
  64091. (function (BABYLON) {
  64092. // We're mainly based on the logic defined into the FreeCamera code
  64093. var GamepadCamera = /** @class */ (function (_super) {
  64094. __extends(GamepadCamera, _super);
  64095. //-- end properties for backward compatibility for inputs
  64096. function GamepadCamera(name, position, scene) {
  64097. return _super.call(this, name, position, scene) || this;
  64098. }
  64099. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  64100. //-- Begin properties for backward compatibility for inputs
  64101. get: function () {
  64102. var gamepad = this.inputs.attached["gamepad"];
  64103. if (gamepad)
  64104. return gamepad.gamepadAngularSensibility;
  64105. return 0;
  64106. },
  64107. set: function (value) {
  64108. var gamepad = this.inputs.attached["gamepad"];
  64109. if (gamepad)
  64110. gamepad.gamepadAngularSensibility = value;
  64111. },
  64112. enumerable: true,
  64113. configurable: true
  64114. });
  64115. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  64116. get: function () {
  64117. var gamepad = this.inputs.attached["gamepad"];
  64118. if (gamepad)
  64119. return gamepad.gamepadMoveSensibility;
  64120. return 0;
  64121. },
  64122. set: function (value) {
  64123. var gamepad = this.inputs.attached["gamepad"];
  64124. if (gamepad)
  64125. gamepad.gamepadMoveSensibility = value;
  64126. },
  64127. enumerable: true,
  64128. configurable: true
  64129. });
  64130. GamepadCamera.prototype.getClassName = function () {
  64131. return "GamepadCamera";
  64132. };
  64133. return GamepadCamera;
  64134. }(BABYLON.UniversalCamera));
  64135. BABYLON.GamepadCamera = GamepadCamera;
  64136. })(BABYLON || (BABYLON = {}));
  64137. //# sourceMappingURL=babylon.gamepadCamera.js.map
  64138. var BABYLON;
  64139. (function (BABYLON) {
  64140. var PostProcessRenderPipelineManager = /** @class */ (function () {
  64141. function PostProcessRenderPipelineManager() {
  64142. this._renderPipelines = {};
  64143. }
  64144. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  64145. this._renderPipelines[renderPipeline._name] = renderPipeline;
  64146. };
  64147. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  64148. if (unique === void 0) { unique = false; }
  64149. var renderPipeline = this._renderPipelines[renderPipelineName];
  64150. if (!renderPipeline) {
  64151. return;
  64152. }
  64153. renderPipeline._attachCameras(cameras, unique);
  64154. };
  64155. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  64156. var renderPipeline = this._renderPipelines[renderPipelineName];
  64157. if (!renderPipeline) {
  64158. return;
  64159. }
  64160. renderPipeline._detachCameras(cameras);
  64161. };
  64162. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  64163. var renderPipeline = this._renderPipelines[renderPipelineName];
  64164. if (!renderPipeline) {
  64165. return;
  64166. }
  64167. renderPipeline._enableEffect(renderEffectName, cameras);
  64168. };
  64169. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  64170. var renderPipeline = this._renderPipelines[renderPipelineName];
  64171. if (!renderPipeline) {
  64172. return;
  64173. }
  64174. renderPipeline._disableEffect(renderEffectName, cameras);
  64175. };
  64176. PostProcessRenderPipelineManager.prototype.update = function () {
  64177. for (var renderPipelineName in this._renderPipelines) {
  64178. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  64179. var pipeline = this._renderPipelines[renderPipelineName];
  64180. if (!pipeline.isSupported) {
  64181. pipeline.dispose();
  64182. delete this._renderPipelines[renderPipelineName];
  64183. }
  64184. else {
  64185. pipeline._update();
  64186. }
  64187. }
  64188. }
  64189. };
  64190. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  64191. for (var renderPipelineName in this._renderPipelines) {
  64192. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  64193. var pipeline = this._renderPipelines[renderPipelineName];
  64194. pipeline._rebuild();
  64195. }
  64196. }
  64197. };
  64198. PostProcessRenderPipelineManager.prototype.dispose = function () {
  64199. for (var renderPipelineName in this._renderPipelines) {
  64200. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  64201. var pipeline = this._renderPipelines[renderPipelineName];
  64202. pipeline.dispose();
  64203. }
  64204. }
  64205. };
  64206. return PostProcessRenderPipelineManager;
  64207. }());
  64208. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  64209. })(BABYLON || (BABYLON = {}));
  64210. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  64211. var BABYLON;
  64212. (function (BABYLON) {
  64213. /**
  64214. * This represents a set of one or more post processes in Babylon.
  64215. * A post process can be used to apply a shader to a texture after it is rendered.
  64216. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  64217. */
  64218. var PostProcessRenderEffect = /** @class */ (function () {
  64219. /**
  64220. * Instantiates a post process render effect.
  64221. * A post process can be used to apply a shader to a texture after it is rendered.
  64222. * @param engine The engine the effect is tied to
  64223. * @param name The name of the effect
  64224. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  64225. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  64226. */
  64227. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  64228. this._name = name;
  64229. this._singleInstance = singleInstance || true;
  64230. this._getPostProcesses = getPostProcesses;
  64231. this._cameras = {};
  64232. this._indicesForCamera = {};
  64233. this._postProcesses = {};
  64234. }
  64235. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  64236. /**
  64237. * Checks if all the post processes in the effect are supported.
  64238. */
  64239. get: function () {
  64240. for (var index in this._postProcesses) {
  64241. for (var ppIndex in this._postProcesses[index]) {
  64242. if (!this._postProcesses[index][ppIndex].isSupported) {
  64243. return false;
  64244. }
  64245. }
  64246. }
  64247. return true;
  64248. },
  64249. enumerable: true,
  64250. configurable: true
  64251. });
  64252. /**
  64253. * Updates the current state of the effect
  64254. */
  64255. PostProcessRenderEffect.prototype._update = function () {
  64256. };
  64257. /**
  64258. * Attaches the effect on cameras
  64259. * @param cameras The camera to attach to.
  64260. */
  64261. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  64262. var _this = this;
  64263. var cameraKey;
  64264. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  64265. if (!cams) {
  64266. return;
  64267. }
  64268. for (var i = 0; i < cams.length; i++) {
  64269. var camera = cams[i];
  64270. var cameraName = camera.name;
  64271. if (this._singleInstance) {
  64272. cameraKey = 0;
  64273. }
  64274. else {
  64275. cameraKey = cameraName;
  64276. }
  64277. if (!this._postProcesses[cameraKey]) {
  64278. var postProcess = this._getPostProcesses();
  64279. if (postProcess) {
  64280. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  64281. }
  64282. }
  64283. if (!this._indicesForCamera[cameraName]) {
  64284. this._indicesForCamera[cameraName] = [];
  64285. }
  64286. this._postProcesses[cameraKey].forEach(function (postProcess) {
  64287. var index = camera.attachPostProcess(postProcess);
  64288. _this._indicesForCamera[cameraName].push(index);
  64289. });
  64290. if (!this._cameras[cameraName]) {
  64291. this._cameras[cameraName] = camera;
  64292. }
  64293. }
  64294. };
  64295. /**
  64296. * Detatches the effect on cameras
  64297. * @param cameras The camera to detatch from.
  64298. */
  64299. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  64300. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  64301. if (!cams) {
  64302. return;
  64303. }
  64304. for (var i = 0; i < cams.length; i++) {
  64305. var camera = cams[i];
  64306. var cameraName = camera.name;
  64307. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  64308. camera.detachPostProcess(postProcess);
  64309. });
  64310. if (this._cameras[cameraName]) {
  64311. //this._indicesForCamera.splice(index, 1);
  64312. this._cameras[cameraName] = null;
  64313. }
  64314. }
  64315. };
  64316. /**
  64317. * Enables the effect on given cameras
  64318. * @param cameras The camera to enable.
  64319. */
  64320. PostProcessRenderEffect.prototype._enable = function (cameras) {
  64321. var _this = this;
  64322. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  64323. if (!cams) {
  64324. return;
  64325. }
  64326. for (var i = 0; i < cams.length; i++) {
  64327. var camera = cams[i];
  64328. var cameraName = camera.name;
  64329. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  64330. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  64331. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  64332. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  64333. });
  64334. }
  64335. }
  64336. }
  64337. };
  64338. /**
  64339. * Disables the effect on the given cameras
  64340. * @param cameras The camera to disable.
  64341. */
  64342. PostProcessRenderEffect.prototype._disable = function (cameras) {
  64343. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  64344. if (!cams) {
  64345. return;
  64346. }
  64347. for (var i = 0; i < cams.length; i++) {
  64348. var camera = cams[i];
  64349. var cameraName = camera.name;
  64350. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  64351. camera.detachPostProcess(postProcess);
  64352. });
  64353. }
  64354. };
  64355. /**
  64356. * Gets a list of the post processes contained in the effect.
  64357. * @param camera The camera to get the post processes on.
  64358. * @returns The list of the post processes in the effect.
  64359. */
  64360. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  64361. if (this._singleInstance) {
  64362. return this._postProcesses[0];
  64363. }
  64364. else {
  64365. if (!camera) {
  64366. return null;
  64367. }
  64368. return this._postProcesses[camera.name];
  64369. }
  64370. };
  64371. return PostProcessRenderEffect;
  64372. }());
  64373. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  64374. })(BABYLON || (BABYLON = {}));
  64375. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  64376. var BABYLON;
  64377. (function (BABYLON) {
  64378. var PostProcessRenderPipeline = /** @class */ (function () {
  64379. function PostProcessRenderPipeline(engine, name) {
  64380. this._name = name;
  64381. this._renderEffects = {};
  64382. this._renderEffectsForIsolatedPass = new Array();
  64383. this._cameras = [];
  64384. }
  64385. PostProcessRenderPipeline.prototype.getClassName = function () {
  64386. return "PostProcessRenderPipeline";
  64387. };
  64388. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  64389. get: function () {
  64390. for (var renderEffectName in this._renderEffects) {
  64391. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  64392. if (!this._renderEffects[renderEffectName].isSupported) {
  64393. return false;
  64394. }
  64395. }
  64396. }
  64397. return true;
  64398. },
  64399. enumerable: true,
  64400. configurable: true
  64401. });
  64402. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  64403. this._renderEffects[renderEffect._name] = renderEffect;
  64404. };
  64405. // private
  64406. PostProcessRenderPipeline.prototype._rebuild = function () {
  64407. };
  64408. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  64409. var renderEffects = this._renderEffects[renderEffectName];
  64410. if (!renderEffects) {
  64411. return;
  64412. }
  64413. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  64414. };
  64415. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  64416. var renderEffects = this._renderEffects[renderEffectName];
  64417. if (!renderEffects) {
  64418. return;
  64419. }
  64420. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  64421. };
  64422. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  64423. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  64424. if (!cams) {
  64425. return;
  64426. }
  64427. var indicesToDelete = [];
  64428. var i;
  64429. for (i = 0; i < cams.length; i++) {
  64430. var camera = cams[i];
  64431. var cameraName = camera.name;
  64432. if (this._cameras.indexOf(camera) === -1) {
  64433. this._cameras[cameraName] = camera;
  64434. }
  64435. else if (unique) {
  64436. indicesToDelete.push(i);
  64437. }
  64438. }
  64439. for (i = 0; i < indicesToDelete.length; i++) {
  64440. cameras.splice(indicesToDelete[i], 1);
  64441. }
  64442. for (var renderEffectName in this._renderEffects) {
  64443. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  64444. this._renderEffects[renderEffectName]._attachCameras(cams);
  64445. }
  64446. }
  64447. };
  64448. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  64449. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  64450. if (!cams) {
  64451. return;
  64452. }
  64453. for (var renderEffectName in this._renderEffects) {
  64454. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  64455. this._renderEffects[renderEffectName]._detachCameras(cams);
  64456. }
  64457. }
  64458. for (var i = 0; i < cams.length; i++) {
  64459. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  64460. }
  64461. };
  64462. PostProcessRenderPipeline.prototype._update = function () {
  64463. for (var renderEffectName in this._renderEffects) {
  64464. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  64465. this._renderEffects[renderEffectName]._update();
  64466. }
  64467. }
  64468. for (var i = 0; i < this._cameras.length; i++) {
  64469. var cameraName = this._cameras[i].name;
  64470. if (this._renderEffectsForIsolatedPass[cameraName]) {
  64471. this._renderEffectsForIsolatedPass[cameraName]._update();
  64472. }
  64473. }
  64474. };
  64475. PostProcessRenderPipeline.prototype._reset = function () {
  64476. this._renderEffects = {};
  64477. this._renderEffectsForIsolatedPass = new Array();
  64478. };
  64479. PostProcessRenderPipeline.prototype.dispose = function () {
  64480. // Must be implemented by children
  64481. };
  64482. __decorate([
  64483. BABYLON.serialize()
  64484. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  64485. return PostProcessRenderPipeline;
  64486. }());
  64487. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  64488. })(BABYLON || (BABYLON = {}));
  64489. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  64490. var BABYLON;
  64491. (function (BABYLON) {
  64492. var DepthRenderer = /** @class */ (function () {
  64493. function DepthRenderer(scene, type) {
  64494. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  64495. var _this = this;
  64496. this._scene = scene;
  64497. var engine = scene.getEngine();
  64498. // Render target
  64499. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  64500. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64501. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64502. this._depthMap.refreshRate = 1;
  64503. this._depthMap.renderParticles = false;
  64504. this._depthMap.renderList = null;
  64505. // set default depth value to 1.0 (far away)
  64506. this._depthMap.onClearObservable.add(function (engine) {
  64507. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  64508. });
  64509. // Custom render function
  64510. var renderSubMesh = function (subMesh) {
  64511. var mesh = subMesh.getRenderingMesh();
  64512. var scene = _this._scene;
  64513. var engine = scene.getEngine();
  64514. var material = subMesh.getMaterial();
  64515. if (!material) {
  64516. return;
  64517. }
  64518. // Culling and reverse (right handed system)
  64519. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  64520. // Managing instances
  64521. var batch = mesh._getInstancesRenderList(subMesh._id);
  64522. if (batch.mustReturn) {
  64523. return;
  64524. }
  64525. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  64526. if (_this.isReady(subMesh, hardwareInstancedRendering) && scene.activeCamera) {
  64527. engine.enableEffect(_this._effect);
  64528. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  64529. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  64530. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.minZ + scene.activeCamera.maxZ);
  64531. // Alpha test
  64532. if (material && material.needAlphaTesting()) {
  64533. var alphaTexture = material.getAlphaTestTexture();
  64534. if (alphaTexture) {
  64535. _this._effect.setTexture("diffuseSampler", alphaTexture);
  64536. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  64537. }
  64538. }
  64539. // Bones
  64540. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  64541. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  64542. }
  64543. // Draw
  64544. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  64545. }
  64546. };
  64547. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  64548. var index;
  64549. if (depthOnlySubMeshes.length) {
  64550. engine.setColorWrite(false);
  64551. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  64552. renderSubMesh(depthOnlySubMeshes.data[index]);
  64553. }
  64554. engine.setColorWrite(true);
  64555. }
  64556. for (index = 0; index < opaqueSubMeshes.length; index++) {
  64557. renderSubMesh(opaqueSubMeshes.data[index]);
  64558. }
  64559. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  64560. renderSubMesh(alphaTestSubMeshes.data[index]);
  64561. }
  64562. };
  64563. }
  64564. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  64565. var material = subMesh.getMaterial();
  64566. if (material.disableDepthWrite) {
  64567. return false;
  64568. }
  64569. var defines = [];
  64570. var attribs = [BABYLON.VertexBuffer.PositionKind];
  64571. var mesh = subMesh.getMesh();
  64572. // Alpha test
  64573. if (material && material.needAlphaTesting()) {
  64574. defines.push("#define ALPHATEST");
  64575. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  64576. attribs.push(BABYLON.VertexBuffer.UVKind);
  64577. defines.push("#define UV1");
  64578. }
  64579. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  64580. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  64581. defines.push("#define UV2");
  64582. }
  64583. }
  64584. // Bones
  64585. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  64586. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  64587. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  64588. if (mesh.numBoneInfluencers > 4) {
  64589. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  64590. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  64591. }
  64592. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  64593. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  64594. }
  64595. else {
  64596. defines.push("#define NUM_BONE_INFLUENCERS 0");
  64597. }
  64598. // Instances
  64599. if (useInstances) {
  64600. defines.push("#define INSTANCES");
  64601. attribs.push("world0");
  64602. attribs.push("world1");
  64603. attribs.push("world2");
  64604. attribs.push("world3");
  64605. }
  64606. // Get correct effect
  64607. var join = defines.join("\n");
  64608. if (this._cachedDefines !== join) {
  64609. this._cachedDefines = join;
  64610. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  64611. }
  64612. return this._effect.isReady();
  64613. };
  64614. DepthRenderer.prototype.getDepthMap = function () {
  64615. return this._depthMap;
  64616. };
  64617. // Methods
  64618. DepthRenderer.prototype.dispose = function () {
  64619. this._depthMap.dispose();
  64620. };
  64621. return DepthRenderer;
  64622. }());
  64623. BABYLON.DepthRenderer = DepthRenderer;
  64624. })(BABYLON || (BABYLON = {}));
  64625. //# sourceMappingURL=babylon.depthRenderer.js.map
  64626. var BABYLON;
  64627. (function (BABYLON) {
  64628. var SSAORenderingPipeline = /** @class */ (function (_super) {
  64629. __extends(SSAORenderingPipeline, _super);
  64630. /**
  64631. * @constructor
  64632. * @param {string} name - The rendering pipeline name
  64633. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  64634. * @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 }
  64635. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  64636. */
  64637. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  64638. var _this = _super.call(this, scene.getEngine(), name) || this;
  64639. // Members
  64640. /**
  64641. * The PassPostProcess id in the pipeline that contains the original scene color
  64642. * @type {string}
  64643. */
  64644. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  64645. /**
  64646. * The SSAO PostProcess id in the pipeline
  64647. * @type {string}
  64648. */
  64649. _this.SSAORenderEffect = "SSAORenderEffect";
  64650. /**
  64651. * The horizontal blur PostProcess id in the pipeline
  64652. * @type {string}
  64653. */
  64654. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  64655. /**
  64656. * The vertical blur PostProcess id in the pipeline
  64657. * @type {string}
  64658. */
  64659. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  64660. /**
  64661. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  64662. * @type {string}
  64663. */
  64664. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  64665. /**
  64666. * The output strength of the SSAO post-process. Default value is 1.0.
  64667. * @type {number}
  64668. */
  64669. _this.totalStrength = 1.0;
  64670. /**
  64671. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  64672. * @type {number}
  64673. */
  64674. _this.radius = 0.0001;
  64675. /**
  64676. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  64677. * Must not be equal to fallOff and superior to fallOff.
  64678. * Default value is 0.975
  64679. * @type {number}
  64680. */
  64681. _this.area = 0.0075;
  64682. /**
  64683. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  64684. * Must not be equal to area and inferior to area.
  64685. * Default value is 0.0
  64686. * @type {number}
  64687. */
  64688. _this.fallOff = 0.000001;
  64689. /**
  64690. * The base color of the SSAO post-process
  64691. * The final result is "base + ssao" between [0, 1]
  64692. * @type {number}
  64693. */
  64694. _this.base = 0.5;
  64695. _this._firstUpdate = true;
  64696. _this._scene = scene;
  64697. // Set up assets
  64698. _this._createRandomTexture();
  64699. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  64700. var ssaoRatio = ratio.ssaoRatio || ratio;
  64701. var combineRatio = ratio.combineRatio || ratio;
  64702. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  64703. _this._createSSAOPostProcess(ssaoRatio);
  64704. _this._createBlurPostProcess(ssaoRatio);
  64705. _this._createSSAOCombinePostProcess(combineRatio);
  64706. // Set up pipeline
  64707. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  64708. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  64709. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  64710. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  64711. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  64712. // Finish
  64713. scene.postProcessRenderPipelineManager.addPipeline(_this);
  64714. if (cameras)
  64715. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  64716. return _this;
  64717. }
  64718. // Public Methods
  64719. /**
  64720. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  64721. */
  64722. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  64723. if (disableDepthRender === void 0) { disableDepthRender = false; }
  64724. for (var i = 0; i < this._scene.cameras.length; i++) {
  64725. var camera = this._scene.cameras[i];
  64726. this._originalColorPostProcess.dispose(camera);
  64727. this._ssaoPostProcess.dispose(camera);
  64728. this._blurHPostProcess.dispose(camera);
  64729. this._blurVPostProcess.dispose(camera);
  64730. this._ssaoCombinePostProcess.dispose(camera);
  64731. }
  64732. this._randomTexture.dispose();
  64733. if (disableDepthRender)
  64734. this._scene.disableDepthRenderer();
  64735. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  64736. _super.prototype.dispose.call(this);
  64737. };
  64738. // Private Methods
  64739. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  64740. var _this = this;
  64741. var size = 16;
  64742. 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);
  64743. 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);
  64744. this._blurHPostProcess.onActivateObservable.add(function () {
  64745. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  64746. _this._blurHPostProcess.kernel = size * dw;
  64747. });
  64748. this._blurVPostProcess.onActivateObservable.add(function () {
  64749. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  64750. _this._blurVPostProcess.kernel = size * dw;
  64751. });
  64752. };
  64753. SSAORenderingPipeline.prototype._rebuild = function () {
  64754. this._firstUpdate = true;
  64755. _super.prototype._rebuild.call(this);
  64756. };
  64757. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  64758. var _this = this;
  64759. var numSamples = 16;
  64760. var sampleSphere = [
  64761. 0.5381, 0.1856, -0.4319,
  64762. 0.1379, 0.2486, 0.4430,
  64763. 0.3371, 0.5679, -0.0057,
  64764. -0.6999, -0.0451, -0.0019,
  64765. 0.0689, -0.1598, -0.8547,
  64766. 0.0560, 0.0069, -0.1843,
  64767. -0.0146, 0.1402, 0.0762,
  64768. 0.0100, -0.1924, -0.0344,
  64769. -0.3577, -0.5301, -0.4358,
  64770. -0.3169, 0.1063, 0.0158,
  64771. 0.0103, -0.5869, 0.0046,
  64772. -0.0897, -0.4940, 0.3287,
  64773. 0.7119, -0.0154, -0.0918,
  64774. -0.0533, 0.0596, -0.5411,
  64775. 0.0352, -0.0631, 0.5460,
  64776. -0.4776, 0.2847, -0.0271
  64777. ];
  64778. var samplesFactor = 1.0 / numSamples;
  64779. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  64780. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  64781. "area", "fallOff", "base", "range", "viewport"
  64782. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  64783. this._ssaoPostProcess.onApply = function (effect) {
  64784. if (_this._firstUpdate) {
  64785. effect.setArray3("sampleSphere", sampleSphere);
  64786. effect.setFloat("samplesFactor", samplesFactor);
  64787. effect.setFloat("randTextureTiles", 4.0);
  64788. }
  64789. effect.setFloat("totalStrength", _this.totalStrength);
  64790. effect.setFloat("radius", _this.radius);
  64791. effect.setFloat("area", _this.area);
  64792. effect.setFloat("fallOff", _this.fallOff);
  64793. effect.setFloat("base", _this.base);
  64794. effect.setTexture("textureSampler", _this._depthTexture);
  64795. effect.setTexture("randomSampler", _this._randomTexture);
  64796. };
  64797. };
  64798. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  64799. var _this = this;
  64800. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  64801. this._ssaoCombinePostProcess.onApply = function (effect) {
  64802. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  64803. };
  64804. };
  64805. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  64806. var size = 512;
  64807. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  64808. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  64809. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  64810. var context = this._randomTexture.getContext();
  64811. var rand = function (min, max) {
  64812. return Math.random() * (max - min) + min;
  64813. };
  64814. var randVector = BABYLON.Vector3.Zero();
  64815. for (var x = 0; x < size; x++) {
  64816. for (var y = 0; y < size; y++) {
  64817. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  64818. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  64819. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  64820. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  64821. context.fillRect(x, y, 1, 1);
  64822. }
  64823. }
  64824. this._randomTexture.update(false);
  64825. };
  64826. __decorate([
  64827. BABYLON.serialize()
  64828. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  64829. __decorate([
  64830. BABYLON.serialize()
  64831. ], SSAORenderingPipeline.prototype, "radius", void 0);
  64832. __decorate([
  64833. BABYLON.serialize()
  64834. ], SSAORenderingPipeline.prototype, "area", void 0);
  64835. __decorate([
  64836. BABYLON.serialize()
  64837. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  64838. __decorate([
  64839. BABYLON.serialize()
  64840. ], SSAORenderingPipeline.prototype, "base", void 0);
  64841. return SSAORenderingPipeline;
  64842. }(BABYLON.PostProcessRenderPipeline));
  64843. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  64844. })(BABYLON || (BABYLON = {}));
  64845. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  64846. var BABYLON;
  64847. (function (BABYLON) {
  64848. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  64849. __extends(SSAO2RenderingPipeline, _super);
  64850. /**
  64851. * @constructor
  64852. * @param {string} name - The rendering pipeline name
  64853. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  64854. * @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 }
  64855. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  64856. */
  64857. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  64858. var _this = _super.call(this, scene.getEngine(), name) || this;
  64859. // Members
  64860. /**
  64861. * The PassPostProcess id in the pipeline that contains the original scene color
  64862. * @type {string}
  64863. */
  64864. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  64865. /**
  64866. * The SSAO PostProcess id in the pipeline
  64867. * @type {string}
  64868. */
  64869. _this.SSAORenderEffect = "SSAORenderEffect";
  64870. /**
  64871. * The horizontal blur PostProcess id in the pipeline
  64872. * @type {string}
  64873. */
  64874. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  64875. /**
  64876. * The vertical blur PostProcess id in the pipeline
  64877. * @type {string}
  64878. */
  64879. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  64880. /**
  64881. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  64882. * @type {string}
  64883. */
  64884. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  64885. /**
  64886. * The output strength of the SSAO post-process. Default value is 1.0.
  64887. * @type {number}
  64888. */
  64889. _this.totalStrength = 1.0;
  64890. /**
  64891. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  64892. * @type {number}
  64893. */
  64894. _this.maxZ = 100.0;
  64895. /**
  64896. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  64897. * @type {number}
  64898. */
  64899. _this.minZAspect = 0.2;
  64900. /**
  64901. * Number of samples used for the SSAO calculations. Default value is 8
  64902. * @type {number}
  64903. */
  64904. _this._samples = 8;
  64905. /**
  64906. * Are we using bilateral blur ?
  64907. * @type {boolean}
  64908. */
  64909. _this._expensiveBlur = true;
  64910. /**
  64911. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  64912. * @type {number}
  64913. */
  64914. _this.radius = 2.0;
  64915. /**
  64916. * The base color of the SSAO post-process
  64917. * The final result is "base + ssao" between [0, 1]
  64918. * @type {number}
  64919. */
  64920. _this.base = 0.1;
  64921. _this._firstUpdate = true;
  64922. _this._scene = scene;
  64923. if (!_this.isSupported) {
  64924. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  64925. return _this;
  64926. }
  64927. var ssaoRatio = ratio.ssaoRatio || ratio;
  64928. var blurRatio = ratio.blurRatio || ratio;
  64929. // Set up assets
  64930. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  64931. _this._createRandomTexture();
  64932. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  64933. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  64934. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  64935. _this._createSSAOPostProcess(1.0);
  64936. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  64937. _this._createSSAOCombinePostProcess(blurRatio);
  64938. // Set up pipeline
  64939. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  64940. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  64941. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  64942. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  64943. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  64944. // Finish
  64945. scene.postProcessRenderPipelineManager.addPipeline(_this);
  64946. if (cameras)
  64947. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  64948. return _this;
  64949. }
  64950. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  64951. get: function () {
  64952. return this._samples;
  64953. },
  64954. set: function (n) {
  64955. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  64956. this._samples = n;
  64957. this._sampleSphere = this._generateHemisphere();
  64958. this._firstUpdate = true;
  64959. },
  64960. enumerable: true,
  64961. configurable: true
  64962. });
  64963. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  64964. get: function () {
  64965. return this._expensiveBlur;
  64966. },
  64967. set: function (b) {
  64968. 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"]);
  64969. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  64970. this._expensiveBlur = b;
  64971. this._firstUpdate = true;
  64972. },
  64973. enumerable: true,
  64974. configurable: true
  64975. });
  64976. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  64977. /**
  64978. * Support test.
  64979. * @type {boolean}
  64980. */
  64981. get: function () {
  64982. var engine = BABYLON.Engine.LastCreatedEngine;
  64983. if (!engine) {
  64984. return false;
  64985. }
  64986. return engine.getCaps().drawBuffersExtension;
  64987. },
  64988. enumerable: true,
  64989. configurable: true
  64990. });
  64991. // Public Methods
  64992. /**
  64993. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  64994. */
  64995. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  64996. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  64997. for (var i = 0; i < this._scene.cameras.length; i++) {
  64998. var camera = this._scene.cameras[i];
  64999. this._originalColorPostProcess.dispose(camera);
  65000. this._ssaoPostProcess.dispose(camera);
  65001. this._blurHPostProcess.dispose(camera);
  65002. this._blurVPostProcess.dispose(camera);
  65003. this._ssaoCombinePostProcess.dispose(camera);
  65004. }
  65005. this._randomTexture.dispose();
  65006. if (disableGeometryBufferRenderer)
  65007. this._scene.disableGeometryBufferRenderer();
  65008. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  65009. _super.prototype.dispose.call(this);
  65010. };
  65011. // Private Methods
  65012. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  65013. var _this = this;
  65014. this._samplerOffsets = [];
  65015. var expensive = this.expensiveBlur;
  65016. for (var i = -8; i < 8; i++) {
  65017. this._samplerOffsets.push(i * 2 + 0.5);
  65018. }
  65019. 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");
  65020. this._blurHPostProcess.onApply = function (effect) {
  65021. if (!_this._scene.activeCamera) {
  65022. return;
  65023. }
  65024. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  65025. effect.setFloat("near", _this._scene.activeCamera.minZ);
  65026. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  65027. effect.setFloat("radius", _this.radius);
  65028. effect.setTexture("depthSampler", _this._depthTexture);
  65029. if (_this._firstUpdate) {
  65030. effect.setArray("samplerOffsets", _this._samplerOffsets);
  65031. }
  65032. };
  65033. 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");
  65034. this._blurVPostProcess.onApply = function (effect) {
  65035. if (!_this._scene.activeCamera) {
  65036. return;
  65037. }
  65038. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  65039. effect.setFloat("near", _this._scene.activeCamera.minZ);
  65040. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  65041. effect.setFloat("radius", _this.radius);
  65042. effect.setTexture("depthSampler", _this._depthTexture);
  65043. if (_this._firstUpdate) {
  65044. effect.setArray("samplerOffsets", _this._samplerOffsets);
  65045. _this._firstUpdate = false;
  65046. }
  65047. };
  65048. };
  65049. SSAO2RenderingPipeline.prototype._rebuild = function () {
  65050. this._firstUpdate = true;
  65051. _super.prototype._rebuild.call(this);
  65052. };
  65053. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  65054. var numSamples = this.samples;
  65055. var result = [];
  65056. var vector, scale;
  65057. var rand = function (min, max) {
  65058. return Math.random() * (max - min) + min;
  65059. };
  65060. var i = 0;
  65061. while (i < numSamples) {
  65062. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  65063. vector.normalize();
  65064. scale = i / numSamples;
  65065. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  65066. vector.scaleInPlace(scale);
  65067. result.push(vector.x, vector.y, vector.z);
  65068. i++;
  65069. }
  65070. return result;
  65071. };
  65072. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  65073. var _this = this;
  65074. var numSamples = this.samples;
  65075. this._sampleSphere = this._generateHemisphere();
  65076. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  65077. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  65078. "base", "range", "projection", "near", "far", "texelSize",
  65079. "xViewport", "yViewport", "maxZ", "minZAspect"
  65080. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  65081. this._ssaoPostProcess.onApply = function (effect) {
  65082. if (_this._firstUpdate) {
  65083. effect.setArray3("sampleSphere", _this._sampleSphere);
  65084. effect.setFloat("randTextureTiles", 4.0);
  65085. }
  65086. if (!_this._scene.activeCamera) {
  65087. return;
  65088. }
  65089. effect.setFloat("samplesFactor", 1 / _this.samples);
  65090. effect.setFloat("totalStrength", _this.totalStrength);
  65091. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  65092. effect.setFloat("radius", _this.radius);
  65093. effect.setFloat("maxZ", _this.maxZ);
  65094. effect.setFloat("minZAspect", _this.minZAspect);
  65095. effect.setFloat("base", _this.base);
  65096. effect.setFloat("near", _this._scene.activeCamera.minZ);
  65097. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  65098. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  65099. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  65100. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  65101. effect.setTexture("textureSampler", _this._depthTexture);
  65102. effect.setTexture("normalSampler", _this._normalTexture);
  65103. effect.setTexture("randomSampler", _this._randomTexture);
  65104. };
  65105. };
  65106. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  65107. var _this = this;
  65108. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  65109. this._ssaoCombinePostProcess.onApply = function (effect) {
  65110. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  65111. };
  65112. };
  65113. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  65114. var size = 512;
  65115. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  65116. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  65117. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  65118. var context = this._randomTexture.getContext();
  65119. var rand = function (min, max) {
  65120. return Math.random() * (max - min) + min;
  65121. };
  65122. var randVector = BABYLON.Vector3.Zero();
  65123. for (var x = 0; x < size; x++) {
  65124. for (var y = 0; y < size; y++) {
  65125. randVector.x = rand(0.0, 1.0);
  65126. randVector.y = rand(0.0, 1.0);
  65127. randVector.z = 0.0;
  65128. randVector.normalize();
  65129. randVector.scaleInPlace(255);
  65130. randVector.x = Math.floor(randVector.x);
  65131. randVector.y = Math.floor(randVector.y);
  65132. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  65133. context.fillRect(x, y, 1, 1);
  65134. }
  65135. }
  65136. this._randomTexture.update(false);
  65137. };
  65138. __decorate([
  65139. BABYLON.serialize()
  65140. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  65141. __decorate([
  65142. BABYLON.serialize()
  65143. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  65144. __decorate([
  65145. BABYLON.serialize()
  65146. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  65147. __decorate([
  65148. BABYLON.serialize("samples")
  65149. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  65150. __decorate([
  65151. BABYLON.serialize("expensiveBlur")
  65152. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  65153. __decorate([
  65154. BABYLON.serialize()
  65155. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  65156. __decorate([
  65157. BABYLON.serialize()
  65158. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  65159. return SSAO2RenderingPipeline;
  65160. }(BABYLON.PostProcessRenderPipeline));
  65161. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  65162. })(BABYLON || (BABYLON = {}));
  65163. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  65164. // BABYLON.JS Chromatic Aberration GLSL Shader
  65165. // Author: Olivier Guyot
  65166. // Separates very slightly R, G and B colors on the edges of the screen
  65167. // Inspired by Francois Tarlier & Martins Upitis
  65168. var BABYLON;
  65169. (function (BABYLON) {
  65170. var LensRenderingPipeline = /** @class */ (function (_super) {
  65171. __extends(LensRenderingPipeline, _super);
  65172. /**
  65173. * @constructor
  65174. *
  65175. * Effect parameters are as follow:
  65176. * {
  65177. * chromatic_aberration: number; // from 0 to x (1 for realism)
  65178. * edge_blur: number; // from 0 to x (1 for realism)
  65179. * distortion: number; // from 0 to x (1 for realism)
  65180. * grain_amount: number; // from 0 to 1
  65181. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  65182. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  65183. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  65184. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  65185. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  65186. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  65187. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  65188. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  65189. * }
  65190. * Note: if an effect parameter is unset, effect is disabled
  65191. *
  65192. * @param {string} name - The rendering pipeline name
  65193. * @param {object} parameters - An object containing all parameters (see above)
  65194. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  65195. * @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)
  65196. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  65197. */
  65198. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  65199. if (ratio === void 0) { ratio = 1.0; }
  65200. var _this = _super.call(this, scene.getEngine(), name) || this;
  65201. // Lens effects can be of the following:
  65202. // - chromatic aberration (slight shift of RGB colors)
  65203. // - blur on the edge of the lens
  65204. // - lens distortion
  65205. // - depth-of-field blur & highlights enhancing
  65206. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  65207. // - grain effect (noise or custom texture)
  65208. // Two additional texture samplers are needed:
  65209. // - depth map (for depth-of-field)
  65210. // - grain texture
  65211. /**
  65212. * The chromatic aberration PostProcess id in the pipeline
  65213. * @type {string}
  65214. */
  65215. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  65216. /**
  65217. * The highlights enhancing PostProcess id in the pipeline
  65218. * @type {string}
  65219. */
  65220. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  65221. /**
  65222. * The depth-of-field PostProcess id in the pipeline
  65223. * @type {string}
  65224. */
  65225. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  65226. _this._scene = scene;
  65227. // Fetch texture samplers
  65228. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  65229. if (parameters.grain_texture) {
  65230. _this._grainTexture = parameters.grain_texture;
  65231. }
  65232. else {
  65233. _this._createGrainTexture();
  65234. }
  65235. // save parameters
  65236. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  65237. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  65238. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  65239. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  65240. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  65241. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  65242. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  65243. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  65244. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  65245. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  65246. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  65247. // Create effects
  65248. _this._createChromaticAberrationPostProcess(ratio);
  65249. _this._createHighlightsPostProcess(ratio);
  65250. _this._createDepthOfFieldPostProcess(ratio / 4);
  65251. // Set up pipeline
  65252. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  65253. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  65254. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  65255. if (_this._highlightsGain === -1) {
  65256. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  65257. }
  65258. // Finish
  65259. scene.postProcessRenderPipelineManager.addPipeline(_this);
  65260. if (cameras) {
  65261. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  65262. }
  65263. return _this;
  65264. }
  65265. // public methods (self explanatory)
  65266. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  65267. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  65268. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  65269. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  65270. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  65271. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  65272. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  65273. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  65274. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  65275. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  65276. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  65277. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  65278. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  65279. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  65280. };
  65281. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  65282. this._highlightsPostProcess.updateEffect();
  65283. };
  65284. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  65285. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  65286. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  65287. this._highlightsGain = amount;
  65288. };
  65289. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  65290. if (this._highlightsGain === -1) {
  65291. this._highlightsGain = 1.0;
  65292. }
  65293. this._highlightsThreshold = amount;
  65294. };
  65295. LensRenderingPipeline.prototype.disableHighlights = function () {
  65296. this._highlightsGain = -1;
  65297. };
  65298. /**
  65299. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  65300. */
  65301. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  65302. if (disableDepthRender === void 0) { disableDepthRender = false; }
  65303. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  65304. this._chromaticAberrationPostProcess = null;
  65305. this._highlightsPostProcess = null;
  65306. this._depthOfFieldPostProcess = null;
  65307. this._grainTexture.dispose();
  65308. if (disableDepthRender)
  65309. this._scene.disableDepthRenderer();
  65310. };
  65311. // colors shifting and distortion
  65312. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  65313. var _this = this;
  65314. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  65315. [], // samplers
  65316. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  65317. this._chromaticAberrationPostProcess.onApply = function (effect) {
  65318. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  65319. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  65320. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  65321. };
  65322. };
  65323. // highlights enhancing
  65324. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  65325. var _this = this;
  65326. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  65327. [], // samplers
  65328. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  65329. this._highlightsPostProcess.onApply = function (effect) {
  65330. effect.setFloat('gain', _this._highlightsGain);
  65331. effect.setFloat('threshold', _this._highlightsThreshold);
  65332. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  65333. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  65334. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  65335. };
  65336. };
  65337. // colors shifting and distortion
  65338. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  65339. var _this = this;
  65340. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  65341. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  65342. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  65343. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  65344. this._depthOfFieldPostProcess.onApply = function (effect) {
  65345. effect.setTexture("depthSampler", _this._depthTexture);
  65346. effect.setTexture("grainSampler", _this._grainTexture);
  65347. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  65348. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  65349. effect.setFloat('grain_amount', _this._grainAmount);
  65350. effect.setBool('blur_noise', _this._blurNoise);
  65351. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  65352. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  65353. effect.setFloat('distortion', _this._distortion);
  65354. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  65355. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  65356. effect.setFloat('aperture', _this._dofAperture);
  65357. effect.setFloat('darken', _this._dofDarken);
  65358. effect.setFloat('edge_blur', _this._edgeBlur);
  65359. effect.setBool('highlights', (_this._highlightsGain !== -1));
  65360. if (_this._scene.activeCamera) {
  65361. effect.setFloat('near', _this._scene.activeCamera.minZ);
  65362. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  65363. }
  65364. };
  65365. };
  65366. // creates a black and white random noise texture, 512x512
  65367. LensRenderingPipeline.prototype._createGrainTexture = function () {
  65368. var size = 512;
  65369. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  65370. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  65371. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  65372. var context = this._grainTexture.getContext();
  65373. var rand = function (min, max) {
  65374. return Math.random() * (max - min) + min;
  65375. };
  65376. var value;
  65377. for (var x = 0; x < size; x++) {
  65378. for (var y = 0; y < size; y++) {
  65379. value = Math.floor(rand(0.42, 0.58) * 255);
  65380. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  65381. context.fillRect(x, y, 1, 1);
  65382. }
  65383. }
  65384. this._grainTexture.update(false);
  65385. };
  65386. return LensRenderingPipeline;
  65387. }(BABYLON.PostProcessRenderPipeline));
  65388. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  65389. })(BABYLON || (BABYLON = {}));
  65390. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  65391. var BABYLON;
  65392. (function (BABYLON) {
  65393. var StandardRenderingPipeline = /** @class */ (function (_super) {
  65394. __extends(StandardRenderingPipeline, _super);
  65395. /**
  65396. * @constructor
  65397. * @param {string} name - The rendering pipeline name
  65398. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  65399. * @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)
  65400. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  65401. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  65402. */
  65403. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  65404. if (originalPostProcess === void 0) { originalPostProcess = null; }
  65405. var _this = _super.call(this, scene.getEngine(), name) || this;
  65406. _this.downSampleX4PostProcess = null;
  65407. _this.brightPassPostProcess = null;
  65408. _this.blurHPostProcesses = [];
  65409. _this.blurVPostProcesses = [];
  65410. _this.textureAdderPostProcess = null;
  65411. _this.volumetricLightPostProcess = null;
  65412. _this.volumetricLightSmoothXPostProcess = null;
  65413. _this.volumetricLightSmoothYPostProcess = null;
  65414. _this.volumetricLightMergePostProces = null;
  65415. _this.volumetricLightFinalPostProcess = null;
  65416. _this.luminancePostProcess = null;
  65417. _this.luminanceDownSamplePostProcesses = [];
  65418. _this.hdrPostProcess = null;
  65419. _this.textureAdderFinalPostProcess = null;
  65420. _this.lensFlareFinalPostProcess = null;
  65421. _this.hdrFinalPostProcess = null;
  65422. _this.lensFlarePostProcess = null;
  65423. _this.lensFlareComposePostProcess = null;
  65424. _this.motionBlurPostProcess = null;
  65425. _this.depthOfFieldPostProcess = null;
  65426. // Values
  65427. _this.brightThreshold = 1.0;
  65428. _this.blurWidth = 512.0;
  65429. _this.horizontalBlur = false;
  65430. _this.exposure = 1.0;
  65431. _this.lensTexture = null;
  65432. _this.volumetricLightCoefficient = 0.2;
  65433. _this.volumetricLightPower = 4.0;
  65434. _this.volumetricLightBlurScale = 64.0;
  65435. _this.sourceLight = null;
  65436. _this.hdrMinimumLuminance = 1.0;
  65437. _this.hdrDecreaseRate = 0.5;
  65438. _this.hdrIncreaseRate = 0.5;
  65439. _this.lensColorTexture = null;
  65440. _this.lensFlareStrength = 20.0;
  65441. _this.lensFlareGhostDispersal = 1.4;
  65442. _this.lensFlareHaloWidth = 0.7;
  65443. _this.lensFlareDistortionStrength = 16.0;
  65444. _this.lensStarTexture = null;
  65445. _this.lensFlareDirtTexture = null;
  65446. _this.depthOfFieldDistance = 10.0;
  65447. _this.depthOfFieldBlurWidth = 64.0;
  65448. _this.motionStrength = 1.0;
  65449. // IAnimatable
  65450. _this.animations = [];
  65451. _this._currentDepthOfFieldSource = null;
  65452. _this._hdrCurrentLuminance = 1.0;
  65453. // Getters and setters
  65454. _this._bloomEnabled = true;
  65455. _this._depthOfFieldEnabled = false;
  65456. _this._vlsEnabled = false;
  65457. _this._lensFlareEnabled = false;
  65458. _this._hdrEnabled = false;
  65459. _this._motionBlurEnabled = false;
  65460. _this._motionBlurSamples = 64.0;
  65461. _this._volumetricLightStepsCount = 50.0;
  65462. _this._cameras = cameras || [];
  65463. // Initialize
  65464. _this._scene = scene;
  65465. _this._basePostProcess = originalPostProcess;
  65466. _this._ratio = ratio;
  65467. // Misc
  65468. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  65469. // Finish
  65470. scene.postProcessRenderPipelineManager.addPipeline(_this);
  65471. _this._buildPipeline();
  65472. return _this;
  65473. }
  65474. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  65475. get: function () {
  65476. return this._bloomEnabled;
  65477. },
  65478. set: function (enabled) {
  65479. if (this._bloomEnabled === enabled) {
  65480. return;
  65481. }
  65482. this._bloomEnabled = enabled;
  65483. this._buildPipeline();
  65484. },
  65485. enumerable: true,
  65486. configurable: true
  65487. });
  65488. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  65489. get: function () {
  65490. return this._depthOfFieldEnabled;
  65491. },
  65492. set: function (enabled) {
  65493. if (this._depthOfFieldEnabled === enabled) {
  65494. return;
  65495. }
  65496. this._depthOfFieldEnabled = enabled;
  65497. this._buildPipeline();
  65498. },
  65499. enumerable: true,
  65500. configurable: true
  65501. });
  65502. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  65503. get: function () {
  65504. return this._lensFlareEnabled;
  65505. },
  65506. set: function (enabled) {
  65507. if (this._lensFlareEnabled === enabled) {
  65508. return;
  65509. }
  65510. this._lensFlareEnabled = enabled;
  65511. this._buildPipeline();
  65512. },
  65513. enumerable: true,
  65514. configurable: true
  65515. });
  65516. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  65517. get: function () {
  65518. return this._hdrEnabled;
  65519. },
  65520. set: function (enabled) {
  65521. if (this._hdrEnabled === enabled) {
  65522. return;
  65523. }
  65524. this._hdrEnabled = enabled;
  65525. this._buildPipeline();
  65526. },
  65527. enumerable: true,
  65528. configurable: true
  65529. });
  65530. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  65531. get: function () {
  65532. return this._vlsEnabled;
  65533. },
  65534. set: function (enabled) {
  65535. if (this._vlsEnabled === enabled) {
  65536. return;
  65537. }
  65538. if (enabled) {
  65539. var geometry = this._scene.enableGeometryBufferRenderer();
  65540. if (!geometry) {
  65541. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  65542. return;
  65543. }
  65544. }
  65545. this._vlsEnabled = enabled;
  65546. this._buildPipeline();
  65547. },
  65548. enumerable: true,
  65549. configurable: true
  65550. });
  65551. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  65552. get: function () {
  65553. return this._motionBlurEnabled;
  65554. },
  65555. set: function (enabled) {
  65556. if (this._motionBlurEnabled === enabled) {
  65557. return;
  65558. }
  65559. this._motionBlurEnabled = enabled;
  65560. this._buildPipeline();
  65561. },
  65562. enumerable: true,
  65563. configurable: true
  65564. });
  65565. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  65566. get: function () {
  65567. return this._volumetricLightStepsCount;
  65568. },
  65569. set: function (count) {
  65570. if (this.volumetricLightPostProcess) {
  65571. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  65572. }
  65573. this._volumetricLightStepsCount = count;
  65574. },
  65575. enumerable: true,
  65576. configurable: true
  65577. });
  65578. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  65579. get: function () {
  65580. return this._motionBlurSamples;
  65581. },
  65582. set: function (samples) {
  65583. if (this.motionBlurPostProcess) {
  65584. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  65585. }
  65586. this._motionBlurSamples = samples;
  65587. },
  65588. enumerable: true,
  65589. configurable: true
  65590. });
  65591. StandardRenderingPipeline.prototype._buildPipeline = function () {
  65592. var _this = this;
  65593. var ratio = this._ratio;
  65594. var scene = this._scene;
  65595. this._disposePostProcesses();
  65596. this._reset();
  65597. // Create pass post-process
  65598. if (!this._basePostProcess) {
  65599. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  65600. this.originalPostProcess.onApply = function (effect) {
  65601. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  65602. };
  65603. }
  65604. else {
  65605. this.originalPostProcess = this._basePostProcess;
  65606. }
  65607. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  65608. this._currentDepthOfFieldSource = this.originalPostProcess;
  65609. if (this._vlsEnabled) {
  65610. // Create volumetric light
  65611. this._createVolumetricLightPostProcess(scene, ratio);
  65612. // Create volumetric light final post-process
  65613. 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);
  65614. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  65615. }
  65616. if (this._bloomEnabled) {
  65617. // Create down sample X4 post-process
  65618. this._createDownSampleX4PostProcess(scene, ratio / 2);
  65619. // Create bright pass post-process
  65620. this._createBrightPassPostProcess(scene, ratio / 2);
  65621. // Create gaussian blur post-processes (down sampling blurs)
  65622. this._createBlurPostProcesses(scene, ratio / 4, 1);
  65623. // Create texture adder post-process
  65624. this._createTextureAdderPostProcess(scene, ratio);
  65625. // Create depth-of-field source post-process
  65626. 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);
  65627. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  65628. }
  65629. if (this._lensFlareEnabled) {
  65630. // Create lens flare post-process
  65631. this._createLensFlarePostProcess(scene, ratio);
  65632. // Create depth-of-field source post-process post lens-flare and disable it now
  65633. 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);
  65634. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  65635. }
  65636. if (this._hdrEnabled) {
  65637. // Create luminance
  65638. this._createLuminancePostProcesses(scene, this._floatTextureType);
  65639. // Create HDR
  65640. this._createHdrPostProcess(scene, ratio);
  65641. // Create depth-of-field source post-process post hdr and disable it now
  65642. 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);
  65643. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  65644. }
  65645. if (this._depthOfFieldEnabled) {
  65646. // Create gaussian blur used by depth-of-field
  65647. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  65648. // Create depth-of-field post-process
  65649. this._createDepthOfFieldPostProcess(scene, ratio);
  65650. }
  65651. if (this._motionBlurEnabled) {
  65652. // Create motion blur post-process
  65653. this._createMotionBlurPostProcess(scene, ratio);
  65654. }
  65655. if (this._cameras !== null) {
  65656. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  65657. }
  65658. };
  65659. // Down Sample X4 Post-Processs
  65660. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  65661. var _this = this;
  65662. var downSampleX4Offsets = new Array(32);
  65663. 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);
  65664. this.downSampleX4PostProcess.onApply = function (effect) {
  65665. var id = 0;
  65666. var width = _this.downSampleX4PostProcess.width;
  65667. var height = _this.downSampleX4PostProcess.height;
  65668. for (var i = -2; i < 2; i++) {
  65669. for (var j = -2; j < 2; j++) {
  65670. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  65671. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  65672. id += 2;
  65673. }
  65674. }
  65675. effect.setArray2("dsOffsets", downSampleX4Offsets);
  65676. };
  65677. // Add to pipeline
  65678. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  65679. };
  65680. // Brightpass Post-Process
  65681. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  65682. var _this = this;
  65683. var brightOffsets = new Array(8);
  65684. 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);
  65685. this.brightPassPostProcess.onApply = function (effect) {
  65686. var sU = (1.0 / _this.brightPassPostProcess.width);
  65687. var sV = (1.0 / _this.brightPassPostProcess.height);
  65688. brightOffsets[0] = -0.5 * sU;
  65689. brightOffsets[1] = 0.5 * sV;
  65690. brightOffsets[2] = 0.5 * sU;
  65691. brightOffsets[3] = 0.5 * sV;
  65692. brightOffsets[4] = -0.5 * sU;
  65693. brightOffsets[5] = -0.5 * sV;
  65694. brightOffsets[6] = 0.5 * sU;
  65695. brightOffsets[7] = -0.5 * sV;
  65696. effect.setArray2("dsOffsets", brightOffsets);
  65697. effect.setFloat("brightThreshold", _this.brightThreshold);
  65698. };
  65699. // Add to pipeline
  65700. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  65701. };
  65702. // Create blur H&V post-processes
  65703. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  65704. var _this = this;
  65705. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  65706. var engine = scene.getEngine();
  65707. 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);
  65708. 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);
  65709. blurX.onActivateObservable.add(function () {
  65710. var dw = blurX.width / engine.getRenderWidth();
  65711. blurX.kernel = _this[blurWidthKey] * dw;
  65712. });
  65713. blurY.onActivateObservable.add(function () {
  65714. var dw = blurY.height / engine.getRenderHeight();
  65715. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  65716. });
  65717. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  65718. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  65719. this.blurHPostProcesses.push(blurX);
  65720. this.blurVPostProcesses.push(blurY);
  65721. };
  65722. // Create texture adder post-process
  65723. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  65724. var _this = this;
  65725. 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);
  65726. this.textureAdderPostProcess.onApply = function (effect) {
  65727. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  65728. effect.setTexture("lensSampler", _this.lensTexture);
  65729. effect.setFloat("exposure", _this.exposure);
  65730. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  65731. };
  65732. // Add to pipeline
  65733. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  65734. };
  65735. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  65736. var _this = this;
  65737. var geometryRenderer = scene.enableGeometryBufferRenderer();
  65738. geometryRenderer.enablePosition = true;
  65739. var geometry = geometryRenderer.getGBuffer();
  65740. // Base post-process
  65741. 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));
  65742. var depthValues = BABYLON.Vector2.Zero();
  65743. this.volumetricLightPostProcess.onApply = function (effect) {
  65744. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  65745. var generator = _this.sourceLight.getShadowGenerator();
  65746. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  65747. effect.setTexture("positionSampler", geometry.textures[2]);
  65748. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  65749. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  65750. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  65751. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  65752. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  65753. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  65754. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  65755. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  65756. effect.setVector2("depthValues", depthValues);
  65757. }
  65758. };
  65759. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  65760. // Smooth
  65761. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  65762. // Merge
  65763. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  65764. this.volumetricLightMergePostProces.onApply = function (effect) {
  65765. effect.setTextureFromPostProcess("originalSampler", _this.originalPostProcess);
  65766. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  65767. };
  65768. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  65769. };
  65770. // Create luminance
  65771. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  65772. var _this = this;
  65773. // Create luminance
  65774. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  65775. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  65776. var offsets = [];
  65777. this.luminancePostProcess.onApply = function (effect) {
  65778. var sU = (1.0 / _this.luminancePostProcess.width);
  65779. var sV = (1.0 / _this.luminancePostProcess.height);
  65780. offsets[0] = -0.5 * sU;
  65781. offsets[1] = 0.5 * sV;
  65782. offsets[2] = 0.5 * sU;
  65783. offsets[3] = 0.5 * sV;
  65784. offsets[4] = -0.5 * sU;
  65785. offsets[5] = -0.5 * sV;
  65786. offsets[6] = 0.5 * sU;
  65787. offsets[7] = -0.5 * sV;
  65788. effect.setArray2("lumOffsets", offsets);
  65789. };
  65790. // Add to pipeline
  65791. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  65792. // Create down sample luminance
  65793. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  65794. var size = Math.pow(3, i);
  65795. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  65796. if (i === 0) {
  65797. defines += "#define FINAL_DOWN_SAMPLER";
  65798. }
  65799. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  65800. this.luminanceDownSamplePostProcesses.push(postProcess);
  65801. }
  65802. // Create callbacks and add effects
  65803. var lastLuminance = this.luminancePostProcess;
  65804. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  65805. var downSampleOffsets = new Array(18);
  65806. pp.onApply = function (effect) {
  65807. if (!lastLuminance) {
  65808. return;
  65809. }
  65810. var id = 0;
  65811. for (var x = -1; x < 2; x++) {
  65812. for (var y = -1; y < 2; y++) {
  65813. downSampleOffsets[id] = x / lastLuminance.width;
  65814. downSampleOffsets[id + 1] = y / lastLuminance.height;
  65815. id += 2;
  65816. }
  65817. }
  65818. effect.setArray2("dsOffsets", downSampleOffsets);
  65819. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  65820. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  65821. lastLuminance = _this.luminancePostProcess;
  65822. }
  65823. else {
  65824. lastLuminance = pp;
  65825. }
  65826. };
  65827. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  65828. pp.onAfterRender = function (effect) {
  65829. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  65830. 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);
  65831. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  65832. };
  65833. }
  65834. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  65835. });
  65836. };
  65837. // Create HDR post-process
  65838. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  65839. var _this = this;
  65840. 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);
  65841. var outputLiminance = 1;
  65842. var time = 0;
  65843. var lastTime = 0;
  65844. this.hdrPostProcess.onApply = function (effect) {
  65845. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  65846. time += scene.getEngine().getDeltaTime();
  65847. if (outputLiminance < 0) {
  65848. outputLiminance = _this._hdrCurrentLuminance;
  65849. }
  65850. else {
  65851. var dt = (lastTime - time) / 1000.0;
  65852. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  65853. outputLiminance += _this.hdrDecreaseRate * dt;
  65854. }
  65855. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  65856. outputLiminance -= _this.hdrIncreaseRate * dt;
  65857. }
  65858. else {
  65859. outputLiminance = _this._hdrCurrentLuminance;
  65860. }
  65861. }
  65862. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  65863. effect.setFloat("averageLuminance", outputLiminance);
  65864. lastTime = time;
  65865. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  65866. };
  65867. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  65868. };
  65869. // Create lens flare post-process
  65870. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  65871. var _this = this;
  65872. 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);
  65873. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  65874. this._createBlurPostProcesses(scene, ratio / 4, 2);
  65875. 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);
  65876. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  65877. var resolution = new BABYLON.Vector2(0, 0);
  65878. // Lens flare
  65879. this.lensFlarePostProcess.onApply = function (effect) {
  65880. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  65881. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  65882. effect.setFloat("strength", _this.lensFlareStrength);
  65883. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  65884. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  65885. // Shift
  65886. resolution.x = _this.lensFlarePostProcess.width;
  65887. resolution.y = _this.lensFlarePostProcess.height;
  65888. effect.setVector2("resolution", resolution);
  65889. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  65890. };
  65891. // Compose
  65892. 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);
  65893. 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);
  65894. this.lensFlareComposePostProcess.onApply = function (effect) {
  65895. if (!_this._scene.activeCamera) {
  65896. return;
  65897. }
  65898. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  65899. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  65900. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  65901. // Lens start rotation matrix
  65902. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  65903. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  65904. 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));
  65905. camRot *= 4.0;
  65906. 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);
  65907. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  65908. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  65909. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  65910. };
  65911. };
  65912. // Create depth-of-field post-process
  65913. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  65914. var _this = this;
  65915. 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);
  65916. this.depthOfFieldPostProcess.onApply = function (effect) {
  65917. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  65918. effect.setTexture("depthSampler", _this._getDepthTexture());
  65919. effect.setFloat("distance", _this.depthOfFieldDistance);
  65920. };
  65921. // Add to pipeline
  65922. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  65923. };
  65924. // Create motion blur post-process
  65925. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  65926. var _this = this;
  65927. 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);
  65928. var motionScale = 0;
  65929. var prevViewProjection = BABYLON.Matrix.Identity();
  65930. var invViewProjection = BABYLON.Matrix.Identity();
  65931. var viewProjection = BABYLON.Matrix.Identity();
  65932. var screenSize = BABYLON.Vector2.Zero();
  65933. this.motionBlurPostProcess.onApply = function (effect) {
  65934. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  65935. viewProjection.invertToRef(invViewProjection);
  65936. effect.setMatrix("inverseViewProjection", invViewProjection);
  65937. effect.setMatrix("prevViewProjection", prevViewProjection);
  65938. prevViewProjection = viewProjection;
  65939. screenSize.x = _this.motionBlurPostProcess.width;
  65940. screenSize.y = _this.motionBlurPostProcess.height;
  65941. effect.setVector2("screenSize", screenSize);
  65942. motionScale = scene.getEngine().getFps() / 60.0;
  65943. effect.setFloat("motionScale", motionScale);
  65944. effect.setFloat("motionStrength", _this.motionStrength);
  65945. effect.setTexture("depthSampler", _this._getDepthTexture());
  65946. };
  65947. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  65948. };
  65949. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  65950. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  65951. var renderer = this._scene.enableGeometryBufferRenderer();
  65952. return renderer.getGBuffer().textures[0];
  65953. }
  65954. return this._scene.enableDepthRenderer().getDepthMap();
  65955. };
  65956. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  65957. for (var i = 0; i < this._cameras.length; i++) {
  65958. var camera = this._cameras[i];
  65959. if (this.originalPostProcess) {
  65960. this.originalPostProcess.dispose(camera);
  65961. }
  65962. if (this.downSampleX4PostProcess) {
  65963. this.downSampleX4PostProcess.dispose(camera);
  65964. }
  65965. if (this.brightPassPostProcess) {
  65966. this.brightPassPostProcess.dispose(camera);
  65967. }
  65968. if (this.textureAdderPostProcess) {
  65969. this.textureAdderPostProcess.dispose(camera);
  65970. }
  65971. if (this.textureAdderFinalPostProcess) {
  65972. this.textureAdderFinalPostProcess.dispose(camera);
  65973. }
  65974. if (this.volumetricLightPostProcess) {
  65975. this.volumetricLightPostProcess.dispose(camera);
  65976. }
  65977. if (this.volumetricLightSmoothXPostProcess) {
  65978. this.volumetricLightSmoothXPostProcess.dispose(camera);
  65979. }
  65980. if (this.volumetricLightSmoothYPostProcess) {
  65981. this.volumetricLightSmoothYPostProcess.dispose(camera);
  65982. }
  65983. if (this.volumetricLightMergePostProces) {
  65984. this.volumetricLightMergePostProces.dispose(camera);
  65985. }
  65986. if (this.volumetricLightFinalPostProcess) {
  65987. this.volumetricLightFinalPostProcess.dispose(camera);
  65988. }
  65989. if (this.lensFlarePostProcess) {
  65990. this.lensFlarePostProcess.dispose(camera);
  65991. }
  65992. if (this.lensFlareComposePostProcess) {
  65993. this.lensFlareComposePostProcess.dispose(camera);
  65994. }
  65995. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  65996. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  65997. }
  65998. if (this.luminancePostProcess) {
  65999. this.luminancePostProcess.dispose(camera);
  66000. }
  66001. if (this.hdrPostProcess) {
  66002. this.hdrPostProcess.dispose(camera);
  66003. }
  66004. if (this.hdrFinalPostProcess) {
  66005. this.hdrFinalPostProcess.dispose(camera);
  66006. }
  66007. if (this.depthOfFieldPostProcess) {
  66008. this.depthOfFieldPostProcess.dispose(camera);
  66009. }
  66010. if (this.motionBlurPostProcess) {
  66011. this.motionBlurPostProcess.dispose(camera);
  66012. }
  66013. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  66014. this.blurHPostProcesses[j].dispose(camera);
  66015. }
  66016. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  66017. this.blurVPostProcesses[j].dispose(camera);
  66018. }
  66019. }
  66020. this.originalPostProcess = null;
  66021. this.downSampleX4PostProcess = null;
  66022. this.brightPassPostProcess = null;
  66023. this.textureAdderPostProcess = null;
  66024. this.textureAdderFinalPostProcess = null;
  66025. this.volumetricLightPostProcess = null;
  66026. this.volumetricLightSmoothXPostProcess = null;
  66027. this.volumetricLightSmoothYPostProcess = null;
  66028. this.volumetricLightMergePostProces = null;
  66029. this.volumetricLightFinalPostProcess = null;
  66030. this.lensFlarePostProcess = null;
  66031. this.lensFlareComposePostProcess = null;
  66032. this.luminancePostProcess = null;
  66033. this.hdrPostProcess = null;
  66034. this.hdrFinalPostProcess = null;
  66035. this.depthOfFieldPostProcess = null;
  66036. this.motionBlurPostProcess = null;
  66037. this.luminanceDownSamplePostProcesses = [];
  66038. this.blurHPostProcesses = [];
  66039. this.blurVPostProcesses = [];
  66040. };
  66041. // Dispose
  66042. StandardRenderingPipeline.prototype.dispose = function () {
  66043. this._disposePostProcesses();
  66044. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  66045. _super.prototype.dispose.call(this);
  66046. };
  66047. // Serialize rendering pipeline
  66048. StandardRenderingPipeline.prototype.serialize = function () {
  66049. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  66050. serializationObject.customType = "StandardRenderingPipeline";
  66051. return serializationObject;
  66052. };
  66053. /**
  66054. * Static members
  66055. */
  66056. // Parse serialized pipeline
  66057. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  66058. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  66059. };
  66060. // Luminance steps
  66061. StandardRenderingPipeline.LuminanceSteps = 6;
  66062. __decorate([
  66063. BABYLON.serialize()
  66064. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  66065. __decorate([
  66066. BABYLON.serialize()
  66067. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  66068. __decorate([
  66069. BABYLON.serialize()
  66070. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  66071. __decorate([
  66072. BABYLON.serialize()
  66073. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  66074. __decorate([
  66075. BABYLON.serializeAsTexture("lensTexture")
  66076. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  66077. __decorate([
  66078. BABYLON.serialize()
  66079. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  66080. __decorate([
  66081. BABYLON.serialize()
  66082. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  66083. __decorate([
  66084. BABYLON.serialize()
  66085. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  66086. __decorate([
  66087. BABYLON.serialize()
  66088. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  66089. __decorate([
  66090. BABYLON.serialize()
  66091. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  66092. __decorate([
  66093. BABYLON.serialize()
  66094. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  66095. __decorate([
  66096. BABYLON.serializeAsTexture("lensColorTexture")
  66097. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  66098. __decorate([
  66099. BABYLON.serialize()
  66100. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  66101. __decorate([
  66102. BABYLON.serialize()
  66103. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  66104. __decorate([
  66105. BABYLON.serialize()
  66106. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  66107. __decorate([
  66108. BABYLON.serialize()
  66109. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  66110. __decorate([
  66111. BABYLON.serializeAsTexture("lensStarTexture")
  66112. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  66113. __decorate([
  66114. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  66115. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  66116. __decorate([
  66117. BABYLON.serialize()
  66118. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  66119. __decorate([
  66120. BABYLON.serialize()
  66121. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  66122. __decorate([
  66123. BABYLON.serialize()
  66124. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  66125. __decorate([
  66126. BABYLON.serialize()
  66127. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  66128. __decorate([
  66129. BABYLON.serialize()
  66130. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  66131. __decorate([
  66132. BABYLON.serialize()
  66133. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  66134. __decorate([
  66135. BABYLON.serialize()
  66136. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  66137. __decorate([
  66138. BABYLON.serialize()
  66139. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  66140. __decorate([
  66141. BABYLON.serialize()
  66142. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  66143. __decorate([
  66144. BABYLON.serialize()
  66145. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  66146. __decorate([
  66147. BABYLON.serialize()
  66148. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  66149. __decorate([
  66150. BABYLON.serialize()
  66151. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  66152. return StandardRenderingPipeline;
  66153. }(BABYLON.PostProcessRenderPipeline));
  66154. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  66155. })(BABYLON || (BABYLON = {}));
  66156. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  66157. var BABYLON;
  66158. (function (BABYLON) {
  66159. var FxaaPostProcess = /** @class */ (function (_super) {
  66160. __extends(FxaaPostProcess, _super);
  66161. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  66162. if (camera === void 0) { camera = null; }
  66163. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  66164. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  66165. _this.onApplyObservable.add(function (effect) {
  66166. var texelSize = _this.texelSize;
  66167. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  66168. });
  66169. return _this;
  66170. }
  66171. return FxaaPostProcess;
  66172. }(BABYLON.PostProcess));
  66173. BABYLON.FxaaPostProcess = FxaaPostProcess;
  66174. })(BABYLON || (BABYLON = {}));
  66175. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  66176. var BABYLON;
  66177. (function (BABYLON) {
  66178. /**
  66179. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  66180. */
  66181. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  66182. __extends(CircleOfConfusionPostProcess, _super);
  66183. /**
  66184. * Creates a new instance of @see CircleOfConfusionPostProcess
  66185. * @param name The name of the effect.
  66186. * @param scene The scene the effect belongs to.
  66187. * @param depthTexture The depth texture of the scene to compute the circle of confusion.
  66188. * @param options The required width/height ratio to downsize to before computing the render pass.
  66189. * @param camera The camera to apply the render pass to.
  66190. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  66191. * @param engine The engine which the post process will be applied. (default: current engine)
  66192. * @param reusable If the post process can be reused on the same frame. (default: false)
  66193. * @param textureType Type of textures used when performing the post process. (default: 0)
  66194. */
  66195. function CircleOfConfusionPostProcess(name, scene, depthTexture, options, camera, samplingMode, engine, reusable, textureType) {
  66196. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  66197. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType) || this;
  66198. /**
  66199. * 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.
  66200. */
  66201. _this.lensSize = 50;
  66202. /**
  66203. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  66204. */
  66205. _this.fStop = 1.4;
  66206. /**
  66207. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  66208. */
  66209. _this.focusDistance = 2000;
  66210. /**
  66211. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  66212. */
  66213. _this.focalLength = 50;
  66214. _this.onApplyObservable.add(function (effect) {
  66215. effect.setTexture("depthSampler", depthTexture);
  66216. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  66217. var aperture = _this.lensSize / _this.fStop;
  66218. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  66219. effect.setFloat('focusDistance', _this.focusDistance);
  66220. effect.setFloat('cocPrecalculation', cocPrecalculation);
  66221. if (scene.activeCamera) {
  66222. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  66223. }
  66224. });
  66225. return _this;
  66226. }
  66227. return CircleOfConfusionPostProcess;
  66228. }(BABYLON.PostProcess));
  66229. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  66230. })(BABYLON || (BABYLON = {}));
  66231. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  66232. var BABYLON;
  66233. (function (BABYLON) {
  66234. /**
  66235. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  66236. */
  66237. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  66238. __extends(DepthOfFieldMergePostProcess, _super);
  66239. /**
  66240. * Creates a new instance of @see CircleOfConfusionPostProcess
  66241. * @param name The name of the effect.
  66242. * @param original The non-blurred image to be modified
  66243. * @param circleOfConfusion The circle of confusion post process that will determine how blurred each pixel should become.
  66244. * @param blurSteps Incrimental bluring post processes.
  66245. * @param options The required width/height ratio to downsize to before computing the render pass.
  66246. * @param camera The camera to apply the render pass to.
  66247. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  66248. * @param engine The engine which the post process will be applied. (default: current engine)
  66249. * @param reusable If the post process can be reused on the same frame. (default: false)
  66250. * @param textureType Type of textures used when performing the post process. (default: 0)
  66251. */
  66252. function DepthOfFieldMergePostProcess(name, original, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType) {
  66253. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  66254. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "originalSampler", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, "#define BLUR_LEVEL " + blurSteps.length + "\n", textureType) || this;
  66255. _this.onApplyObservable.add(function (effect) {
  66256. effect.setTextureFromPostProcess("circleOfConfusionSampler", circleOfConfusion);
  66257. effect.setTextureFromPostProcess("originalSampler", original);
  66258. blurSteps.forEach(function (step, index) {
  66259. effect.setTextureFromPostProcess("blurStep" + (index + 1), step);
  66260. });
  66261. });
  66262. return _this;
  66263. }
  66264. return DepthOfFieldMergePostProcess;
  66265. }(BABYLON.PostProcess));
  66266. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  66267. })(BABYLON || (BABYLON = {}));
  66268. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  66269. var BABYLON;
  66270. (function (BABYLON) {
  66271. /**
  66272. * Specifies the level of max blur that should be applied when using the depth of field effect
  66273. */
  66274. var DepthOfFieldEffectBlurLevel;
  66275. (function (DepthOfFieldEffectBlurLevel) {
  66276. /**
  66277. * Subtle blur
  66278. */
  66279. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  66280. /**
  66281. * Medium blur
  66282. */
  66283. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  66284. /**
  66285. * Large blur
  66286. */
  66287. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  66288. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  66289. ;
  66290. /**
  66291. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  66292. */
  66293. var DepthOfFieldEffect = /** @class */ (function (_super) {
  66294. __extends(DepthOfFieldEffect, _super);
  66295. /**
  66296. * Creates a new instance of @see DepthOfFieldEffect
  66297. * @param scene The scene the effect belongs to.
  66298. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  66299. */
  66300. function DepthOfFieldEffect(scene, blurLevel, pipelineTextureType) {
  66301. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  66302. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  66303. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  66304. // Enable and get current depth map
  66305. var depthMap = scene.enableDepthRenderer().getDepthMap();
  66306. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  66307. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", scene, depthMap, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  66308. // Capture circle of confusion texture
  66309. _this._depthOfFieldPass = new BABYLON.PassPostProcess("depthOfFieldPass", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  66310. _this._depthOfFieldPass.autoClear = false;
  66311. // 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)
  66312. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  66313. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  66314. _this._depthOfFieldBlurY = [];
  66315. _this._depthOfFieldBlurX = [];
  66316. var blurCount = 1;
  66317. var kernelSize = 15;
  66318. switch (blurLevel) {
  66319. case DepthOfFieldEffectBlurLevel.High: {
  66320. blurCount = 3;
  66321. kernelSize = 51;
  66322. break;
  66323. }
  66324. case DepthOfFieldEffectBlurLevel.Medium: {
  66325. blurCount = 2;
  66326. kernelSize = 31;
  66327. break;
  66328. }
  66329. default: {
  66330. kernelSize = 15;
  66331. blurCount = 1;
  66332. break;
  66333. }
  66334. }
  66335. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  66336. for (var i = 0; i < blurCount; i++) {
  66337. var blurY = new BABYLON.DepthOfFieldBlurPostProcess("verticle blur", scene, new BABYLON.Vector2(0, 1.0), adjustedKernelSize, 1.0 / Math.pow(2, i), null, _this._depthOfFieldPass, i == 0 ? _this._circleOfConfusion : null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  66338. blurY.autoClear = false;
  66339. var blurX = new BABYLON.DepthOfFieldBlurPostProcess("horizontal blur", scene, new BABYLON.Vector2(1.0, 0), adjustedKernelSize, 1.0 / Math.pow(2, i), null, _this._depthOfFieldPass, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  66340. blurX.autoClear = false;
  66341. _this._depthOfFieldBlurY.push(blurY);
  66342. _this._depthOfFieldBlurX.push(blurX);
  66343. }
  66344. // Merge blurred images with original image based on circleOfConfusion
  66345. _this._depthOfFieldMerge = new BABYLON.DepthOfFieldMergePostProcess("depthOfFieldMerge", _this._circleOfConfusion, _this._depthOfFieldPass, _this._depthOfFieldBlurY.slice(1), 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  66346. _this._depthOfFieldMerge.autoClear = false;
  66347. // Set all post processes on the effect.
  66348. var effects = [_this._circleOfConfusion, _this._depthOfFieldPass];
  66349. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  66350. effects.push(_this._depthOfFieldBlurY[i]);
  66351. effects.push(_this._depthOfFieldBlurX[i]);
  66352. }
  66353. effects.push(_this._depthOfFieldMerge);
  66354. return effects;
  66355. }, true) || this;
  66356. return _this;
  66357. }
  66358. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  66359. get: function () {
  66360. return this._circleOfConfusion.focalLength;
  66361. },
  66362. /**
  66363. * The focal the length of the camera used in the effect
  66364. */
  66365. set: function (value) {
  66366. this._circleOfConfusion.focalLength = value;
  66367. },
  66368. enumerable: true,
  66369. configurable: true
  66370. });
  66371. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  66372. get: function () {
  66373. return this._circleOfConfusion.fStop;
  66374. },
  66375. /**
  66376. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  66377. */
  66378. set: function (value) {
  66379. this._circleOfConfusion.fStop = value;
  66380. },
  66381. enumerable: true,
  66382. configurable: true
  66383. });
  66384. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  66385. get: function () {
  66386. return this._circleOfConfusion.focusDistance;
  66387. },
  66388. /**
  66389. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  66390. */
  66391. set: function (value) {
  66392. this._circleOfConfusion.focusDistance = value;
  66393. },
  66394. enumerable: true,
  66395. configurable: true
  66396. });
  66397. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  66398. get: function () {
  66399. return this._circleOfConfusion.lensSize;
  66400. },
  66401. /**
  66402. * 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.
  66403. */
  66404. set: function (value) {
  66405. this._circleOfConfusion.lensSize = value;
  66406. },
  66407. enumerable: true,
  66408. configurable: true
  66409. });
  66410. /**
  66411. * Disposes each of the internal effects for a given camera.
  66412. * @param camera The camera to dispose the effect on.
  66413. */
  66414. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  66415. this._depthOfFieldPass.dispose(camera);
  66416. this._circleOfConfusion.dispose(camera);
  66417. this._depthOfFieldBlurX.forEach(function (element) {
  66418. element.dispose(camera);
  66419. });
  66420. this._depthOfFieldBlurY.forEach(function (element) {
  66421. element.dispose(camera);
  66422. });
  66423. this._depthOfFieldMerge.dispose(camera);
  66424. };
  66425. return DepthOfFieldEffect;
  66426. }(BABYLON.PostProcessRenderEffect));
  66427. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  66428. })(BABYLON || (BABYLON = {}));
  66429. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  66430. var BABYLON;
  66431. (function (BABYLON) {
  66432. /**
  66433. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  66434. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  66435. */
  66436. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  66437. __extends(DefaultRenderingPipeline, _super);
  66438. /**
  66439. * @constructor
  66440. * @param {string} name - The rendering pipeline name
  66441. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  66442. * @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)
  66443. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  66444. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline
  66445. */
  66446. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  66447. if (automaticBuild === void 0) { automaticBuild = true; }
  66448. var _this = _super.call(this, scene.getEngine(), name) || this;
  66449. /**
  66450. * ID of the pass post process used for bloom,
  66451. */
  66452. _this.PassPostProcessId = "PassPostProcessEffect";
  66453. /**
  66454. * ID of the highlight post process used for bloom,
  66455. */
  66456. _this.HighLightsPostProcessId = "HighLightsPostProcessEffect";
  66457. /**
  66458. * ID of the blurX post process used for bloom,
  66459. */
  66460. _this.BlurXPostProcessId = "BlurXPostProcessEffect";
  66461. /**
  66462. * ID of the blurY post process used for bloom,
  66463. */
  66464. _this.BlurYPostProcessId = "BlurYPostProcessEffect";
  66465. /**
  66466. * ID of the copy back post process used for bloom,
  66467. */
  66468. _this.CopyBackPostProcessId = "CopyBackPostProcessEffect";
  66469. /**
  66470. * ID of the image processing post process;
  66471. */
  66472. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  66473. /**
  66474. * ID of the Fast Approximate Anti-Aliasing post process;
  66475. */
  66476. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  66477. /**
  66478. * ID of the final merge post process;
  66479. */
  66480. _this.FinalMergePostProcessId = "FinalMergePostProcessEffect";
  66481. /**
  66482. * Animations which can be used to tweak settings over a period of time
  66483. */
  66484. _this.animations = [];
  66485. // Values
  66486. _this._bloomEnabled = false;
  66487. _this._depthOfFieldEnabled = false;
  66488. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  66489. _this._fxaaEnabled = false;
  66490. _this._imageProcessingEnabled = true;
  66491. _this._bloomScale = 0.6;
  66492. _this._buildAllowed = true;
  66493. /**
  66494. * Specifies the size of the bloom blur kernel, relative to the final output size
  66495. */
  66496. _this.bloomKernel = 64;
  66497. /**
  66498. * Specifies the weight of the bloom in the final rendering
  66499. */
  66500. _this._bloomWeight = 0.15;
  66501. _this._cameras = cameras || [];
  66502. _this._buildAllowed = automaticBuild;
  66503. // Initialize
  66504. _this._scene = scene;
  66505. var caps = _this._scene.getEngine().getCaps();
  66506. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  66507. // Misc
  66508. if (_this._hdr) {
  66509. if (caps.textureHalfFloatRender) {
  66510. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  66511. }
  66512. else if (caps.textureFloatRender) {
  66513. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  66514. }
  66515. }
  66516. else {
  66517. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  66518. }
  66519. // Attach
  66520. scene.postProcessRenderPipelineManager.addPipeline(_this);
  66521. _this._buildPipeline();
  66522. return _this;
  66523. }
  66524. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  66525. get: function () {
  66526. return this._bloomWeight;
  66527. },
  66528. /**
  66529. * The strength of the bloom.
  66530. */
  66531. set: function (value) {
  66532. if (this._bloomWeight === value) {
  66533. return;
  66534. }
  66535. this._bloomWeight = value;
  66536. if (this._hdr && this.copyBack) {
  66537. this.copyBack.alphaConstants = new BABYLON.Color4(value, value, value, value);
  66538. }
  66539. },
  66540. enumerable: true,
  66541. configurable: true
  66542. });
  66543. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  66544. get: function () {
  66545. return this._bloomScale;
  66546. },
  66547. /**
  66548. * The scale of the bloom, lower value will provide better performance.
  66549. */
  66550. set: function (value) {
  66551. if (this._bloomScale === value) {
  66552. return;
  66553. }
  66554. this._bloomScale = value;
  66555. this._buildPipeline();
  66556. },
  66557. enumerable: true,
  66558. configurable: true
  66559. });
  66560. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  66561. get: function () {
  66562. return this._bloomEnabled;
  66563. },
  66564. /**
  66565. * Enable or disable the bloom from the pipeline
  66566. */
  66567. set: function (enabled) {
  66568. if (this._bloomEnabled === enabled) {
  66569. return;
  66570. }
  66571. this._bloomEnabled = enabled;
  66572. this._buildPipeline();
  66573. },
  66574. enumerable: true,
  66575. configurable: true
  66576. });
  66577. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  66578. /**
  66579. * If the depth of field is enabled.
  66580. */
  66581. get: function () {
  66582. return this._depthOfFieldEnabled;
  66583. },
  66584. set: function (enabled) {
  66585. if (this._depthOfFieldEnabled === enabled) {
  66586. return;
  66587. }
  66588. this._depthOfFieldEnabled = enabled;
  66589. this._buildPipeline();
  66590. },
  66591. enumerable: true,
  66592. configurable: true
  66593. });
  66594. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  66595. /**
  66596. * Blur level of the depth of field effect. (Higher blur will effect performance)
  66597. */
  66598. get: function () {
  66599. return this._depthOfFieldBlurLevel;
  66600. },
  66601. set: function (value) {
  66602. if (this._depthOfFieldBlurLevel === value) {
  66603. return;
  66604. }
  66605. this._depthOfFieldBlurLevel = value;
  66606. this._buildPipeline();
  66607. },
  66608. enumerable: true,
  66609. configurable: true
  66610. });
  66611. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  66612. get: function () {
  66613. return this._fxaaEnabled;
  66614. },
  66615. /**
  66616. * If the anti aliasing is enabled.
  66617. */
  66618. set: function (enabled) {
  66619. if (this._fxaaEnabled === enabled) {
  66620. return;
  66621. }
  66622. this._fxaaEnabled = enabled;
  66623. this._buildPipeline();
  66624. },
  66625. enumerable: true,
  66626. configurable: true
  66627. });
  66628. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  66629. get: function () {
  66630. return this._imageProcessingEnabled;
  66631. },
  66632. /**
  66633. * If image processing is enabled.
  66634. */
  66635. set: function (enabled) {
  66636. if (this._imageProcessingEnabled === enabled) {
  66637. return;
  66638. }
  66639. this._imageProcessingEnabled = enabled;
  66640. this._buildPipeline();
  66641. },
  66642. enumerable: true,
  66643. configurable: true
  66644. });
  66645. /**
  66646. * Force the compilation of the entire pipeline.
  66647. */
  66648. DefaultRenderingPipeline.prototype.prepare = function () {
  66649. var previousState = this._buildAllowed;
  66650. this._buildAllowed = true;
  66651. this._buildPipeline();
  66652. this._buildAllowed = previousState;
  66653. };
  66654. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  66655. var _this = this;
  66656. if (!this._buildAllowed) {
  66657. return;
  66658. }
  66659. var engine = this._scene.getEngine();
  66660. this._disposePostProcesses();
  66661. this._reset();
  66662. if (this.depthOfFieldEnabled) {
  66663. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType);
  66664. this.addEffect(this.depthOfField);
  66665. }
  66666. if (this.bloomEnabled) {
  66667. this.pass = new BABYLON.PassPostProcess("sceneRenderTarget", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  66668. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.PassPostProcessId, function () { return _this.pass; }, true));
  66669. if (!this._hdr) {
  66670. this.highlights = new BABYLON.HighlightsPostProcess("highlights", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  66671. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.HighLightsPostProcessId, function () { return _this.highlights; }, true));
  66672. this.highlights.autoClear = false;
  66673. this.highlights.alwaysForcePOT = true;
  66674. }
  66675. this.blurX = new BABYLON.BlurPostProcess("horizontal blur", new BABYLON.Vector2(1.0, 0), 10.0, this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  66676. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurXPostProcessId, function () { return _this.blurX; }, true));
  66677. this.blurX.alwaysForcePOT = true;
  66678. this.blurX.autoClear = false;
  66679. this.blurX.onActivateObservable.add(function () {
  66680. var dw = _this.blurX.width / engine.getRenderWidth(true);
  66681. _this.blurX.kernel = _this.bloomKernel * dw;
  66682. });
  66683. this.blurY = new BABYLON.BlurPostProcess("vertical blur", new BABYLON.Vector2(0, 1.0), 10.0, this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  66684. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurYPostProcessId, function () { return _this.blurY; }, true));
  66685. this.blurY.alwaysForcePOT = true;
  66686. this.blurY.autoClear = false;
  66687. this.blurY.onActivateObservable.add(function () {
  66688. var dh = _this.blurY.height / engine.getRenderHeight(true);
  66689. _this.blurY.kernel = _this.bloomKernel * dh;
  66690. });
  66691. this.copyBack = new BABYLON.PassPostProcess("bloomBlendBlit", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  66692. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.CopyBackPostProcessId, function () { return _this.copyBack; }, true));
  66693. this.copyBack.alwaysForcePOT = true;
  66694. if (this._hdr) {
  66695. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_INTERPOLATE;
  66696. var w = this.bloomWeight;
  66697. this.copyBack.alphaConstants = new BABYLON.Color4(w, w, w, w);
  66698. }
  66699. else {
  66700. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_SCREENMODE;
  66701. }
  66702. this.copyBack.autoClear = false;
  66703. }
  66704. if (this._imageProcessingEnabled) {
  66705. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  66706. if (this._hdr) {
  66707. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  66708. }
  66709. else {
  66710. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  66711. }
  66712. }
  66713. if (this.fxaaEnabled) {
  66714. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  66715. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  66716. this.fxaa.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  66717. }
  66718. else if (this._hdr && this.imageProcessing) {
  66719. this.finalMerge = this.imageProcessing;
  66720. }
  66721. else {
  66722. this.finalMerge = new BABYLON.PassPostProcess("finalMerge", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  66723. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FinalMergePostProcessId, function () { return _this.finalMerge; }, true));
  66724. this.finalMerge.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  66725. }
  66726. if (this.bloomEnabled) {
  66727. if (this._hdr) {
  66728. this.copyBack.shareOutputWith(this.blurX);
  66729. if (this.imageProcessing) {
  66730. this.imageProcessing.shareOutputWith(this.pass);
  66731. this.imageProcessing.autoClear = false;
  66732. }
  66733. else if (this.fxaa) {
  66734. this.fxaa.shareOutputWith(this.pass);
  66735. }
  66736. else {
  66737. this.finalMerge.shareOutputWith(this.pass);
  66738. }
  66739. }
  66740. else {
  66741. if (this.fxaa) {
  66742. this.fxaa.shareOutputWith(this.pass);
  66743. }
  66744. else {
  66745. this.finalMerge.shareOutputWith(this.pass);
  66746. }
  66747. }
  66748. }
  66749. if (this._cameras !== null) {
  66750. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  66751. }
  66752. };
  66753. DefaultRenderingPipeline.prototype._disposePostProcesses = function () {
  66754. for (var i = 0; i < this._cameras.length; i++) {
  66755. var camera = this._cameras[i];
  66756. if (this.pass) {
  66757. this.pass.dispose(camera);
  66758. }
  66759. if (this.highlights) {
  66760. this.highlights.dispose(camera);
  66761. }
  66762. if (this.blurX) {
  66763. this.blurX.dispose(camera);
  66764. }
  66765. if (this.blurY) {
  66766. this.blurY.dispose(camera);
  66767. }
  66768. if (this.copyBack) {
  66769. this.copyBack.dispose(camera);
  66770. }
  66771. if (this.imageProcessing) {
  66772. this.imageProcessing.dispose(camera);
  66773. }
  66774. if (this.fxaa) {
  66775. this.fxaa.dispose(camera);
  66776. }
  66777. if (this.finalMerge) {
  66778. this.finalMerge.dispose(camera);
  66779. }
  66780. if (this.depthOfField) {
  66781. this.depthOfField.disposeEffects(camera);
  66782. }
  66783. }
  66784. this.pass = null;
  66785. this.highlights = null;
  66786. this.blurX = null;
  66787. this.blurY = null;
  66788. this.copyBack = null;
  66789. this.imageProcessing = null;
  66790. this.fxaa = null;
  66791. this.finalMerge = null;
  66792. this.depthOfField = null;
  66793. };
  66794. /**
  66795. * Dispose of the pipeline and stop all post processes
  66796. */
  66797. DefaultRenderingPipeline.prototype.dispose = function () {
  66798. this._disposePostProcesses();
  66799. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  66800. _super.prototype.dispose.call(this);
  66801. };
  66802. /**
  66803. * Serialize the rendering pipeline (Used when exporting)
  66804. * @returns the serialized object
  66805. */
  66806. DefaultRenderingPipeline.prototype.serialize = function () {
  66807. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  66808. serializationObject.customType = "DefaultRenderingPipeline";
  66809. return serializationObject;
  66810. };
  66811. /**
  66812. * Parse the serialized pipeline
  66813. * @param source Source pipeline.
  66814. * @param scene The scene to load the pipeline to.
  66815. * @param rootUrl The URL of the serialized pipeline.
  66816. * @returns An instantiated pipeline from the serialized object.
  66817. */
  66818. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  66819. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  66820. };
  66821. __decorate([
  66822. BABYLON.serialize()
  66823. ], DefaultRenderingPipeline.prototype, "bloomKernel", void 0);
  66824. __decorate([
  66825. BABYLON.serialize()
  66826. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  66827. __decorate([
  66828. BABYLON.serialize()
  66829. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  66830. __decorate([
  66831. BABYLON.serialize()
  66832. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  66833. __decorate([
  66834. BABYLON.serialize()
  66835. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  66836. __decorate([
  66837. BABYLON.serialize()
  66838. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  66839. __decorate([
  66840. BABYLON.serialize()
  66841. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  66842. __decorate([
  66843. BABYLON.serialize()
  66844. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  66845. __decorate([
  66846. BABYLON.serialize()
  66847. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  66848. __decorate([
  66849. BABYLON.serialize()
  66850. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  66851. return DefaultRenderingPipeline;
  66852. }(BABYLON.PostProcessRenderPipeline));
  66853. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  66854. })(BABYLON || (BABYLON = {}));
  66855. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  66856. var BABYLON;
  66857. (function (BABYLON) {
  66858. /**
  66859. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  66860. */
  66861. var GeometryBufferRenderer = /** @class */ (function () {
  66862. /**
  66863. * Creates a new G Buffer for the scene. @see GeometryBufferRenderer
  66864. * @param scene The scene the buffer belongs to
  66865. * @param ratio How big is the buffer related to the main canvas.
  66866. */
  66867. function GeometryBufferRenderer(scene, ratio) {
  66868. if (ratio === void 0) { ratio = 1; }
  66869. this._enablePosition = false;
  66870. this._scene = scene;
  66871. this._ratio = ratio;
  66872. // Render target
  66873. this._createRenderTargets();
  66874. }
  66875. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  66876. /**
  66877. * Set the render list (meshes to be rendered) used in the G buffer.
  66878. */
  66879. set: function (meshes) {
  66880. this._multiRenderTarget.renderList = meshes;
  66881. },
  66882. enumerable: true,
  66883. configurable: true
  66884. });
  66885. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  66886. /**
  66887. * Gets wether or not G buffer are supported by the running hardware.
  66888. * This requires draw buffer supports
  66889. */
  66890. get: function () {
  66891. return this._multiRenderTarget.isSupported;
  66892. },
  66893. enumerable: true,
  66894. configurable: true
  66895. });
  66896. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  66897. /**
  66898. * Gets wether or not position are enabled for the G buffer.
  66899. */
  66900. get: function () {
  66901. return this._enablePosition;
  66902. },
  66903. /**
  66904. * Sets wether or not position are enabled for the G buffer.
  66905. */
  66906. set: function (enable) {
  66907. this._enablePosition = enable;
  66908. this.dispose();
  66909. this._createRenderTargets();
  66910. },
  66911. enumerable: true,
  66912. configurable: true
  66913. });
  66914. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  66915. /**
  66916. * Gets the scene associated with the buffer.
  66917. */
  66918. get: function () {
  66919. return this._scene;
  66920. },
  66921. enumerable: true,
  66922. configurable: true
  66923. });
  66924. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  66925. /**
  66926. * Gets the ratio used by the buffer during its creation.
  66927. * How big is the buffer related to the main canvas.
  66928. */
  66929. get: function () {
  66930. return this._ratio;
  66931. },
  66932. enumerable: true,
  66933. configurable: true
  66934. });
  66935. /**
  66936. * Checks wether everything is ready to render a submesh to the G buffer.
  66937. * @param subMesh the submesh to check readiness for
  66938. * @param useInstances is the mesh drawn using instance or not
  66939. * @returns true if ready otherwise false
  66940. */
  66941. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  66942. var material = subMesh.getMaterial();
  66943. if (material && material.disableDepthWrite) {
  66944. return false;
  66945. }
  66946. var defines = [];
  66947. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  66948. var mesh = subMesh.getMesh();
  66949. // Alpha test
  66950. if (material && material.needAlphaTesting()) {
  66951. defines.push("#define ALPHATEST");
  66952. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  66953. attribs.push(BABYLON.VertexBuffer.UVKind);
  66954. defines.push("#define UV1");
  66955. }
  66956. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  66957. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  66958. defines.push("#define UV2");
  66959. }
  66960. }
  66961. // Buffers
  66962. if (this._enablePosition) {
  66963. defines.push("#define POSITION");
  66964. }
  66965. // Bones
  66966. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  66967. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  66968. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  66969. if (mesh.numBoneInfluencers > 4) {
  66970. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  66971. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  66972. }
  66973. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  66974. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  66975. }
  66976. else {
  66977. defines.push("#define NUM_BONE_INFLUENCERS 0");
  66978. }
  66979. // Instances
  66980. if (useInstances) {
  66981. defines.push("#define INSTANCES");
  66982. attribs.push("world0");
  66983. attribs.push("world1");
  66984. attribs.push("world2");
  66985. attribs.push("world3");
  66986. }
  66987. // Get correct effect
  66988. var join = defines.join("\n");
  66989. if (this._cachedDefines !== join) {
  66990. this._cachedDefines = join;
  66991. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  66992. }
  66993. return this._effect.isReady();
  66994. };
  66995. /**
  66996. * Gets the current underlying G Buffer.
  66997. * @returns the buffer
  66998. */
  66999. GeometryBufferRenderer.prototype.getGBuffer = function () {
  67000. return this._multiRenderTarget;
  67001. };
  67002. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  67003. /**
  67004. * Gets the number of samples used to render the buffer (anti aliasing).
  67005. */
  67006. get: function () {
  67007. return this._multiRenderTarget.samples;
  67008. },
  67009. /**
  67010. * Sets the number of samples used to render the buffer (anti aliasing).
  67011. */
  67012. set: function (value) {
  67013. this._multiRenderTarget.samples = value;
  67014. },
  67015. enumerable: true,
  67016. configurable: true
  67017. });
  67018. /**
  67019. * Disposes the renderer and frees up associated resources.
  67020. */
  67021. GeometryBufferRenderer.prototype.dispose = function () {
  67022. this.getGBuffer().dispose();
  67023. };
  67024. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  67025. var _this = this;
  67026. var engine = this._scene.getEngine();
  67027. var count = this._enablePosition ? 3 : 2;
  67028. 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 });
  67029. if (!this.isSupported) {
  67030. return;
  67031. }
  67032. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67033. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67034. this._multiRenderTarget.refreshRate = 1;
  67035. this._multiRenderTarget.renderParticles = false;
  67036. this._multiRenderTarget.renderList = null;
  67037. // set default depth value to 1.0 (far away)
  67038. this._multiRenderTarget.onClearObservable.add(function (engine) {
  67039. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  67040. });
  67041. // Custom render function
  67042. var renderSubMesh = function (subMesh) {
  67043. var mesh = subMesh.getRenderingMesh();
  67044. var scene = _this._scene;
  67045. var engine = scene.getEngine();
  67046. var material = subMesh.getMaterial();
  67047. if (!material) {
  67048. return;
  67049. }
  67050. // Culling
  67051. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  67052. // Managing instances
  67053. var batch = mesh._getInstancesRenderList(subMesh._id);
  67054. if (batch.mustReturn) {
  67055. return;
  67056. }
  67057. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  67058. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  67059. engine.enableEffect(_this._effect);
  67060. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  67061. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  67062. _this._effect.setMatrix("view", scene.getViewMatrix());
  67063. // Alpha test
  67064. if (material && material.needAlphaTesting()) {
  67065. var alphaTexture = material.getAlphaTestTexture();
  67066. if (alphaTexture) {
  67067. _this._effect.setTexture("diffuseSampler", alphaTexture);
  67068. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  67069. }
  67070. }
  67071. // Bones
  67072. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  67073. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  67074. }
  67075. // Draw
  67076. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  67077. }
  67078. };
  67079. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  67080. var index;
  67081. if (depthOnlySubMeshes.length) {
  67082. engine.setColorWrite(false);
  67083. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  67084. renderSubMesh(depthOnlySubMeshes.data[index]);
  67085. }
  67086. engine.setColorWrite(true);
  67087. }
  67088. for (index = 0; index < opaqueSubMeshes.length; index++) {
  67089. renderSubMesh(opaqueSubMeshes.data[index]);
  67090. }
  67091. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  67092. renderSubMesh(alphaTestSubMeshes.data[index]);
  67093. }
  67094. };
  67095. };
  67096. return GeometryBufferRenderer;
  67097. }());
  67098. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  67099. })(BABYLON || (BABYLON = {}));
  67100. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  67101. var BABYLON;
  67102. (function (BABYLON) {
  67103. var RefractionPostProcess = /** @class */ (function (_super) {
  67104. __extends(RefractionPostProcess, _super);
  67105. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  67106. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  67107. _this.color = color;
  67108. _this.depth = depth;
  67109. _this.colorLevel = colorLevel;
  67110. _this.onActivateObservable.add(function (cam) {
  67111. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  67112. });
  67113. _this.onApplyObservable.add(function (effect) {
  67114. effect.setColor3("baseColor", _this.color);
  67115. effect.setFloat("depth", _this.depth);
  67116. effect.setFloat("colorLevel", _this.colorLevel);
  67117. effect.setTexture("refractionSampler", _this._refRexture);
  67118. });
  67119. return _this;
  67120. }
  67121. // Methods
  67122. RefractionPostProcess.prototype.dispose = function (camera) {
  67123. if (this._refRexture) {
  67124. this._refRexture.dispose();
  67125. }
  67126. _super.prototype.dispose.call(this, camera);
  67127. };
  67128. return RefractionPostProcess;
  67129. }(BABYLON.PostProcess));
  67130. BABYLON.RefractionPostProcess = RefractionPostProcess;
  67131. })(BABYLON || (BABYLON = {}));
  67132. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  67133. var BABYLON;
  67134. (function (BABYLON) {
  67135. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  67136. __extends(BlackAndWhitePostProcess, _super);
  67137. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  67138. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  67139. _this.degree = 1;
  67140. _this.onApplyObservable.add(function (effect) {
  67141. effect.setFloat("degree", _this.degree);
  67142. });
  67143. return _this;
  67144. }
  67145. return BlackAndWhitePostProcess;
  67146. }(BABYLON.PostProcess));
  67147. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  67148. })(BABYLON || (BABYLON = {}));
  67149. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  67150. var BABYLON;
  67151. (function (BABYLON) {
  67152. var ConvolutionPostProcess = /** @class */ (function (_super) {
  67153. __extends(ConvolutionPostProcess, _super);
  67154. function ConvolutionPostProcess(name, kernel, options, camera, samplingMode, engine, reusable) {
  67155. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable) || this;
  67156. _this.kernel = kernel;
  67157. _this.onApply = function (effect) {
  67158. effect.setFloat2("screenSize", _this.width, _this.height);
  67159. effect.setArray("kernel", _this.kernel);
  67160. };
  67161. return _this;
  67162. }
  67163. // Statics
  67164. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  67165. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  67166. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  67167. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  67168. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  67169. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  67170. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  67171. return ConvolutionPostProcess;
  67172. }(BABYLON.PostProcess));
  67173. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  67174. })(BABYLON || (BABYLON = {}));
  67175. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  67176. var BABYLON;
  67177. (function (BABYLON) {
  67178. var FilterPostProcess = /** @class */ (function (_super) {
  67179. __extends(FilterPostProcess, _super);
  67180. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  67181. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  67182. _this.kernelMatrix = kernelMatrix;
  67183. _this.onApply = function (effect) {
  67184. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  67185. };
  67186. return _this;
  67187. }
  67188. return FilterPostProcess;
  67189. }(BABYLON.PostProcess));
  67190. BABYLON.FilterPostProcess = FilterPostProcess;
  67191. })(BABYLON || (BABYLON = {}));
  67192. //# sourceMappingURL=babylon.filterPostProcess.js.map
  67193. var BABYLON;
  67194. (function (BABYLON) {
  67195. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  67196. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  67197. __extends(VolumetricLightScatteringPostProcess, _super);
  67198. /**
  67199. * @constructor
  67200. * @param {string} name - The post-process name
  67201. * @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)
  67202. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  67203. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  67204. * @param {number} samples - The post-process quality, default 100
  67205. * @param {number} samplingMode - The post-process filtering mode
  67206. * @param {BABYLON.Engine} engine - The babylon engine
  67207. * @param {boolean} reusable - If the post-process is reusable
  67208. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  67209. */
  67210. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  67211. if (samples === void 0) { samples = 100; }
  67212. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  67213. 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;
  67214. _this._screenCoordinates = BABYLON.Vector2.Zero();
  67215. /**
  67216. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  67217. * @type {Vector3}
  67218. */
  67219. _this.customMeshPosition = BABYLON.Vector3.Zero();
  67220. /**
  67221. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  67222. * @type {boolean}
  67223. */
  67224. _this.useCustomMeshPosition = false;
  67225. /**
  67226. * If the post-process should inverse the light scattering direction
  67227. * @type {boolean}
  67228. */
  67229. _this.invert = true;
  67230. /**
  67231. * Array containing the excluded meshes not rendered in the internal pass
  67232. */
  67233. _this.excludedMeshes = new Array();
  67234. /**
  67235. * Controls the overall intensity of the post-process
  67236. * @type {number}
  67237. */
  67238. _this.exposure = 0.3;
  67239. /**
  67240. * Dissipates each sample's contribution in range [0, 1]
  67241. * @type {number}
  67242. */
  67243. _this.decay = 0.96815;
  67244. /**
  67245. * Controls the overall intensity of each sample
  67246. * @type {number}
  67247. */
  67248. _this.weight = 0.58767;
  67249. /**
  67250. * Controls the density of each sample
  67251. * @type {number}
  67252. */
  67253. _this.density = 0.926;
  67254. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  67255. engine = scene.getEngine();
  67256. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  67257. // Configure mesh
  67258. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  67259. // Configure
  67260. _this._createPass(scene, ratio.passRatio || ratio);
  67261. _this.onActivate = function (camera) {
  67262. if (!_this.isSupported) {
  67263. _this.dispose(camera);
  67264. }
  67265. _this.onActivate = null;
  67266. };
  67267. _this.onApplyObservable.add(function (effect) {
  67268. _this._updateMeshScreenCoordinates(scene);
  67269. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  67270. effect.setFloat("exposure", _this.exposure);
  67271. effect.setFloat("decay", _this.decay);
  67272. effect.setFloat("weight", _this.weight);
  67273. effect.setFloat("density", _this.density);
  67274. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  67275. });
  67276. return _this;
  67277. }
  67278. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  67279. get: function () {
  67280. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  67281. return false;
  67282. },
  67283. set: function (useDiffuseColor) {
  67284. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  67285. },
  67286. enumerable: true,
  67287. configurable: true
  67288. });
  67289. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  67290. return "VolumetricLightScatteringPostProcess";
  67291. };
  67292. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  67293. var mesh = subMesh.getMesh();
  67294. // Render this.mesh as default
  67295. if (mesh === this.mesh && mesh.material) {
  67296. return mesh.material.isReady(mesh);
  67297. }
  67298. var defines = [];
  67299. var attribs = [BABYLON.VertexBuffer.PositionKind];
  67300. var material = subMesh.getMaterial();
  67301. // Alpha test
  67302. if (material) {
  67303. if (material.needAlphaTesting()) {
  67304. defines.push("#define ALPHATEST");
  67305. }
  67306. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  67307. attribs.push(BABYLON.VertexBuffer.UVKind);
  67308. defines.push("#define UV1");
  67309. }
  67310. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  67311. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  67312. defines.push("#define UV2");
  67313. }
  67314. }
  67315. // Bones
  67316. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  67317. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  67318. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  67319. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  67320. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  67321. }
  67322. else {
  67323. defines.push("#define NUM_BONE_INFLUENCERS 0");
  67324. }
  67325. // Instances
  67326. if (useInstances) {
  67327. defines.push("#define INSTANCES");
  67328. attribs.push("world0");
  67329. attribs.push("world1");
  67330. attribs.push("world2");
  67331. attribs.push("world3");
  67332. }
  67333. // Get correct effect
  67334. var join = defines.join("\n");
  67335. if (this._cachedDefines !== join) {
  67336. this._cachedDefines = join;
  67337. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  67338. }
  67339. return this._volumetricLightScatteringPass.isReady();
  67340. };
  67341. /**
  67342. * Sets the new light position for light scattering effect
  67343. * @param {BABYLON.Vector3} The new custom light position
  67344. */
  67345. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  67346. this.customMeshPosition = position;
  67347. };
  67348. /**
  67349. * Returns the light position for light scattering effect
  67350. * @return {BABYLON.Vector3} The custom light position
  67351. */
  67352. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  67353. return this.customMeshPosition;
  67354. };
  67355. /**
  67356. * Disposes the internal assets and detaches the post-process from the camera
  67357. */
  67358. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  67359. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  67360. if (rttIndex !== -1) {
  67361. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  67362. }
  67363. this._volumetricLightScatteringRTT.dispose();
  67364. _super.prototype.dispose.call(this, camera);
  67365. };
  67366. /**
  67367. * Returns the render target texture used by the post-process
  67368. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  67369. */
  67370. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  67371. return this._volumetricLightScatteringRTT;
  67372. };
  67373. // Private methods
  67374. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  67375. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  67376. return true;
  67377. }
  67378. return false;
  67379. };
  67380. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  67381. var _this = this;
  67382. var engine = scene.getEngine();
  67383. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  67384. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67385. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67386. this._volumetricLightScatteringRTT.renderList = null;
  67387. this._volumetricLightScatteringRTT.renderParticles = false;
  67388. var camera = this.getCamera();
  67389. if (camera) {
  67390. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  67391. }
  67392. else {
  67393. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  67394. }
  67395. // Custom render function for submeshes
  67396. var renderSubMesh = function (subMesh) {
  67397. var mesh = subMesh.getRenderingMesh();
  67398. if (_this._meshExcluded(mesh)) {
  67399. return;
  67400. }
  67401. var material = subMesh.getMaterial();
  67402. if (!material) {
  67403. return;
  67404. }
  67405. var scene = mesh.getScene();
  67406. var engine = scene.getEngine();
  67407. // Culling
  67408. engine.setState(material.backFaceCulling);
  67409. // Managing instances
  67410. var batch = mesh._getInstancesRenderList(subMesh._id);
  67411. if (batch.mustReturn) {
  67412. return;
  67413. }
  67414. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  67415. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  67416. var effect = _this._volumetricLightScatteringPass;
  67417. if (mesh === _this.mesh) {
  67418. if (subMesh.effect) {
  67419. effect = subMesh.effect;
  67420. }
  67421. else {
  67422. effect = material.getEffect();
  67423. }
  67424. }
  67425. engine.enableEffect(effect);
  67426. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  67427. if (mesh === _this.mesh) {
  67428. material.bind(mesh.getWorldMatrix(), mesh);
  67429. }
  67430. else {
  67431. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  67432. // Alpha test
  67433. if (material && material.needAlphaTesting()) {
  67434. var alphaTexture = material.getAlphaTestTexture();
  67435. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  67436. if (alphaTexture) {
  67437. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  67438. }
  67439. }
  67440. // Bones
  67441. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  67442. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  67443. }
  67444. }
  67445. // Draw
  67446. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  67447. }
  67448. };
  67449. // Render target texture callbacks
  67450. var savedSceneClearColor;
  67451. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  67452. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  67453. savedSceneClearColor = scene.clearColor;
  67454. scene.clearColor = sceneClearColor;
  67455. });
  67456. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  67457. scene.clearColor = savedSceneClearColor;
  67458. });
  67459. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  67460. var engine = scene.getEngine();
  67461. var index;
  67462. if (depthOnlySubMeshes.length) {
  67463. engine.setColorWrite(false);
  67464. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  67465. renderSubMesh(depthOnlySubMeshes.data[index]);
  67466. }
  67467. engine.setColorWrite(true);
  67468. }
  67469. for (index = 0; index < opaqueSubMeshes.length; index++) {
  67470. renderSubMesh(opaqueSubMeshes.data[index]);
  67471. }
  67472. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  67473. renderSubMesh(alphaTestSubMeshes.data[index]);
  67474. }
  67475. if (transparentSubMeshes.length) {
  67476. // Sort sub meshes
  67477. for (index = 0; index < transparentSubMeshes.length; index++) {
  67478. var submesh = transparentSubMeshes.data[index];
  67479. var boundingInfo = submesh.getBoundingInfo();
  67480. if (boundingInfo && scene.activeCamera) {
  67481. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  67482. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  67483. }
  67484. }
  67485. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  67486. sortedArray.sort(function (a, b) {
  67487. // Alpha index first
  67488. if (a._alphaIndex > b._alphaIndex) {
  67489. return 1;
  67490. }
  67491. if (a._alphaIndex < b._alphaIndex) {
  67492. return -1;
  67493. }
  67494. // Then distance to camera
  67495. if (a._distanceToCamera < b._distanceToCamera) {
  67496. return 1;
  67497. }
  67498. if (a._distanceToCamera > b._distanceToCamera) {
  67499. return -1;
  67500. }
  67501. return 0;
  67502. });
  67503. // Render sub meshes
  67504. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  67505. for (index = 0; index < sortedArray.length; index++) {
  67506. renderSubMesh(sortedArray[index]);
  67507. }
  67508. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  67509. }
  67510. };
  67511. };
  67512. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  67513. var transform = scene.getTransformMatrix();
  67514. var meshPosition;
  67515. if (this.useCustomMeshPosition) {
  67516. meshPosition = this.customMeshPosition;
  67517. }
  67518. else if (this.attachedNode) {
  67519. meshPosition = this.attachedNode.position;
  67520. }
  67521. else {
  67522. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  67523. }
  67524. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  67525. this._screenCoordinates.x = pos.x / this._viewPort.width;
  67526. this._screenCoordinates.y = pos.y / this._viewPort.height;
  67527. if (this.invert)
  67528. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  67529. };
  67530. // Static methods
  67531. /**
  67532. * Creates a default mesh for the Volumeric Light Scattering post-process
  67533. * @param {string} The mesh name
  67534. * @param {BABYLON.Scene} The scene where to create the mesh
  67535. * @return {BABYLON.Mesh} the default mesh
  67536. */
  67537. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  67538. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  67539. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  67540. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  67541. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  67542. mesh.material = material;
  67543. return mesh;
  67544. };
  67545. __decorate([
  67546. BABYLON.serializeAsVector3()
  67547. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  67548. __decorate([
  67549. BABYLON.serialize()
  67550. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  67551. __decorate([
  67552. BABYLON.serialize()
  67553. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  67554. __decorate([
  67555. BABYLON.serializeAsMeshReference()
  67556. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  67557. __decorate([
  67558. BABYLON.serialize()
  67559. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  67560. __decorate([
  67561. BABYLON.serialize()
  67562. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  67563. __decorate([
  67564. BABYLON.serialize()
  67565. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  67566. __decorate([
  67567. BABYLON.serialize()
  67568. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  67569. __decorate([
  67570. BABYLON.serialize()
  67571. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  67572. return VolumetricLightScatteringPostProcess;
  67573. }(BABYLON.PostProcess));
  67574. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  67575. })(BABYLON || (BABYLON = {}));
  67576. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  67577. //
  67578. // This post-process allows the modification of rendered colors by using
  67579. // a 'look-up table' (LUT). This effect is also called Color Grading.
  67580. //
  67581. // The object needs to be provided an url to a texture containing the color
  67582. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  67583. // Use an image editing software to tweak the LUT to match your needs.
  67584. //
  67585. // For an example of a color LUT, see here:
  67586. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  67587. // For explanations on color grading, see here:
  67588. // http://udn.epicgames.com/Three/ColorGrading.html
  67589. //
  67590. var BABYLON;
  67591. (function (BABYLON) {
  67592. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  67593. __extends(ColorCorrectionPostProcess, _super);
  67594. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  67595. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  67596. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  67597. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  67598. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67599. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67600. _this.onApply = function (effect) {
  67601. effect.setTexture("colorTable", _this._colorTableTexture);
  67602. };
  67603. return _this;
  67604. }
  67605. return ColorCorrectionPostProcess;
  67606. }(BABYLON.PostProcess));
  67607. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  67608. })(BABYLON || (BABYLON = {}));
  67609. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  67610. var BABYLON;
  67611. (function (BABYLON) {
  67612. var TonemappingOperator;
  67613. (function (TonemappingOperator) {
  67614. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  67615. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  67616. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  67617. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  67618. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  67619. ;
  67620. var TonemapPostProcess = /** @class */ (function (_super) {
  67621. __extends(TonemapPostProcess, _super);
  67622. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  67623. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  67624. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  67625. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  67626. _this._operator = _operator;
  67627. _this.exposureAdjustment = exposureAdjustment;
  67628. var defines = "#define ";
  67629. if (_this._operator === TonemappingOperator.Hable)
  67630. defines += "HABLE_TONEMAPPING";
  67631. else if (_this._operator === TonemappingOperator.Reinhard)
  67632. defines += "REINHARD_TONEMAPPING";
  67633. else if (_this._operator === TonemappingOperator.HejiDawson)
  67634. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  67635. else if (_this._operator === TonemappingOperator.Photographic)
  67636. defines += "PHOTOGRAPHIC_TONEMAPPING";
  67637. //sadly a second call to create the effect.
  67638. _this.updateEffect(defines);
  67639. _this.onApply = function (effect) {
  67640. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  67641. };
  67642. return _this;
  67643. }
  67644. return TonemapPostProcess;
  67645. }(BABYLON.PostProcess));
  67646. BABYLON.TonemapPostProcess = TonemapPostProcess;
  67647. })(BABYLON || (BABYLON = {}));
  67648. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  67649. var BABYLON;
  67650. (function (BABYLON) {
  67651. var DisplayPassPostProcess = /** @class */ (function (_super) {
  67652. __extends(DisplayPassPostProcess, _super);
  67653. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  67654. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  67655. }
  67656. return DisplayPassPostProcess;
  67657. }(BABYLON.PostProcess));
  67658. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  67659. })(BABYLON || (BABYLON = {}));
  67660. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  67661. var BABYLON;
  67662. (function (BABYLON) {
  67663. var HighlightsPostProcess = /** @class */ (function (_super) {
  67664. __extends(HighlightsPostProcess, _super);
  67665. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  67666. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  67667. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  67668. }
  67669. return HighlightsPostProcess;
  67670. }(BABYLON.PostProcess));
  67671. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  67672. })(BABYLON || (BABYLON = {}));
  67673. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  67674. var BABYLON;
  67675. (function (BABYLON) {
  67676. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  67677. __extends(ImageProcessingPostProcess, _super);
  67678. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  67679. if (camera === void 0) { camera = null; }
  67680. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  67681. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  67682. _this._fromLinearSpace = true;
  67683. /**
  67684. * Defines cache preventing GC.
  67685. */
  67686. _this._defines = {
  67687. IMAGEPROCESSING: false,
  67688. VIGNETTE: false,
  67689. VIGNETTEBLENDMODEMULTIPLY: false,
  67690. VIGNETTEBLENDMODEOPAQUE: false,
  67691. TONEMAPPING: false,
  67692. CONTRAST: false,
  67693. COLORCURVES: false,
  67694. COLORGRADING: false,
  67695. COLORGRADING3D: false,
  67696. FROMLINEARSPACE: false,
  67697. SAMPLER3DGREENDEPTH: false,
  67698. SAMPLER3DBGRMAP: false,
  67699. IMAGEPROCESSINGPOSTPROCESS: false,
  67700. EXPOSURE: false,
  67701. };
  67702. // Setup the configuration as forced by the constructor. This would then not force the
  67703. // scene materials output in linear space and let untouched the default forward pass.
  67704. if (imageProcessingConfiguration) {
  67705. imageProcessingConfiguration.applyByPostProcess = true;
  67706. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  67707. // This will cause the shader to be compiled
  67708. _this.fromLinearSpace = false;
  67709. }
  67710. else {
  67711. _this._attachImageProcessingConfiguration(null, true);
  67712. _this.imageProcessingConfiguration.applyByPostProcess = true;
  67713. }
  67714. _this.onApply = function (effect) {
  67715. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  67716. };
  67717. return _this;
  67718. }
  67719. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  67720. /**
  67721. * Gets the image processing configuration used either in this material.
  67722. */
  67723. get: function () {
  67724. return this._imageProcessingConfiguration;
  67725. },
  67726. /**
  67727. * Sets the Default image processing configuration used either in the this material.
  67728. *
  67729. * If sets to null, the scene one is in use.
  67730. */
  67731. set: function (value) {
  67732. this._attachImageProcessingConfiguration(value);
  67733. },
  67734. enumerable: true,
  67735. configurable: true
  67736. });
  67737. /**
  67738. * Attaches a new image processing configuration to the PBR Material.
  67739. * @param configuration
  67740. */
  67741. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  67742. var _this = this;
  67743. if (doNotBuild === void 0) { doNotBuild = false; }
  67744. if (configuration === this._imageProcessingConfiguration) {
  67745. return;
  67746. }
  67747. // Detaches observer.
  67748. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  67749. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  67750. }
  67751. // Pick the scene configuration if needed.
  67752. if (!configuration) {
  67753. var scene = null;
  67754. var engine = this.getEngine();
  67755. var camera = this.getCamera();
  67756. if (camera) {
  67757. scene = camera.getScene();
  67758. }
  67759. else if (engine && engine.scenes) {
  67760. var scenes = engine.scenes;
  67761. scene = scenes[scenes.length - 1];
  67762. }
  67763. else {
  67764. scene = BABYLON.Engine.LastCreatedScene;
  67765. }
  67766. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  67767. }
  67768. else {
  67769. this._imageProcessingConfiguration = configuration;
  67770. }
  67771. // Attaches observer.
  67772. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  67773. _this._updateParameters();
  67774. });
  67775. // Ensure the effect will be rebuilt.
  67776. if (!doNotBuild) {
  67777. this._updateParameters();
  67778. }
  67779. };
  67780. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  67781. /**
  67782. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  67783. */
  67784. get: function () {
  67785. return this.imageProcessingConfiguration.colorCurves;
  67786. },
  67787. /**
  67788. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  67789. */
  67790. set: function (value) {
  67791. this.imageProcessingConfiguration.colorCurves = value;
  67792. },
  67793. enumerable: true,
  67794. configurable: true
  67795. });
  67796. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  67797. /**
  67798. * Gets wether the color curves effect is enabled.
  67799. */
  67800. get: function () {
  67801. return this.imageProcessingConfiguration.colorCurvesEnabled;
  67802. },
  67803. /**
  67804. * Sets wether the color curves effect is enabled.
  67805. */
  67806. set: function (value) {
  67807. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  67808. },
  67809. enumerable: true,
  67810. configurable: true
  67811. });
  67812. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  67813. /**
  67814. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  67815. */
  67816. get: function () {
  67817. return this.imageProcessingConfiguration.colorGradingTexture;
  67818. },
  67819. /**
  67820. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  67821. */
  67822. set: function (value) {
  67823. this.imageProcessingConfiguration.colorGradingTexture = value;
  67824. },
  67825. enumerable: true,
  67826. configurable: true
  67827. });
  67828. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  67829. /**
  67830. * Gets wether the color grading effect is enabled.
  67831. */
  67832. get: function () {
  67833. return this.imageProcessingConfiguration.colorGradingEnabled;
  67834. },
  67835. /**
  67836. * Gets wether the color grading effect is enabled.
  67837. */
  67838. set: function (value) {
  67839. this.imageProcessingConfiguration.colorGradingEnabled = value;
  67840. },
  67841. enumerable: true,
  67842. configurable: true
  67843. });
  67844. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  67845. /**
  67846. * Gets exposure used in the effect.
  67847. */
  67848. get: function () {
  67849. return this.imageProcessingConfiguration.exposure;
  67850. },
  67851. /**
  67852. * Sets exposure used in the effect.
  67853. */
  67854. set: function (value) {
  67855. this.imageProcessingConfiguration.exposure = value;
  67856. },
  67857. enumerable: true,
  67858. configurable: true
  67859. });
  67860. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  67861. /**
  67862. * Gets wether tonemapping is enabled or not.
  67863. */
  67864. get: function () {
  67865. return this._imageProcessingConfiguration.toneMappingEnabled;
  67866. },
  67867. /**
  67868. * Sets wether tonemapping is enabled or not
  67869. */
  67870. set: function (value) {
  67871. this._imageProcessingConfiguration.toneMappingEnabled = value;
  67872. },
  67873. enumerable: true,
  67874. configurable: true
  67875. });
  67876. ;
  67877. ;
  67878. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  67879. /**
  67880. * Gets contrast used in the effect.
  67881. */
  67882. get: function () {
  67883. return this.imageProcessingConfiguration.contrast;
  67884. },
  67885. /**
  67886. * Sets contrast used in the effect.
  67887. */
  67888. set: function (value) {
  67889. this.imageProcessingConfiguration.contrast = value;
  67890. },
  67891. enumerable: true,
  67892. configurable: true
  67893. });
  67894. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  67895. /**
  67896. * Gets Vignette stretch size.
  67897. */
  67898. get: function () {
  67899. return this.imageProcessingConfiguration.vignetteStretch;
  67900. },
  67901. /**
  67902. * Sets Vignette stretch size.
  67903. */
  67904. set: function (value) {
  67905. this.imageProcessingConfiguration.vignetteStretch = value;
  67906. },
  67907. enumerable: true,
  67908. configurable: true
  67909. });
  67910. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  67911. /**
  67912. * Gets Vignette centre X Offset.
  67913. */
  67914. get: function () {
  67915. return this.imageProcessingConfiguration.vignetteCentreX;
  67916. },
  67917. /**
  67918. * Sets Vignette centre X Offset.
  67919. */
  67920. set: function (value) {
  67921. this.imageProcessingConfiguration.vignetteCentreX = value;
  67922. },
  67923. enumerable: true,
  67924. configurable: true
  67925. });
  67926. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  67927. /**
  67928. * Gets Vignette centre Y Offset.
  67929. */
  67930. get: function () {
  67931. return this.imageProcessingConfiguration.vignetteCentreY;
  67932. },
  67933. /**
  67934. * Sets Vignette centre Y Offset.
  67935. */
  67936. set: function (value) {
  67937. this.imageProcessingConfiguration.vignetteCentreY = value;
  67938. },
  67939. enumerable: true,
  67940. configurable: true
  67941. });
  67942. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  67943. /**
  67944. * Gets Vignette weight or intensity of the vignette effect.
  67945. */
  67946. get: function () {
  67947. return this.imageProcessingConfiguration.vignetteWeight;
  67948. },
  67949. /**
  67950. * Sets Vignette weight or intensity of the vignette effect.
  67951. */
  67952. set: function (value) {
  67953. this.imageProcessingConfiguration.vignetteWeight = value;
  67954. },
  67955. enumerable: true,
  67956. configurable: true
  67957. });
  67958. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  67959. /**
  67960. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  67961. * if vignetteEnabled is set to true.
  67962. */
  67963. get: function () {
  67964. return this.imageProcessingConfiguration.vignetteColor;
  67965. },
  67966. /**
  67967. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  67968. * if vignetteEnabled is set to true.
  67969. */
  67970. set: function (value) {
  67971. this.imageProcessingConfiguration.vignetteColor = value;
  67972. },
  67973. enumerable: true,
  67974. configurable: true
  67975. });
  67976. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  67977. /**
  67978. * Gets Camera field of view used by the Vignette effect.
  67979. */
  67980. get: function () {
  67981. return this.imageProcessingConfiguration.vignetteCameraFov;
  67982. },
  67983. /**
  67984. * Sets Camera field of view used by the Vignette effect.
  67985. */
  67986. set: function (value) {
  67987. this.imageProcessingConfiguration.vignetteCameraFov = value;
  67988. },
  67989. enumerable: true,
  67990. configurable: true
  67991. });
  67992. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  67993. /**
  67994. * Gets the vignette blend mode allowing different kind of effect.
  67995. */
  67996. get: function () {
  67997. return this.imageProcessingConfiguration.vignetteBlendMode;
  67998. },
  67999. /**
  68000. * Sets the vignette blend mode allowing different kind of effect.
  68001. */
  68002. set: function (value) {
  68003. this.imageProcessingConfiguration.vignetteBlendMode = value;
  68004. },
  68005. enumerable: true,
  68006. configurable: true
  68007. });
  68008. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  68009. /**
  68010. * Gets wether the vignette effect is enabled.
  68011. */
  68012. get: function () {
  68013. return this.imageProcessingConfiguration.vignetteEnabled;
  68014. },
  68015. /**
  68016. * Sets wether the vignette effect is enabled.
  68017. */
  68018. set: function (value) {
  68019. this.imageProcessingConfiguration.vignetteEnabled = value;
  68020. },
  68021. enumerable: true,
  68022. configurable: true
  68023. });
  68024. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  68025. /**
  68026. * Gets wether the input of the processing is in Gamma or Linear Space.
  68027. */
  68028. get: function () {
  68029. return this._fromLinearSpace;
  68030. },
  68031. /**
  68032. * Sets wether the input of the processing is in Gamma or Linear Space.
  68033. */
  68034. set: function (value) {
  68035. if (this._fromLinearSpace === value) {
  68036. return;
  68037. }
  68038. this._fromLinearSpace = value;
  68039. this._updateParameters();
  68040. },
  68041. enumerable: true,
  68042. configurable: true
  68043. });
  68044. ImageProcessingPostProcess.prototype.getClassName = function () {
  68045. return "ImageProcessingPostProcess";
  68046. };
  68047. ImageProcessingPostProcess.prototype._updateParameters = function () {
  68048. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  68049. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  68050. var defines = "";
  68051. for (var define in this._defines) {
  68052. if (this._defines[define]) {
  68053. defines += "#define " + define + ";\r\n";
  68054. }
  68055. }
  68056. var samplers = ["textureSampler"];
  68057. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  68058. var uniforms = ["scale"];
  68059. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  68060. this.updateEffect(defines, uniforms, samplers);
  68061. };
  68062. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  68063. _super.prototype.dispose.call(this, camera);
  68064. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  68065. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  68066. }
  68067. this.imageProcessingConfiguration.applyByPostProcess = false;
  68068. };
  68069. __decorate([
  68070. BABYLON.serialize()
  68071. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  68072. return ImageProcessingPostProcess;
  68073. }(BABYLON.PostProcess));
  68074. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  68075. })(BABYLON || (BABYLON = {}));
  68076. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  68077. var BABYLON;
  68078. (function (BABYLON) {
  68079. /**
  68080. * The Blur Post Process which blurs an image based on a kernel and direction.
  68081. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  68082. */
  68083. var BlurPostProcess = /** @class */ (function (_super) {
  68084. __extends(BlurPostProcess, _super);
  68085. /**
  68086. * Creates a new instance of @see BlurPostProcess
  68087. * @param name The name of the effect.
  68088. * @param direction The direction in which to blur the image.
  68089. * @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.
  68090. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  68091. * @param camera The camera to apply the render pass to.
  68092. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  68093. * @param engine The engine which the post process will be applied. (default: current engine)
  68094. * @param reusable If the post process can be reused on the same frame. (default: false)
  68095. * @param textureType Type of textures used when performing the post process. (default: 0)
  68096. */
  68097. function BlurPostProcess(name, /** The direction in which to blur the image. */ direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines) {
  68098. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  68099. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68100. if (defines === void 0) { defines = ""; }
  68101. 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;
  68102. _this.direction = direction;
  68103. _this._packedFloat = false;
  68104. _this._staticDefines = "";
  68105. _this._staticDefines = defines;
  68106. _this.onApplyObservable.add(function (effect) {
  68107. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  68108. });
  68109. _this.kernel = kernel;
  68110. return _this;
  68111. }
  68112. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  68113. /**
  68114. * Gets the length in pixels of the blur sample region
  68115. */
  68116. get: function () {
  68117. return this._idealKernel;
  68118. },
  68119. /**
  68120. * Sets the length in pixels of the blur sample region
  68121. */
  68122. set: function (v) {
  68123. if (this._idealKernel === v) {
  68124. return;
  68125. }
  68126. v = Math.max(v, 1);
  68127. this._idealKernel = v;
  68128. this._kernel = this._nearestBestKernel(v);
  68129. this._updateParameters();
  68130. },
  68131. enumerable: true,
  68132. configurable: true
  68133. });
  68134. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  68135. /**
  68136. * Gets wether or not the blur is unpacking/repacking floats
  68137. */
  68138. get: function () {
  68139. return this._packedFloat;
  68140. },
  68141. /**
  68142. * Sets wether or not the blur needs to unpack/repack floats
  68143. */
  68144. set: function (v) {
  68145. if (this._packedFloat === v) {
  68146. return;
  68147. }
  68148. this._packedFloat = v;
  68149. this._updateParameters();
  68150. },
  68151. enumerable: true,
  68152. configurable: true
  68153. });
  68154. BlurPostProcess.prototype._updateParameters = function () {
  68155. // Generate sampling offsets and weights
  68156. var N = this._kernel;
  68157. var centerIndex = (N - 1) / 2;
  68158. // Generate Gaussian sampling weights over kernel
  68159. var offsets = [];
  68160. var weights = [];
  68161. var totalWeight = 0;
  68162. for (var i = 0; i < N; i++) {
  68163. var u = i / (N - 1);
  68164. var w = this._gaussianWeight(u * 2.0 - 1);
  68165. offsets[i] = (i - centerIndex);
  68166. weights[i] = w;
  68167. totalWeight += w;
  68168. }
  68169. // Normalize weights
  68170. for (var i = 0; i < weights.length; i++) {
  68171. weights[i] /= totalWeight;
  68172. }
  68173. // Optimize: combine samples to take advantage of hardware linear sampling
  68174. // Walk from left to center, combining pairs (symmetrically)
  68175. var linearSamplingWeights = [];
  68176. var linearSamplingOffsets = [];
  68177. var linearSamplingMap = [];
  68178. for (var i = 0; i <= centerIndex; i += 2) {
  68179. var j = Math.min(i + 1, Math.floor(centerIndex));
  68180. var singleCenterSample = i === j;
  68181. if (singleCenterSample) {
  68182. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  68183. }
  68184. else {
  68185. var sharedCell = j === centerIndex;
  68186. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  68187. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  68188. if (offsetLinear === 0) {
  68189. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  68190. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  68191. }
  68192. else {
  68193. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  68194. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  68195. }
  68196. }
  68197. }
  68198. for (var i = 0; i < linearSamplingMap.length; i++) {
  68199. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  68200. linearSamplingWeights[i] = linearSamplingMap[i].w;
  68201. }
  68202. // Replace with optimized
  68203. offsets = linearSamplingOffsets;
  68204. weights = linearSamplingWeights;
  68205. // Generate shaders
  68206. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  68207. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  68208. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  68209. var defines = "";
  68210. defines += this._staticDefines;
  68211. for (var i = 0; i < varyingCount; i++) {
  68212. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  68213. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  68214. }
  68215. var depCount = 0;
  68216. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  68217. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  68218. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  68219. depCount++;
  68220. }
  68221. if (this.packedFloat) {
  68222. defines += "#define PACKEDFLOAT 1";
  68223. }
  68224. this.updateEffect(defines, null, null, {
  68225. varyingCount: varyingCount,
  68226. depCount: depCount
  68227. });
  68228. };
  68229. /**
  68230. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  68231. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  68232. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  68233. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  68234. * The gaps between physical kernels are compensated for in the weighting of the samples
  68235. * @param idealKernel Ideal blur kernel.
  68236. * @return Nearest best kernel.
  68237. */
  68238. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  68239. var v = Math.round(idealKernel);
  68240. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  68241. var k = _a[_i];
  68242. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  68243. return Math.max(k, 3);
  68244. }
  68245. }
  68246. return Math.max(v, 3);
  68247. };
  68248. /**
  68249. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  68250. * @param x The point on the Gaussian distribution to sample.
  68251. * @return the value of the Gaussian function at x.
  68252. */
  68253. BlurPostProcess.prototype._gaussianWeight = function (x) {
  68254. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  68255. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  68256. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  68257. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  68258. // truncated at around 1.3% of peak strength.
  68259. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  68260. var sigma = (1 / 3);
  68261. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  68262. var exponent = -((x * x) / (2.0 * sigma * sigma));
  68263. var weight = (1.0 / denominator) * Math.exp(exponent);
  68264. return weight;
  68265. };
  68266. /**
  68267. * Generates a string that can be used as a floating point number in GLSL.
  68268. * @param x Value to print.
  68269. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  68270. * @return GLSL float string.
  68271. */
  68272. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  68273. if (decimalFigures === void 0) { decimalFigures = 8; }
  68274. return x.toFixed(decimalFigures).replace(/0+$/, '');
  68275. };
  68276. return BlurPostProcess;
  68277. }(BABYLON.PostProcess));
  68278. BABYLON.BlurPostProcess = BlurPostProcess;
  68279. })(BABYLON || (BABYLON = {}));
  68280. //# sourceMappingURL=babylon.blurPostProcess.js.map
  68281. var BABYLON;
  68282. (function (BABYLON) {
  68283. var Bone = /** @class */ (function (_super) {
  68284. __extends(Bone, _super);
  68285. function Bone(name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  68286. if (parentBone === void 0) { parentBone = null; }
  68287. if (localMatrix === void 0) { localMatrix = null; }
  68288. if (restPose === void 0) { restPose = null; }
  68289. if (baseMatrix === void 0) { baseMatrix = null; }
  68290. if (index === void 0) { index = null; }
  68291. var _this = _super.call(this, name, skeleton.getScene()) || this;
  68292. _this.name = name;
  68293. _this.children = new Array();
  68294. _this.animations = new Array();
  68295. // Set this value to map this bone to a different index in the transform matrices.
  68296. // Set this value to -1 to exclude the bone from the transform matrices.
  68297. _this._index = null;
  68298. _this._worldTransform = new BABYLON.Matrix();
  68299. _this._absoluteTransform = new BABYLON.Matrix();
  68300. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  68301. _this._scaleMatrix = BABYLON.Matrix.Identity();
  68302. _this._scaleVector = BABYLON.Vector3.One();
  68303. _this._negateScaleChildren = BABYLON.Vector3.One();
  68304. _this._scalingDeterminant = 1;
  68305. _this._skeleton = skeleton;
  68306. _this._localMatrix = localMatrix ? localMatrix : BABYLON.Matrix.Identity();
  68307. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  68308. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  68309. _this._index = index;
  68310. skeleton.bones.push(_this);
  68311. _this.setParent(parentBone, false);
  68312. _this._updateDifferenceMatrix();
  68313. return _this;
  68314. }
  68315. Object.defineProperty(Bone.prototype, "_matrix", {
  68316. get: function () {
  68317. return this._localMatrix;
  68318. },
  68319. set: function (val) {
  68320. if (this._localMatrix) {
  68321. this._localMatrix.copyFrom(val);
  68322. }
  68323. else {
  68324. this._localMatrix = val;
  68325. }
  68326. },
  68327. enumerable: true,
  68328. configurable: true
  68329. });
  68330. // Members
  68331. Bone.prototype.getSkeleton = function () {
  68332. return this._skeleton;
  68333. };
  68334. Bone.prototype.getParent = function () {
  68335. return this._parent;
  68336. };
  68337. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  68338. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  68339. if (this._parent === parent) {
  68340. return;
  68341. }
  68342. if (this._parent) {
  68343. var index = this._parent.children.indexOf(this);
  68344. if (index !== -1) {
  68345. this._parent.children.splice(index, 1);
  68346. }
  68347. }
  68348. this._parent = parent;
  68349. if (this._parent) {
  68350. this._parent.children.push(this);
  68351. }
  68352. if (updateDifferenceMatrix) {
  68353. this._updateDifferenceMatrix();
  68354. }
  68355. };
  68356. Bone.prototype.getLocalMatrix = function () {
  68357. return this._localMatrix;
  68358. };
  68359. Bone.prototype.getBaseMatrix = function () {
  68360. return this._baseMatrix;
  68361. };
  68362. Bone.prototype.getRestPose = function () {
  68363. return this._restPose;
  68364. };
  68365. Bone.prototype.returnToRest = function () {
  68366. this.updateMatrix(this._restPose.clone());
  68367. };
  68368. Bone.prototype.getWorldMatrix = function () {
  68369. return this._worldTransform;
  68370. };
  68371. Bone.prototype.getInvertedAbsoluteTransform = function () {
  68372. return this._invertedAbsoluteTransform;
  68373. };
  68374. Bone.prototype.getAbsoluteTransform = function () {
  68375. return this._absoluteTransform;
  68376. };
  68377. Object.defineProperty(Bone.prototype, "position", {
  68378. // Properties (matches AbstractMesh properties)
  68379. get: function () {
  68380. return this.getPosition();
  68381. },
  68382. set: function (newPosition) {
  68383. this.setPosition(newPosition);
  68384. },
  68385. enumerable: true,
  68386. configurable: true
  68387. });
  68388. Object.defineProperty(Bone.prototype, "rotation", {
  68389. get: function () {
  68390. return this.getRotation();
  68391. },
  68392. set: function (newRotation) {
  68393. this.setRotation(newRotation);
  68394. },
  68395. enumerable: true,
  68396. configurable: true
  68397. });
  68398. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  68399. get: function () {
  68400. return this.getRotationQuaternion();
  68401. },
  68402. set: function (newRotation) {
  68403. this.setRotationQuaternion(newRotation);
  68404. },
  68405. enumerable: true,
  68406. configurable: true
  68407. });
  68408. Object.defineProperty(Bone.prototype, "scaling", {
  68409. get: function () {
  68410. return this.getScale();
  68411. },
  68412. set: function (newScaling) {
  68413. this.setScale(newScaling.x, newScaling.y, newScaling.z);
  68414. },
  68415. enumerable: true,
  68416. configurable: true
  68417. });
  68418. // Methods
  68419. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  68420. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  68421. this._baseMatrix = matrix.clone();
  68422. this._localMatrix = matrix.clone();
  68423. this._skeleton._markAsDirty();
  68424. if (updateDifferenceMatrix) {
  68425. this._updateDifferenceMatrix();
  68426. }
  68427. };
  68428. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  68429. if (!rootMatrix) {
  68430. rootMatrix = this._baseMatrix;
  68431. }
  68432. if (this._parent) {
  68433. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  68434. }
  68435. else {
  68436. this._absoluteTransform.copyFrom(rootMatrix);
  68437. }
  68438. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  68439. for (var index = 0; index < this.children.length; index++) {
  68440. this.children[index]._updateDifferenceMatrix();
  68441. }
  68442. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  68443. };
  68444. Bone.prototype.markAsDirty = function () {
  68445. this._currentRenderId++;
  68446. this._skeleton._markAsDirty();
  68447. };
  68448. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  68449. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  68450. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  68451. // all animation may be coming from a library skeleton, so may need to create animation
  68452. if (this.animations.length === 0) {
  68453. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  68454. this.animations[0].setKeys([]);
  68455. }
  68456. // get animation info / verify there is such a range from the source bone
  68457. var sourceRange = source.animations[0].getRange(rangeName);
  68458. if (!sourceRange) {
  68459. return false;
  68460. }
  68461. var from = sourceRange.from;
  68462. var to = sourceRange.to;
  68463. var sourceKeys = source.animations[0].getKeys();
  68464. // rescaling prep
  68465. var sourceBoneLength = source.length;
  68466. var sourceParent = source.getParent();
  68467. var parent = this.getParent();
  68468. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  68469. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  68470. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  68471. var destKeys = this.animations[0].getKeys();
  68472. // loop vars declaration
  68473. var orig;
  68474. var origTranslation;
  68475. var mat;
  68476. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  68477. orig = sourceKeys[key];
  68478. if (orig.frame >= from && orig.frame <= to) {
  68479. if (rescaleAsRequired) {
  68480. mat = orig.value.clone();
  68481. // scale based on parent ratio, when bone has parent
  68482. if (parentScalingReqd) {
  68483. origTranslation = mat.getTranslation();
  68484. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  68485. // scale based on skeleton dimension ratio when root bone, and value is passed
  68486. }
  68487. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  68488. origTranslation = mat.getTranslation();
  68489. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  68490. // use original when root bone, and no data for skelDimensionsRatio
  68491. }
  68492. else {
  68493. mat = orig.value;
  68494. }
  68495. }
  68496. else {
  68497. mat = orig.value;
  68498. }
  68499. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  68500. }
  68501. }
  68502. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  68503. return true;
  68504. };
  68505. /**
  68506. * Translate the bone in local or world space.
  68507. * @param vec The amount to translate the bone.
  68508. * @param space The space that the translation is in.
  68509. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  68510. */
  68511. Bone.prototype.translate = function (vec, space, mesh) {
  68512. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  68513. var lm = this.getLocalMatrix();
  68514. if (space == BABYLON.Space.LOCAL) {
  68515. lm.m[12] += vec.x;
  68516. lm.m[13] += vec.y;
  68517. lm.m[14] += vec.z;
  68518. }
  68519. else {
  68520. var wm = null;
  68521. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  68522. if (mesh) {
  68523. wm = mesh.getWorldMatrix();
  68524. }
  68525. this._skeleton.computeAbsoluteTransforms();
  68526. var tmat = Bone._tmpMats[0];
  68527. var tvec = Bone._tmpVecs[0];
  68528. if (this._parent) {
  68529. if (mesh && wm) {
  68530. tmat.copyFrom(this._parent.getAbsoluteTransform());
  68531. tmat.multiplyToRef(wm, tmat);
  68532. }
  68533. else {
  68534. tmat.copyFrom(this._parent.getAbsoluteTransform());
  68535. }
  68536. }
  68537. tmat.m[12] = 0;
  68538. tmat.m[13] = 0;
  68539. tmat.m[14] = 0;
  68540. tmat.invert();
  68541. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  68542. lm.m[12] += tvec.x;
  68543. lm.m[13] += tvec.y;
  68544. lm.m[14] += tvec.z;
  68545. }
  68546. this.markAsDirty();
  68547. };
  68548. /**
  68549. * Set the postion of the bone in local or world space.
  68550. * @param position The position to set the bone.
  68551. * @param space The space that the position is in.
  68552. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  68553. */
  68554. Bone.prototype.setPosition = function (position, space, mesh) {
  68555. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  68556. var lm = this.getLocalMatrix();
  68557. if (space == BABYLON.Space.LOCAL) {
  68558. lm.m[12] = position.x;
  68559. lm.m[13] = position.y;
  68560. lm.m[14] = position.z;
  68561. }
  68562. else {
  68563. var wm = null;
  68564. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  68565. if (mesh) {
  68566. wm = mesh.getWorldMatrix();
  68567. }
  68568. this._skeleton.computeAbsoluteTransforms();
  68569. var tmat = Bone._tmpMats[0];
  68570. var vec = Bone._tmpVecs[0];
  68571. if (this._parent) {
  68572. if (mesh && wm) {
  68573. tmat.copyFrom(this._parent.getAbsoluteTransform());
  68574. tmat.multiplyToRef(wm, tmat);
  68575. }
  68576. else {
  68577. tmat.copyFrom(this._parent.getAbsoluteTransform());
  68578. }
  68579. }
  68580. tmat.invert();
  68581. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  68582. lm.m[12] = vec.x;
  68583. lm.m[13] = vec.y;
  68584. lm.m[14] = vec.z;
  68585. }
  68586. this.markAsDirty();
  68587. };
  68588. /**
  68589. * Set the absolute postion of the bone (world space).
  68590. * @param position The position to set the bone.
  68591. * @param mesh The mesh that this bone is attached to.
  68592. */
  68593. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  68594. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  68595. };
  68596. /**
  68597. * Set the scale of the bone on the x, y and z axes.
  68598. * @param x The scale of the bone on the x axis.
  68599. * @param x The scale of the bone on the y axis.
  68600. * @param z The scale of the bone on the z axis.
  68601. * @param scaleChildren Set this to true if children of the bone should be scaled.
  68602. */
  68603. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  68604. if (scaleChildren === void 0) { scaleChildren = false; }
  68605. if (this.animations[0] && !this.animations[0].hasRunningRuntimeAnimations) {
  68606. if (!scaleChildren) {
  68607. this._negateScaleChildren.x = 1 / x;
  68608. this._negateScaleChildren.y = 1 / y;
  68609. this._negateScaleChildren.z = 1 / z;
  68610. }
  68611. this._syncScaleVector();
  68612. }
  68613. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  68614. };
  68615. /**
  68616. * Scale the bone on the x, y and z axes.
  68617. * @param x The amount to scale the bone on the x axis.
  68618. * @param x The amount to scale the bone on the y axis.
  68619. * @param z The amount to scale the bone on the z axis.
  68620. * @param scaleChildren Set this to true if children of the bone should be scaled.
  68621. */
  68622. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  68623. if (scaleChildren === void 0) { scaleChildren = false; }
  68624. var locMat = this.getLocalMatrix();
  68625. var origLocMat = Bone._tmpMats[0];
  68626. origLocMat.copyFrom(locMat);
  68627. var origLocMatInv = Bone._tmpMats[1];
  68628. origLocMatInv.copyFrom(origLocMat);
  68629. origLocMatInv.invert();
  68630. var scaleMat = Bone._tmpMats[2];
  68631. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  68632. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  68633. this._scaleVector.x *= x;
  68634. this._scaleVector.y *= y;
  68635. this._scaleVector.z *= z;
  68636. locMat.multiplyToRef(origLocMatInv, locMat);
  68637. locMat.multiplyToRef(scaleMat, locMat);
  68638. locMat.multiplyToRef(origLocMat, locMat);
  68639. var parent = this.getParent();
  68640. if (parent) {
  68641. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  68642. }
  68643. else {
  68644. this.getAbsoluteTransform().copyFrom(locMat);
  68645. }
  68646. var len = this.children.length;
  68647. scaleMat.invert();
  68648. for (var i = 0; i < len; i++) {
  68649. var child = this.children[i];
  68650. var cm = child.getLocalMatrix();
  68651. cm.multiplyToRef(scaleMat, cm);
  68652. var lm = child.getLocalMatrix();
  68653. lm.m[12] *= x;
  68654. lm.m[13] *= y;
  68655. lm.m[14] *= z;
  68656. }
  68657. this.computeAbsoluteTransforms();
  68658. if (scaleChildren) {
  68659. for (var i = 0; i < len; i++) {
  68660. this.children[i].scale(x, y, z, scaleChildren);
  68661. }
  68662. }
  68663. this.markAsDirty();
  68664. };
  68665. /**
  68666. * Set the yaw, pitch, and roll of the bone in local or world space.
  68667. * @param yaw The rotation of the bone on the y axis.
  68668. * @param pitch The rotation of the bone on the x axis.
  68669. * @param roll The rotation of the bone on the z axis.
  68670. * @param space The space that the axes of rotation are in.
  68671. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  68672. */
  68673. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  68674. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  68675. var rotMat = Bone._tmpMats[0];
  68676. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  68677. var rotMatInv = Bone._tmpMats[1];
  68678. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  68679. rotMatInv.multiplyToRef(rotMat, rotMat);
  68680. this._rotateWithMatrix(rotMat, space, mesh);
  68681. };
  68682. /**
  68683. * Rotate the bone on an axis in local or world space.
  68684. * @param axis The axis to rotate the bone on.
  68685. * @param amount The amount to rotate the bone.
  68686. * @param space The space that the axis is in.
  68687. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  68688. */
  68689. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  68690. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  68691. var rmat = Bone._tmpMats[0];
  68692. rmat.m[12] = 0;
  68693. rmat.m[13] = 0;
  68694. rmat.m[14] = 0;
  68695. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  68696. this._rotateWithMatrix(rmat, space, mesh);
  68697. };
  68698. /**
  68699. * Set the rotation of the bone to a particular axis angle in local or world space.
  68700. * @param axis The axis to rotate the bone on.
  68701. * @param angle The angle that the bone should be rotated to.
  68702. * @param space The space that the axis is in.
  68703. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  68704. */
  68705. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  68706. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  68707. var rotMat = Bone._tmpMats[0];
  68708. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  68709. var rotMatInv = Bone._tmpMats[1];
  68710. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  68711. rotMatInv.multiplyToRef(rotMat, rotMat);
  68712. this._rotateWithMatrix(rotMat, space, mesh);
  68713. };
  68714. /**
  68715. * Set the euler rotation of the bone in local of world space.
  68716. * @param rotation The euler rotation that the bone should be set to.
  68717. * @param space The space that the rotation is in.
  68718. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  68719. */
  68720. Bone.prototype.setRotation = function (rotation, space, mesh) {
  68721. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  68722. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  68723. };
  68724. /**
  68725. * Set the quaternion rotation of the bone in local of world space.
  68726. * @param quat The quaternion rotation that the bone should be set to.
  68727. * @param space The space that the rotation is in.
  68728. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  68729. */
  68730. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  68731. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  68732. var rotMatInv = Bone._tmpMats[0];
  68733. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  68734. var rotMat = Bone._tmpMats[1];
  68735. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  68736. rotMatInv.multiplyToRef(rotMat, rotMat);
  68737. this._rotateWithMatrix(rotMat, space, mesh);
  68738. };
  68739. /**
  68740. * Set the rotation matrix of the bone in local of world space.
  68741. * @param rotMat The rotation matrix that the bone should be set to.
  68742. * @param space The space that the rotation is in.
  68743. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  68744. */
  68745. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  68746. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  68747. var rotMatInv = Bone._tmpMats[0];
  68748. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  68749. var rotMat2 = Bone._tmpMats[1];
  68750. rotMat2.copyFrom(rotMat);
  68751. rotMatInv.multiplyToRef(rotMat, rotMat2);
  68752. this._rotateWithMatrix(rotMat2, space, mesh);
  68753. };
  68754. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  68755. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  68756. var lmat = this.getLocalMatrix();
  68757. var lx = lmat.m[12];
  68758. var ly = lmat.m[13];
  68759. var lz = lmat.m[14];
  68760. var parent = this.getParent();
  68761. var parentScale = Bone._tmpMats[3];
  68762. var parentScaleInv = Bone._tmpMats[4];
  68763. if (parent) {
  68764. if (space == BABYLON.Space.WORLD) {
  68765. if (mesh) {
  68766. parentScale.copyFrom(mesh.getWorldMatrix());
  68767. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  68768. }
  68769. else {
  68770. parentScale.copyFrom(parent.getAbsoluteTransform());
  68771. }
  68772. }
  68773. else {
  68774. parentScale = parent._scaleMatrix;
  68775. }
  68776. parentScaleInv.copyFrom(parentScale);
  68777. parentScaleInv.invert();
  68778. lmat.multiplyToRef(parentScale, lmat);
  68779. lmat.multiplyToRef(rmat, lmat);
  68780. lmat.multiplyToRef(parentScaleInv, lmat);
  68781. }
  68782. else {
  68783. if (space == BABYLON.Space.WORLD && mesh) {
  68784. parentScale.copyFrom(mesh.getWorldMatrix());
  68785. parentScaleInv.copyFrom(parentScale);
  68786. parentScaleInv.invert();
  68787. lmat.multiplyToRef(parentScale, lmat);
  68788. lmat.multiplyToRef(rmat, lmat);
  68789. lmat.multiplyToRef(parentScaleInv, lmat);
  68790. }
  68791. else {
  68792. lmat.multiplyToRef(rmat, lmat);
  68793. }
  68794. }
  68795. lmat.m[12] = lx;
  68796. lmat.m[13] = ly;
  68797. lmat.m[14] = lz;
  68798. this.computeAbsoluteTransforms();
  68799. this.markAsDirty();
  68800. };
  68801. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  68802. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  68803. if (space == BABYLON.Space.WORLD) {
  68804. var scaleMatrix = Bone._tmpMats[2];
  68805. scaleMatrix.copyFrom(this._scaleMatrix);
  68806. rotMatInv.copyFrom(this.getAbsoluteTransform());
  68807. if (mesh) {
  68808. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  68809. var meshScale = Bone._tmpMats[3];
  68810. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  68811. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  68812. }
  68813. rotMatInv.invert();
  68814. scaleMatrix.m[0] *= this._scalingDeterminant;
  68815. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  68816. }
  68817. else {
  68818. rotMatInv.copyFrom(this.getLocalMatrix());
  68819. rotMatInv.invert();
  68820. var scaleMatrix = Bone._tmpMats[2];
  68821. scaleMatrix.copyFrom(this._scaleMatrix);
  68822. if (this._parent) {
  68823. var pscaleMatrix = Bone._tmpMats[3];
  68824. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  68825. pscaleMatrix.invert();
  68826. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  68827. }
  68828. else {
  68829. scaleMatrix.m[0] *= this._scalingDeterminant;
  68830. }
  68831. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  68832. }
  68833. };
  68834. /**
  68835. * Get the scale of the bone
  68836. * @returns the scale of the bone
  68837. */
  68838. Bone.prototype.getScale = function () {
  68839. return this._scaleVector.clone();
  68840. };
  68841. /**
  68842. * Copy the scale of the bone to a vector3.
  68843. * @param result The vector3 to copy the scale to
  68844. */
  68845. Bone.prototype.getScaleToRef = function (result) {
  68846. result.copyFrom(this._scaleVector);
  68847. };
  68848. /**
  68849. * Get the position of the bone in local or world space.
  68850. * @param space The space that the returned position is in.
  68851. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  68852. * @returns The position of the bone
  68853. */
  68854. Bone.prototype.getPosition = function (space, mesh) {
  68855. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  68856. if (mesh === void 0) { mesh = null; }
  68857. var pos = BABYLON.Vector3.Zero();
  68858. this.getPositionToRef(space, mesh, pos);
  68859. return pos;
  68860. };
  68861. /**
  68862. * Copy the position of the bone to a vector3 in local or world space.
  68863. * @param space The space that the returned position is in.
  68864. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  68865. * @param result The vector3 to copy the position to.
  68866. */
  68867. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  68868. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  68869. if (space == BABYLON.Space.LOCAL) {
  68870. var lm = this.getLocalMatrix();
  68871. result.x = lm.m[12];
  68872. result.y = lm.m[13];
  68873. result.z = lm.m[14];
  68874. }
  68875. else {
  68876. var wm = null;
  68877. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  68878. if (mesh) {
  68879. wm = mesh.getWorldMatrix();
  68880. }
  68881. this._skeleton.computeAbsoluteTransforms();
  68882. var tmat = Bone._tmpMats[0];
  68883. if (mesh && wm) {
  68884. tmat.copyFrom(this.getAbsoluteTransform());
  68885. tmat.multiplyToRef(wm, tmat);
  68886. }
  68887. else {
  68888. tmat = this.getAbsoluteTransform();
  68889. }
  68890. result.x = tmat.m[12];
  68891. result.y = tmat.m[13];
  68892. result.z = tmat.m[14];
  68893. }
  68894. };
  68895. /**
  68896. * Get the absolute position of the bone (world space).
  68897. * @param mesh The mesh that this bone is attached to.
  68898. * @returns The absolute position of the bone
  68899. */
  68900. Bone.prototype.getAbsolutePosition = function (mesh) {
  68901. if (mesh === void 0) { mesh = null; }
  68902. var pos = BABYLON.Vector3.Zero();
  68903. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  68904. return pos;
  68905. };
  68906. /**
  68907. * Copy the absolute position of the bone (world space) to the result param.
  68908. * @param mesh The mesh that this bone is attached to.
  68909. * @param result The vector3 to copy the absolute position to.
  68910. */
  68911. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  68912. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  68913. };
  68914. /**
  68915. * Compute the absolute transforms of this bone and its children.
  68916. */
  68917. Bone.prototype.computeAbsoluteTransforms = function () {
  68918. if (this._parent) {
  68919. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  68920. }
  68921. else {
  68922. this._absoluteTransform.copyFrom(this._localMatrix);
  68923. var poseMatrix = this._skeleton.getPoseMatrix();
  68924. if (poseMatrix) {
  68925. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  68926. }
  68927. }
  68928. var children = this.children;
  68929. var len = children.length;
  68930. for (var i = 0; i < len; i++) {
  68931. children[i].computeAbsoluteTransforms();
  68932. }
  68933. };
  68934. Bone.prototype._syncScaleVector = function () {
  68935. var lm = this.getLocalMatrix();
  68936. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  68937. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  68938. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  68939. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  68940. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  68941. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  68942. this._scaleVector.x = xs * Math.sqrt(xsq);
  68943. this._scaleVector.y = ys * Math.sqrt(ysq);
  68944. this._scaleVector.z = zs * Math.sqrt(zsq);
  68945. if (this._parent) {
  68946. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  68947. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  68948. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  68949. }
  68950. BABYLON.Matrix.FromValuesToRef(this._scaleVector.x, 0, 0, 0, 0, this._scaleVector.y, 0, 0, 0, 0, this._scaleVector.z, 0, 0, 0, 0, 1, this._scaleMatrix);
  68951. };
  68952. /**
  68953. * Get the world direction from an axis that is in the local space of the bone.
  68954. * @param localAxis The local direction that is used to compute the world direction.
  68955. * @param mesh The mesh that this bone is attached to.
  68956. * @returns The world direction
  68957. */
  68958. Bone.prototype.getDirection = function (localAxis, mesh) {
  68959. if (mesh === void 0) { mesh = null; }
  68960. var result = BABYLON.Vector3.Zero();
  68961. this.getDirectionToRef(localAxis, mesh, result);
  68962. return result;
  68963. };
  68964. /**
  68965. * Copy the world direction to a vector3 from an axis that is in the local space of the bone.
  68966. * @param localAxis The local direction that is used to compute the world direction.
  68967. * @param mesh The mesh that this bone is attached to.
  68968. * @param result The vector3 that the world direction will be copied to.
  68969. */
  68970. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  68971. if (mesh === void 0) { mesh = null; }
  68972. var wm = null;
  68973. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  68974. if (mesh) {
  68975. wm = mesh.getWorldMatrix();
  68976. }
  68977. this._skeleton.computeAbsoluteTransforms();
  68978. var mat = Bone._tmpMats[0];
  68979. mat.copyFrom(this.getAbsoluteTransform());
  68980. if (mesh && wm) {
  68981. mat.multiplyToRef(wm, mat);
  68982. }
  68983. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  68984. result.normalize();
  68985. };
  68986. /**
  68987. * Get the euler rotation of the bone in local or world space.
  68988. * @param space The space that the rotation should be in.
  68989. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  68990. * @returns The euler rotation
  68991. */
  68992. Bone.prototype.getRotation = function (space, mesh) {
  68993. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  68994. if (mesh === void 0) { mesh = null; }
  68995. var result = BABYLON.Vector3.Zero();
  68996. this.getRotationToRef(space, mesh, result);
  68997. return result;
  68998. };
  68999. /**
  69000. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space.
  69001. * @param space The space that the rotation should be in.
  69002. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  69003. * @param result The vector3 that the rotation should be copied to.
  69004. */
  69005. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  69006. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  69007. if (mesh === void 0) { mesh = null; }
  69008. var quat = Bone._tmpQuat;
  69009. this.getRotationQuaternionToRef(space, mesh, quat);
  69010. quat.toEulerAnglesToRef(result);
  69011. };
  69012. /**
  69013. * Get the quaternion rotation of the bone in either local or world space.
  69014. * @param space The space that the rotation should be in.
  69015. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  69016. * @returns The quaternion rotation
  69017. */
  69018. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  69019. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  69020. if (mesh === void 0) { mesh = null; }
  69021. var result = BABYLON.Quaternion.Identity();
  69022. this.getRotationQuaternionToRef(space, mesh, result);
  69023. return result;
  69024. };
  69025. /**
  69026. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space.
  69027. * @param space The space that the rotation should be in.
  69028. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  69029. * @param result The quaternion that the rotation should be copied to.
  69030. */
  69031. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  69032. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  69033. if (mesh === void 0) { mesh = null; }
  69034. if (space == BABYLON.Space.LOCAL) {
  69035. this.getLocalMatrix().decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  69036. }
  69037. else {
  69038. var mat = Bone._tmpMats[0];
  69039. var amat = this.getAbsoluteTransform();
  69040. if (mesh) {
  69041. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  69042. }
  69043. else {
  69044. mat.copyFrom(amat);
  69045. }
  69046. mat.m[0] *= this._scalingDeterminant;
  69047. mat.m[1] *= this._scalingDeterminant;
  69048. mat.m[2] *= this._scalingDeterminant;
  69049. mat.decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  69050. }
  69051. };
  69052. /**
  69053. * Get the rotation matrix of the bone in local or world space.
  69054. * @param space The space that the rotation should be in.
  69055. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  69056. * @returns The rotation matrix
  69057. */
  69058. Bone.prototype.getRotationMatrix = function (space, mesh) {
  69059. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  69060. var result = BABYLON.Matrix.Identity();
  69061. this.getRotationMatrixToRef(space, mesh, result);
  69062. return result;
  69063. };
  69064. /**
  69065. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space.
  69066. * @param space The space that the rotation should be in.
  69067. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  69068. * @param result The quaternion that the rotation should be copied to.
  69069. */
  69070. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  69071. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  69072. if (space == BABYLON.Space.LOCAL) {
  69073. this.getLocalMatrix().getRotationMatrixToRef(result);
  69074. }
  69075. else {
  69076. var mat = Bone._tmpMats[0];
  69077. var amat = this.getAbsoluteTransform();
  69078. if (mesh) {
  69079. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  69080. }
  69081. else {
  69082. mat.copyFrom(amat);
  69083. }
  69084. mat.m[0] *= this._scalingDeterminant;
  69085. mat.m[1] *= this._scalingDeterminant;
  69086. mat.m[2] *= this._scalingDeterminant;
  69087. mat.getRotationMatrixToRef(result);
  69088. }
  69089. };
  69090. /**
  69091. * Get the world position of a point that is in the local space of the bone.
  69092. * @param position The local position
  69093. * @param mesh The mesh that this bone is attached to.
  69094. * @returns The world position
  69095. */
  69096. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  69097. if (mesh === void 0) { mesh = null; }
  69098. var result = BABYLON.Vector3.Zero();
  69099. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  69100. return result;
  69101. };
  69102. /**
  69103. * Get the world position of a point that is in the local space of the bone and copy it to the result param.
  69104. * @param position The local position
  69105. * @param mesh The mesh that this bone is attached to.
  69106. * @param result The vector3 that the world position should be copied to.
  69107. */
  69108. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  69109. if (mesh === void 0) { mesh = null; }
  69110. var wm = null;
  69111. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  69112. if (mesh) {
  69113. wm = mesh.getWorldMatrix();
  69114. }
  69115. this._skeleton.computeAbsoluteTransforms();
  69116. var tmat = Bone._tmpMats[0];
  69117. if (mesh && wm) {
  69118. tmat.copyFrom(this.getAbsoluteTransform());
  69119. tmat.multiplyToRef(wm, tmat);
  69120. }
  69121. else {
  69122. tmat = this.getAbsoluteTransform();
  69123. }
  69124. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  69125. };
  69126. /**
  69127. * Get the local position of a point that is in world space.
  69128. * @param position The world position
  69129. * @param mesh The mesh that this bone is attached to.
  69130. * @returns The local position
  69131. */
  69132. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  69133. if (mesh === void 0) { mesh = null; }
  69134. var result = BABYLON.Vector3.Zero();
  69135. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  69136. return result;
  69137. };
  69138. /**
  69139. * Get the local position of a point that is in world space and copy it to the result param.
  69140. * @param position The world position
  69141. * @param mesh The mesh that this bone is attached to.
  69142. * @param result The vector3 that the local position should be copied to.
  69143. */
  69144. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  69145. if (mesh === void 0) { mesh = null; }
  69146. var wm = null;
  69147. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  69148. if (mesh) {
  69149. wm = mesh.getWorldMatrix();
  69150. }
  69151. this._skeleton.computeAbsoluteTransforms();
  69152. var tmat = Bone._tmpMats[0];
  69153. tmat.copyFrom(this.getAbsoluteTransform());
  69154. if (mesh && wm) {
  69155. tmat.multiplyToRef(wm, tmat);
  69156. }
  69157. tmat.invert();
  69158. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  69159. };
  69160. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  69161. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  69162. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  69163. return Bone;
  69164. }(BABYLON.Node));
  69165. BABYLON.Bone = Bone;
  69166. })(BABYLON || (BABYLON = {}));
  69167. //# sourceMappingURL=babylon.bone.js.map
  69168. var BABYLON;
  69169. (function (BABYLON) {
  69170. var BoneIKController = /** @class */ (function () {
  69171. function BoneIKController(mesh, bone, options) {
  69172. this.targetPosition = BABYLON.Vector3.Zero();
  69173. this.poleTargetPosition = BABYLON.Vector3.Zero();
  69174. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  69175. this.poleAngle = 0;
  69176. this.slerpAmount = 1;
  69177. this._bone1Quat = BABYLON.Quaternion.Identity();
  69178. this._bone1Mat = BABYLON.Matrix.Identity();
  69179. this._bone2Ang = Math.PI;
  69180. this._maxAngle = Math.PI;
  69181. this._rightHandedSystem = false;
  69182. this._bendAxis = BABYLON.Vector3.Right();
  69183. this._slerping = false;
  69184. this._adjustRoll = 0;
  69185. this._bone2 = bone;
  69186. this._bone1 = bone.getParent();
  69187. if (!this._bone1) {
  69188. return;
  69189. }
  69190. this.mesh = mesh;
  69191. var bonePos = bone.getPosition();
  69192. if (bone.getAbsoluteTransform().determinant() > 0) {
  69193. this._rightHandedSystem = true;
  69194. this._bendAxis.x = 0;
  69195. this._bendAxis.y = 0;
  69196. this._bendAxis.z = -1;
  69197. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  69198. this._adjustRoll = Math.PI * .5;
  69199. this._bendAxis.z = 1;
  69200. }
  69201. }
  69202. if (this._bone1.length) {
  69203. var boneScale1 = this._bone1.getScale();
  69204. var boneScale2 = this._bone2.getScale();
  69205. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  69206. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  69207. }
  69208. else if (this._bone1.children[0]) {
  69209. mesh.computeWorldMatrix(true);
  69210. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  69211. var pos2 = this._bone2.getAbsolutePosition(mesh);
  69212. var pos3 = this._bone1.getAbsolutePosition(mesh);
  69213. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  69214. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  69215. }
  69216. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  69217. this.maxAngle = Math.PI;
  69218. if (options) {
  69219. if (options.targetMesh) {
  69220. this.targetMesh = options.targetMesh;
  69221. this.targetMesh.computeWorldMatrix(true);
  69222. }
  69223. if (options.poleTargetMesh) {
  69224. this.poleTargetMesh = options.poleTargetMesh;
  69225. this.poleTargetMesh.computeWorldMatrix(true);
  69226. }
  69227. else if (options.poleTargetBone) {
  69228. this.poleTargetBone = options.poleTargetBone;
  69229. }
  69230. else if (this._bone1.getParent()) {
  69231. this.poleTargetBone = this._bone1.getParent();
  69232. }
  69233. if (options.poleTargetLocalOffset) {
  69234. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  69235. }
  69236. if (options.poleAngle) {
  69237. this.poleAngle = options.poleAngle;
  69238. }
  69239. if (options.bendAxis) {
  69240. this._bendAxis.copyFrom(options.bendAxis);
  69241. }
  69242. if (options.maxAngle) {
  69243. this.maxAngle = options.maxAngle;
  69244. }
  69245. if (options.slerpAmount) {
  69246. this.slerpAmount = options.slerpAmount;
  69247. }
  69248. }
  69249. }
  69250. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  69251. get: function () {
  69252. return this._maxAngle;
  69253. },
  69254. set: function (value) {
  69255. this._setMaxAngle(value);
  69256. },
  69257. enumerable: true,
  69258. configurable: true
  69259. });
  69260. BoneIKController.prototype._setMaxAngle = function (ang) {
  69261. if (ang < 0) {
  69262. ang = 0;
  69263. }
  69264. if (ang > Math.PI || ang == undefined) {
  69265. ang = Math.PI;
  69266. }
  69267. this._maxAngle = ang;
  69268. var a = this._bone1Length;
  69269. var b = this._bone2Length;
  69270. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  69271. };
  69272. BoneIKController.prototype.update = function () {
  69273. var bone1 = this._bone1;
  69274. if (!bone1) {
  69275. return;
  69276. }
  69277. var target = this.targetPosition;
  69278. var poleTarget = this.poleTargetPosition;
  69279. var mat1 = BoneIKController._tmpMats[0];
  69280. var mat2 = BoneIKController._tmpMats[1];
  69281. if (this.targetMesh) {
  69282. target.copyFrom(this.targetMesh.getAbsolutePosition());
  69283. }
  69284. if (this.poleTargetBone) {
  69285. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  69286. }
  69287. else if (this.poleTargetMesh) {
  69288. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  69289. }
  69290. var bonePos = BoneIKController._tmpVecs[0];
  69291. var zaxis = BoneIKController._tmpVecs[1];
  69292. var xaxis = BoneIKController._tmpVecs[2];
  69293. var yaxis = BoneIKController._tmpVecs[3];
  69294. var upAxis = BoneIKController._tmpVecs[4];
  69295. var _tmpQuat = BoneIKController._tmpQuat;
  69296. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  69297. poleTarget.subtractToRef(bonePos, upAxis);
  69298. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  69299. upAxis.y = 1;
  69300. }
  69301. else {
  69302. upAxis.normalize();
  69303. }
  69304. target.subtractToRef(bonePos, yaxis);
  69305. yaxis.normalize();
  69306. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  69307. zaxis.normalize();
  69308. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  69309. xaxis.normalize();
  69310. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  69311. var a = this._bone1Length;
  69312. var b = this._bone2Length;
  69313. var c = BABYLON.Vector3.Distance(bonePos, target);
  69314. if (this._maxReach > 0) {
  69315. c = Math.min(this._maxReach, c);
  69316. }
  69317. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  69318. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  69319. if (acosa > 1) {
  69320. acosa = 1;
  69321. }
  69322. if (acosb > 1) {
  69323. acosb = 1;
  69324. }
  69325. if (acosa < -1) {
  69326. acosa = -1;
  69327. }
  69328. if (acosb < -1) {
  69329. acosb = -1;
  69330. }
  69331. var angA = Math.acos(acosa);
  69332. var angB = Math.acos(acosb);
  69333. var angC = -angA - angB;
  69334. if (this._rightHandedSystem) {
  69335. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  69336. mat2.multiplyToRef(mat1, mat1);
  69337. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  69338. mat2.multiplyToRef(mat1, mat1);
  69339. }
  69340. else {
  69341. var _tmpVec = BoneIKController._tmpVecs[5];
  69342. _tmpVec.copyFrom(this._bendAxis);
  69343. _tmpVec.x *= -1;
  69344. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  69345. mat2.multiplyToRef(mat1, mat1);
  69346. }
  69347. if (this.poleAngle) {
  69348. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  69349. mat1.multiplyToRef(mat2, mat1);
  69350. }
  69351. if (this._bone1) {
  69352. if (this.slerpAmount < 1) {
  69353. if (!this._slerping) {
  69354. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  69355. }
  69356. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  69357. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  69358. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  69359. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  69360. this._slerping = true;
  69361. }
  69362. else {
  69363. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  69364. this._bone1Mat.copyFrom(mat1);
  69365. this._slerping = false;
  69366. }
  69367. }
  69368. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  69369. this._bone2Ang = angC;
  69370. };
  69371. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  69372. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  69373. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  69374. return BoneIKController;
  69375. }());
  69376. BABYLON.BoneIKController = BoneIKController;
  69377. })(BABYLON || (BABYLON = {}));
  69378. //# sourceMappingURL=babylon.boneIKController.js.map
  69379. var BABYLON;
  69380. (function (BABYLON) {
  69381. var BoneLookController = /** @class */ (function () {
  69382. /**
  69383. * Create a BoneLookController
  69384. * @param mesh the mesh that the bone belongs to
  69385. * @param bone the bone that will be looking to the target
  69386. * @param target the target Vector3 to look at
  69387. * @param settings optional settings:
  69388. * - maxYaw: the maximum angle the bone will yaw to
  69389. * - minYaw: the minimum angle the bone will yaw to
  69390. * - maxPitch: the maximum angle the bone will pitch to
  69391. * - minPitch: the minimum angle the bone will yaw to
  69392. * - slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  69393. * - upAxis: the up axis of the coordinate system
  69394. * - upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  69395. * - yawAxis: set yawAxis if the bone does not yaw on the y axis
  69396. * - pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  69397. * - adjustYaw: used to make an adjustment to the yaw of the bone
  69398. * - adjustPitch: used to make an adjustment to the pitch of the bone
  69399. * - adjustRoll: used to make an adjustment to the roll of the bone
  69400. **/
  69401. function BoneLookController(mesh, bone, target, options) {
  69402. /**
  69403. * The up axis of the coordinate system that is used when the bone is rotated.
  69404. */
  69405. this.upAxis = BABYLON.Vector3.Up();
  69406. /**
  69407. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  69408. */
  69409. this.upAxisSpace = BABYLON.Space.LOCAL;
  69410. /**
  69411. * Used to make an adjustment to the yaw of the bone.
  69412. */
  69413. this.adjustYaw = 0;
  69414. /**
  69415. * Used to make an adjustment to the pitch of the bone.
  69416. */
  69417. this.adjustPitch = 0;
  69418. /**
  69419. * Used to make an adjustment to the roll of the bone.
  69420. */
  69421. this.adjustRoll = 0;
  69422. /**
  69423. * 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).
  69424. */
  69425. this.slerpAmount = 1;
  69426. this._boneQuat = BABYLON.Quaternion.Identity();
  69427. this._slerping = false;
  69428. this._firstFrameSkipped = false;
  69429. this._fowardAxis = BABYLON.Vector3.Forward();
  69430. this.mesh = mesh;
  69431. this.bone = bone;
  69432. this.target = target;
  69433. if (options) {
  69434. if (options.adjustYaw) {
  69435. this.adjustYaw = options.adjustYaw;
  69436. }
  69437. if (options.adjustPitch) {
  69438. this.adjustPitch = options.adjustPitch;
  69439. }
  69440. if (options.adjustRoll) {
  69441. this.adjustRoll = options.adjustRoll;
  69442. }
  69443. if (options.maxYaw != null) {
  69444. this.maxYaw = options.maxYaw;
  69445. }
  69446. else {
  69447. this.maxYaw = Math.PI;
  69448. }
  69449. if (options.minYaw != null) {
  69450. this.minYaw = options.minYaw;
  69451. }
  69452. else {
  69453. this.minYaw = -Math.PI;
  69454. }
  69455. if (options.maxPitch != null) {
  69456. this.maxPitch = options.maxPitch;
  69457. }
  69458. else {
  69459. this.maxPitch = Math.PI;
  69460. }
  69461. if (options.minPitch != null) {
  69462. this.minPitch = options.minPitch;
  69463. }
  69464. else {
  69465. this.minPitch = -Math.PI;
  69466. }
  69467. if (options.slerpAmount != null) {
  69468. this.slerpAmount = options.slerpAmount;
  69469. }
  69470. if (options.upAxis != null) {
  69471. this.upAxis = options.upAxis;
  69472. }
  69473. if (options.upAxisSpace != null) {
  69474. this.upAxisSpace = options.upAxisSpace;
  69475. }
  69476. if (options.yawAxis != null || options.pitchAxis != null) {
  69477. var newYawAxis = BABYLON.Axis.Y;
  69478. var newPitchAxis = BABYLON.Axis.X;
  69479. if (options.yawAxis != null) {
  69480. newYawAxis = options.yawAxis.clone();
  69481. newYawAxis.normalize();
  69482. }
  69483. if (options.pitchAxis != null) {
  69484. newPitchAxis = options.pitchAxis.clone();
  69485. newPitchAxis.normalize();
  69486. }
  69487. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  69488. this._transformYawPitch = BABYLON.Matrix.Identity();
  69489. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  69490. this._transformYawPitchInv = this._transformYawPitch.clone();
  69491. this._transformYawPitch.invert();
  69492. }
  69493. }
  69494. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  69495. this.upAxisSpace = BABYLON.Space.LOCAL;
  69496. }
  69497. }
  69498. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  69499. /**
  69500. * Get/set the minimum yaw angle that the bone can look to.
  69501. */
  69502. get: function () {
  69503. return this._minYaw;
  69504. },
  69505. set: function (value) {
  69506. this._minYaw = value;
  69507. this._minYawSin = Math.sin(value);
  69508. this._minYawCos = Math.cos(value);
  69509. if (this._maxYaw != null) {
  69510. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  69511. this._yawRange = this._maxYaw - this._minYaw;
  69512. }
  69513. },
  69514. enumerable: true,
  69515. configurable: true
  69516. });
  69517. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  69518. /**
  69519. * Get/set the maximum yaw angle that the bone can look to.
  69520. */
  69521. get: function () {
  69522. return this._maxYaw;
  69523. },
  69524. set: function (value) {
  69525. this._maxYaw = value;
  69526. this._maxYawSin = Math.sin(value);
  69527. this._maxYawCos = Math.cos(value);
  69528. if (this._minYaw != null) {
  69529. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  69530. this._yawRange = this._maxYaw - this._minYaw;
  69531. }
  69532. },
  69533. enumerable: true,
  69534. configurable: true
  69535. });
  69536. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  69537. /**
  69538. * Get/set the minimum pitch angle that the bone can look to.
  69539. */
  69540. get: function () {
  69541. return this._minPitch;
  69542. },
  69543. set: function (value) {
  69544. this._minPitch = value;
  69545. this._minPitchTan = Math.tan(value);
  69546. },
  69547. enumerable: true,
  69548. configurable: true
  69549. });
  69550. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  69551. /**
  69552. * Get/set the maximum pitch angle that the bone can look to.
  69553. */
  69554. get: function () {
  69555. return this._maxPitch;
  69556. },
  69557. set: function (value) {
  69558. this._maxPitch = value;
  69559. this._maxPitchTan = Math.tan(value);
  69560. },
  69561. enumerable: true,
  69562. configurable: true
  69563. });
  69564. /**
  69565. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()).
  69566. */
  69567. BoneLookController.prototype.update = function () {
  69568. //skip the first frame when slerping so that the mesh rotation is correct
  69569. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  69570. this._firstFrameSkipped = true;
  69571. return;
  69572. }
  69573. var bone = this.bone;
  69574. var bonePos = BoneLookController._tmpVecs[0];
  69575. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  69576. var target = this.target;
  69577. var _tmpMat1 = BoneLookController._tmpMats[0];
  69578. var _tmpMat2 = BoneLookController._tmpMats[1];
  69579. var mesh = this.mesh;
  69580. var parentBone = bone.getParent();
  69581. var upAxis = BoneLookController._tmpVecs[1];
  69582. upAxis.copyFrom(this.upAxis);
  69583. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  69584. if (this._transformYawPitch) {
  69585. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  69586. }
  69587. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  69588. }
  69589. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  69590. mesh.getDirectionToRef(upAxis, upAxis);
  69591. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  69592. upAxis.normalize();
  69593. }
  69594. }
  69595. var checkYaw = false;
  69596. var checkPitch = false;
  69597. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  69598. checkYaw = true;
  69599. }
  69600. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  69601. checkPitch = true;
  69602. }
  69603. if (checkYaw || checkPitch) {
  69604. var spaceMat = BoneLookController._tmpMats[2];
  69605. var spaceMatInv = BoneLookController._tmpMats[3];
  69606. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  69607. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  69608. }
  69609. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  69610. spaceMat.copyFrom(mesh.getWorldMatrix());
  69611. }
  69612. else {
  69613. var forwardAxis = BoneLookController._tmpVecs[2];
  69614. forwardAxis.copyFrom(this._fowardAxis);
  69615. if (this._transformYawPitch) {
  69616. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  69617. }
  69618. if (parentBone) {
  69619. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  69620. }
  69621. else {
  69622. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  69623. }
  69624. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  69625. rightAxis.normalize();
  69626. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  69627. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  69628. }
  69629. spaceMat.invertToRef(spaceMatInv);
  69630. var xzlen = null;
  69631. if (checkPitch) {
  69632. var localTarget = BoneLookController._tmpVecs[3];
  69633. target.subtractToRef(bonePos, localTarget);
  69634. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  69635. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  69636. var pitch = Math.atan2(localTarget.y, xzlen);
  69637. var newPitch = pitch;
  69638. if (pitch > this._maxPitch) {
  69639. localTarget.y = this._maxPitchTan * xzlen;
  69640. newPitch = this._maxPitch;
  69641. }
  69642. else if (pitch < this._minPitch) {
  69643. localTarget.y = this._minPitchTan * xzlen;
  69644. newPitch = this._minPitch;
  69645. }
  69646. if (pitch != newPitch) {
  69647. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  69648. localTarget.addInPlace(bonePos);
  69649. target = localTarget;
  69650. }
  69651. }
  69652. if (checkYaw) {
  69653. var localTarget = BoneLookController._tmpVecs[4];
  69654. target.subtractToRef(bonePos, localTarget);
  69655. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  69656. var yaw = Math.atan2(localTarget.x, localTarget.z);
  69657. var newYaw = yaw;
  69658. if (yaw > this._maxYaw || yaw < this._minYaw) {
  69659. if (xzlen == null) {
  69660. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  69661. }
  69662. if (this._yawRange > Math.PI) {
  69663. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  69664. localTarget.z = this._maxYawCos * xzlen;
  69665. localTarget.x = this._maxYawSin * xzlen;
  69666. newYaw = this._maxYaw;
  69667. }
  69668. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  69669. localTarget.z = this._minYawCos * xzlen;
  69670. localTarget.x = this._minYawSin * xzlen;
  69671. newYaw = this._minYaw;
  69672. }
  69673. }
  69674. else {
  69675. if (yaw > this._maxYaw) {
  69676. localTarget.z = this._maxYawCos * xzlen;
  69677. localTarget.x = this._maxYawSin * xzlen;
  69678. newYaw = this._maxYaw;
  69679. }
  69680. else if (yaw < this._minYaw) {
  69681. localTarget.z = this._minYawCos * xzlen;
  69682. localTarget.x = this._minYawSin * xzlen;
  69683. newYaw = this._minYaw;
  69684. }
  69685. }
  69686. }
  69687. if (this._slerping && this._yawRange > Math.PI) {
  69688. //are we going to be crossing into the min/max region?
  69689. var boneFwd = BoneLookController._tmpVecs[8];
  69690. boneFwd.copyFrom(BABYLON.Axis.Z);
  69691. if (this._transformYawPitch) {
  69692. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  69693. }
  69694. var boneRotMat = BoneLookController._tmpMats[4];
  69695. this._boneQuat.toRotationMatrix(boneRotMat);
  69696. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  69697. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  69698. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  69699. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  69700. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  69701. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  69702. if (angBtwTar > angBtwMidYaw) {
  69703. if (xzlen == null) {
  69704. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  69705. }
  69706. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  69707. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  69708. if (angBtwMin < angBtwMax) {
  69709. newYaw = boneYaw + Math.PI * .75;
  69710. localTarget.z = Math.cos(newYaw) * xzlen;
  69711. localTarget.x = Math.sin(newYaw) * xzlen;
  69712. }
  69713. else {
  69714. newYaw = boneYaw - Math.PI * .75;
  69715. localTarget.z = Math.cos(newYaw) * xzlen;
  69716. localTarget.x = Math.sin(newYaw) * xzlen;
  69717. }
  69718. }
  69719. }
  69720. if (yaw != newYaw) {
  69721. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  69722. localTarget.addInPlace(bonePos);
  69723. target = localTarget;
  69724. }
  69725. }
  69726. }
  69727. var zaxis = BoneLookController._tmpVecs[5];
  69728. var xaxis = BoneLookController._tmpVecs[6];
  69729. var yaxis = BoneLookController._tmpVecs[7];
  69730. var _tmpQuat = BoneLookController._tmpQuat;
  69731. target.subtractToRef(bonePos, zaxis);
  69732. zaxis.normalize();
  69733. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  69734. xaxis.normalize();
  69735. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  69736. yaxis.normalize();
  69737. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  69738. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  69739. return;
  69740. }
  69741. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  69742. return;
  69743. }
  69744. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  69745. return;
  69746. }
  69747. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  69748. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  69749. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  69750. }
  69751. if (this.slerpAmount < 1) {
  69752. if (!this._slerping) {
  69753. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  69754. }
  69755. if (this._transformYawPitch) {
  69756. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  69757. }
  69758. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  69759. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  69760. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  69761. this._slerping = true;
  69762. }
  69763. else {
  69764. if (this._transformYawPitch) {
  69765. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  69766. }
  69767. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  69768. this._slerping = false;
  69769. }
  69770. };
  69771. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  69772. var angDiff = ang2 - ang1;
  69773. angDiff %= Math.PI * 2;
  69774. if (angDiff > Math.PI) {
  69775. angDiff -= Math.PI * 2;
  69776. }
  69777. else if (angDiff < -Math.PI) {
  69778. angDiff += Math.PI * 2;
  69779. }
  69780. return angDiff;
  69781. };
  69782. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  69783. ang1 %= (2 * Math.PI);
  69784. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  69785. ang2 %= (2 * Math.PI);
  69786. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  69787. var ab = 0;
  69788. if (ang1 < ang2) {
  69789. ab = ang2 - ang1;
  69790. }
  69791. else {
  69792. ab = ang1 - ang2;
  69793. }
  69794. if (ab > Math.PI) {
  69795. ab = Math.PI * 2 - ab;
  69796. }
  69797. return ab;
  69798. };
  69799. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  69800. ang %= (2 * Math.PI);
  69801. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  69802. ang1 %= (2 * Math.PI);
  69803. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  69804. ang2 %= (2 * Math.PI);
  69805. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  69806. if (ang1 < ang2) {
  69807. if (ang > ang1 && ang < ang2) {
  69808. return true;
  69809. }
  69810. }
  69811. else {
  69812. if (ang > ang2 && ang < ang1) {
  69813. return true;
  69814. }
  69815. }
  69816. return false;
  69817. };
  69818. 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()];
  69819. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  69820. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  69821. return BoneLookController;
  69822. }());
  69823. BABYLON.BoneLookController = BoneLookController;
  69824. })(BABYLON || (BABYLON = {}));
  69825. //# sourceMappingURL=babylon.boneLookController.js.map
  69826. var BABYLON;
  69827. (function (BABYLON) {
  69828. var Skeleton = /** @class */ (function () {
  69829. function Skeleton(name, id, scene) {
  69830. this.name = name;
  69831. this.id = id;
  69832. this.bones = new Array();
  69833. this.needInitialSkinMatrix = false;
  69834. this._isDirty = true;
  69835. this._meshesWithPoseMatrix = new Array();
  69836. this._identity = BABYLON.Matrix.Identity();
  69837. this._ranges = {};
  69838. this._lastAbsoluteTransformsUpdateId = -1;
  69839. // Events
  69840. /**
  69841. * An event triggered before computing the skeleton's matrices
  69842. * @type {BABYLON.Observable}
  69843. */
  69844. this.onBeforeComputeObservable = new BABYLON.Observable();
  69845. this.bones = [];
  69846. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  69847. scene.skeletons.push(this);
  69848. //make sure it will recalculate the matrix next time prepare is called.
  69849. this._isDirty = true;
  69850. }
  69851. // Members
  69852. Skeleton.prototype.getTransformMatrices = function (mesh) {
  69853. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  69854. return mesh._bonesTransformMatrices;
  69855. }
  69856. if (!this._transformMatrices) {
  69857. this.prepare();
  69858. }
  69859. return this._transformMatrices;
  69860. };
  69861. Skeleton.prototype.getScene = function () {
  69862. return this._scene;
  69863. };
  69864. // Methods
  69865. /**
  69866. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  69867. */
  69868. Skeleton.prototype.toString = function (fullDetails) {
  69869. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  69870. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  69871. if (fullDetails) {
  69872. ret += ", Ranges: {";
  69873. var first = true;
  69874. for (var name_1 in this._ranges) {
  69875. if (first) {
  69876. ret += ", ";
  69877. first = false;
  69878. }
  69879. ret += name_1;
  69880. }
  69881. ret += "}";
  69882. }
  69883. return ret;
  69884. };
  69885. /**
  69886. * Get bone's index searching by name
  69887. * @param {string} name is bone's name to search for
  69888. * @return {number} Indice of the bone. Returns -1 if not found
  69889. */
  69890. Skeleton.prototype.getBoneIndexByName = function (name) {
  69891. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  69892. if (this.bones[boneIndex].name === name) {
  69893. return boneIndex;
  69894. }
  69895. }
  69896. return -1;
  69897. };
  69898. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  69899. // check name not already in use
  69900. if (!this._ranges[name]) {
  69901. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  69902. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  69903. if (this.bones[i].animations[0]) {
  69904. this.bones[i].animations[0].createRange(name, from, to);
  69905. }
  69906. }
  69907. }
  69908. };
  69909. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  69910. if (deleteFrames === void 0) { deleteFrames = true; }
  69911. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  69912. if (this.bones[i].animations[0]) {
  69913. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  69914. }
  69915. }
  69916. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  69917. };
  69918. Skeleton.prototype.getAnimationRange = function (name) {
  69919. return this._ranges[name];
  69920. };
  69921. /**
  69922. * Returns as an Array, all AnimationRanges defined on this skeleton
  69923. */
  69924. Skeleton.prototype.getAnimationRanges = function () {
  69925. var animationRanges = [];
  69926. var name;
  69927. var i = 0;
  69928. for (name in this._ranges) {
  69929. animationRanges[i] = this._ranges[name];
  69930. i++;
  69931. }
  69932. return animationRanges;
  69933. };
  69934. /**
  69935. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  69936. */
  69937. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  69938. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  69939. if (this._ranges[name] || !source.getAnimationRange(name)) {
  69940. return false;
  69941. }
  69942. var ret = true;
  69943. var frameOffset = this._getHighestAnimationFrame() + 1;
  69944. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  69945. var boneDict = {};
  69946. var sourceBones = source.bones;
  69947. var nBones;
  69948. var i;
  69949. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  69950. boneDict[sourceBones[i].name] = sourceBones[i];
  69951. }
  69952. if (this.bones.length !== sourceBones.length) {
  69953. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  69954. ret = false;
  69955. }
  69956. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  69957. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  69958. var boneName = this.bones[i].name;
  69959. var sourceBone = boneDict[boneName];
  69960. if (sourceBone) {
  69961. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  69962. }
  69963. else {
  69964. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  69965. ret = false;
  69966. }
  69967. }
  69968. // do not call createAnimationRange(), since it also is done to bones, which was already done
  69969. var range = source.getAnimationRange(name);
  69970. if (range) {
  69971. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  69972. }
  69973. return ret;
  69974. };
  69975. Skeleton.prototype.returnToRest = function () {
  69976. for (var index = 0; index < this.bones.length; index++) {
  69977. this.bones[index].returnToRest();
  69978. }
  69979. };
  69980. Skeleton.prototype._getHighestAnimationFrame = function () {
  69981. var ret = 0;
  69982. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  69983. if (this.bones[i].animations[0]) {
  69984. var highest = this.bones[i].animations[0].getHighestFrame();
  69985. if (ret < highest) {
  69986. ret = highest;
  69987. }
  69988. }
  69989. }
  69990. return ret;
  69991. };
  69992. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  69993. var range = this.getAnimationRange(name);
  69994. if (!range) {
  69995. return null;
  69996. }
  69997. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  69998. };
  69999. Skeleton.prototype._markAsDirty = function () {
  70000. this._isDirty = true;
  70001. };
  70002. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  70003. this._meshesWithPoseMatrix.push(mesh);
  70004. };
  70005. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  70006. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  70007. if (index > -1) {
  70008. this._meshesWithPoseMatrix.splice(index, 1);
  70009. }
  70010. };
  70011. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  70012. this.onBeforeComputeObservable.notifyObservers(this);
  70013. for (var index = 0; index < this.bones.length; index++) {
  70014. var bone = this.bones[index];
  70015. var parentBone = bone.getParent();
  70016. if (parentBone) {
  70017. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  70018. }
  70019. else {
  70020. if (initialSkinMatrix) {
  70021. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  70022. }
  70023. else {
  70024. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  70025. }
  70026. }
  70027. if (bone._index !== -1) {
  70028. var mappedIndex = bone._index === null ? index : bone._index;
  70029. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  70030. }
  70031. }
  70032. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  70033. };
  70034. Skeleton.prototype.prepare = function () {
  70035. if (!this._isDirty) {
  70036. return;
  70037. }
  70038. if (this.needInitialSkinMatrix) {
  70039. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  70040. var mesh = this._meshesWithPoseMatrix[index];
  70041. var poseMatrix = mesh.getPoseMatrix();
  70042. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  70043. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  70044. }
  70045. if (this._synchronizedWithMesh !== mesh) {
  70046. this._synchronizedWithMesh = mesh;
  70047. // Prepare bones
  70048. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  70049. var bone = this.bones[boneIndex];
  70050. if (!bone.getParent()) {
  70051. var matrix = bone.getBaseMatrix();
  70052. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  70053. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  70054. }
  70055. }
  70056. }
  70057. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  70058. }
  70059. }
  70060. else {
  70061. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  70062. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  70063. }
  70064. this._computeTransformMatrices(this._transformMatrices, null);
  70065. }
  70066. this._isDirty = false;
  70067. this._scene._activeBones.addCount(this.bones.length, false);
  70068. };
  70069. Skeleton.prototype.getAnimatables = function () {
  70070. if (!this._animatables || this._animatables.length !== this.bones.length) {
  70071. this._animatables = [];
  70072. for (var index = 0; index < this.bones.length; index++) {
  70073. this._animatables.push(this.bones[index]);
  70074. }
  70075. }
  70076. return this._animatables;
  70077. };
  70078. Skeleton.prototype.clone = function (name, id) {
  70079. var result = new Skeleton(name, id || name, this._scene);
  70080. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  70081. for (var index = 0; index < this.bones.length; index++) {
  70082. var source = this.bones[index];
  70083. var parentBone = null;
  70084. var parent_1 = source.getParent();
  70085. if (parent_1) {
  70086. var parentIndex = this.bones.indexOf(parent_1);
  70087. parentBone = result.bones[parentIndex];
  70088. }
  70089. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  70090. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  70091. }
  70092. if (this._ranges) {
  70093. result._ranges = {};
  70094. for (var rangeName in this._ranges) {
  70095. var range = this._ranges[rangeName];
  70096. if (range) {
  70097. result._ranges[rangeName] = range.clone();
  70098. }
  70099. }
  70100. }
  70101. this._isDirty = true;
  70102. return result;
  70103. };
  70104. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  70105. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  70106. this.bones.forEach(function (bone) {
  70107. bone.animations.forEach(function (animation) {
  70108. animation.enableBlending = true;
  70109. animation.blendingSpeed = blendingSpeed;
  70110. });
  70111. });
  70112. };
  70113. Skeleton.prototype.dispose = function () {
  70114. this._meshesWithPoseMatrix = [];
  70115. // Animations
  70116. this.getScene().stopAnimation(this);
  70117. // Remove from scene
  70118. this.getScene().removeSkeleton(this);
  70119. };
  70120. Skeleton.prototype.serialize = function () {
  70121. var serializationObject = {};
  70122. serializationObject.name = this.name;
  70123. serializationObject.id = this.id;
  70124. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  70125. serializationObject.bones = [];
  70126. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  70127. for (var index = 0; index < this.bones.length; index++) {
  70128. var bone = this.bones[index];
  70129. var parent_2 = bone.getParent();
  70130. var serializedBone = {
  70131. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  70132. name: bone.name,
  70133. matrix: bone.getBaseMatrix().toArray(),
  70134. rest: bone.getRestPose().toArray()
  70135. };
  70136. serializationObject.bones.push(serializedBone);
  70137. if (bone.length) {
  70138. serializedBone.length = bone.length;
  70139. }
  70140. if (bone.animations && bone.animations.length > 0) {
  70141. serializedBone.animation = bone.animations[0].serialize();
  70142. }
  70143. serializationObject.ranges = [];
  70144. for (var name in this._ranges) {
  70145. var source = this._ranges[name];
  70146. if (!source) {
  70147. continue;
  70148. }
  70149. var range = {};
  70150. range.name = name;
  70151. range.from = source.from;
  70152. range.to = source.to;
  70153. serializationObject.ranges.push(range);
  70154. }
  70155. }
  70156. return serializationObject;
  70157. };
  70158. Skeleton.Parse = function (parsedSkeleton, scene) {
  70159. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  70160. if (parsedSkeleton.dimensionsAtRest) {
  70161. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  70162. }
  70163. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  70164. var index;
  70165. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  70166. var parsedBone = parsedSkeleton.bones[index];
  70167. var parentBone = null;
  70168. if (parsedBone.parentBoneIndex > -1) {
  70169. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  70170. }
  70171. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  70172. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  70173. if (parsedBone.length) {
  70174. bone.length = parsedBone.length;
  70175. }
  70176. if (parsedBone.animation) {
  70177. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  70178. }
  70179. }
  70180. // placed after bones, so createAnimationRange can cascade down
  70181. if (parsedSkeleton.ranges) {
  70182. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  70183. var data = parsedSkeleton.ranges[index];
  70184. skeleton.createAnimationRange(data.name, data.from, data.to);
  70185. }
  70186. }
  70187. return skeleton;
  70188. };
  70189. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  70190. if (forceUpdate === void 0) { forceUpdate = false; }
  70191. var renderId = this._scene.getRenderId();
  70192. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  70193. this.bones[0].computeAbsoluteTransforms();
  70194. this._lastAbsoluteTransformsUpdateId = renderId;
  70195. }
  70196. };
  70197. Skeleton.prototype.getPoseMatrix = function () {
  70198. var poseMatrix = null;
  70199. if (this._meshesWithPoseMatrix.length > 0) {
  70200. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  70201. }
  70202. return poseMatrix;
  70203. };
  70204. Skeleton.prototype.sortBones = function () {
  70205. var bones = new Array();
  70206. var visited = new Array(this.bones.length);
  70207. for (var index = 0; index < this.bones.length; index++) {
  70208. this._sortBones(index, bones, visited);
  70209. }
  70210. this.bones = bones;
  70211. };
  70212. Skeleton.prototype._sortBones = function (index, bones, visited) {
  70213. if (visited[index]) {
  70214. return;
  70215. }
  70216. visited[index] = true;
  70217. var bone = this.bones[index];
  70218. if (bone._index === undefined) {
  70219. bone._index = index;
  70220. }
  70221. var parentBone = bone.getParent();
  70222. if (parentBone) {
  70223. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  70224. }
  70225. bones.push(bone);
  70226. };
  70227. return Skeleton;
  70228. }());
  70229. BABYLON.Skeleton = Skeleton;
  70230. })(BABYLON || (BABYLON = {}));
  70231. //# sourceMappingURL=babylon.skeleton.js.map
  70232. var BABYLON;
  70233. (function (BABYLON) {
  70234. var SphericalPolynomial = /** @class */ (function () {
  70235. function SphericalPolynomial() {
  70236. this.x = BABYLON.Vector3.Zero();
  70237. this.y = BABYLON.Vector3.Zero();
  70238. this.z = BABYLON.Vector3.Zero();
  70239. this.xx = BABYLON.Vector3.Zero();
  70240. this.yy = BABYLON.Vector3.Zero();
  70241. this.zz = BABYLON.Vector3.Zero();
  70242. this.xy = BABYLON.Vector3.Zero();
  70243. this.yz = BABYLON.Vector3.Zero();
  70244. this.zx = BABYLON.Vector3.Zero();
  70245. }
  70246. SphericalPolynomial.prototype.addAmbient = function (color) {
  70247. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  70248. this.xx = this.xx.add(colorVector);
  70249. this.yy = this.yy.add(colorVector);
  70250. this.zz = this.zz.add(colorVector);
  70251. };
  70252. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  70253. var result = new SphericalPolynomial();
  70254. result.x = harmonics.L11.scale(1.02333);
  70255. result.y = harmonics.L1_1.scale(1.02333);
  70256. result.z = harmonics.L10.scale(1.02333);
  70257. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  70258. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  70259. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  70260. result.yz = harmonics.L2_1.scale(0.858086);
  70261. result.zx = harmonics.L21.scale(0.858086);
  70262. result.xy = harmonics.L2_2.scale(0.858086);
  70263. result.scale(1.0 / Math.PI);
  70264. return result;
  70265. };
  70266. SphericalPolynomial.prototype.scale = function (scale) {
  70267. this.x = this.x.scale(scale);
  70268. this.y = this.y.scale(scale);
  70269. this.z = this.z.scale(scale);
  70270. this.xx = this.xx.scale(scale);
  70271. this.yy = this.yy.scale(scale);
  70272. this.zz = this.zz.scale(scale);
  70273. this.yz = this.yz.scale(scale);
  70274. this.zx = this.zx.scale(scale);
  70275. this.xy = this.xy.scale(scale);
  70276. };
  70277. return SphericalPolynomial;
  70278. }());
  70279. BABYLON.SphericalPolynomial = SphericalPolynomial;
  70280. var SphericalHarmonics = /** @class */ (function () {
  70281. function SphericalHarmonics() {
  70282. this.L00 = BABYLON.Vector3.Zero();
  70283. this.L1_1 = BABYLON.Vector3.Zero();
  70284. this.L10 = BABYLON.Vector3.Zero();
  70285. this.L11 = BABYLON.Vector3.Zero();
  70286. this.L2_2 = BABYLON.Vector3.Zero();
  70287. this.L2_1 = BABYLON.Vector3.Zero();
  70288. this.L20 = BABYLON.Vector3.Zero();
  70289. this.L21 = BABYLON.Vector3.Zero();
  70290. this.L22 = BABYLON.Vector3.Zero();
  70291. }
  70292. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  70293. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  70294. var c = colorVector.scale(deltaSolidAngle);
  70295. this.L00 = this.L00.add(c.scale(0.282095));
  70296. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  70297. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  70298. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  70299. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  70300. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  70301. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  70302. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  70303. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  70304. };
  70305. SphericalHarmonics.prototype.scale = function (scale) {
  70306. this.L00 = this.L00.scale(scale);
  70307. this.L1_1 = this.L1_1.scale(scale);
  70308. this.L10 = this.L10.scale(scale);
  70309. this.L11 = this.L11.scale(scale);
  70310. this.L2_2 = this.L2_2.scale(scale);
  70311. this.L2_1 = this.L2_1.scale(scale);
  70312. this.L20 = this.L20.scale(scale);
  70313. this.L21 = this.L21.scale(scale);
  70314. this.L22 = this.L22.scale(scale);
  70315. };
  70316. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  70317. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  70318. //
  70319. // E_lm = A_l * L_lm
  70320. //
  70321. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  70322. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  70323. // the scaling factors are given in equation 9.
  70324. // Constant (Band 0)
  70325. this.L00 = this.L00.scale(3.141593);
  70326. // Linear (Band 1)
  70327. this.L1_1 = this.L1_1.scale(2.094395);
  70328. this.L10 = this.L10.scale(2.094395);
  70329. this.L11 = this.L11.scale(2.094395);
  70330. // Quadratic (Band 2)
  70331. this.L2_2 = this.L2_2.scale(0.785398);
  70332. this.L2_1 = this.L2_1.scale(0.785398);
  70333. this.L20 = this.L20.scale(0.785398);
  70334. this.L21 = this.L21.scale(0.785398);
  70335. this.L22 = this.L22.scale(0.785398);
  70336. };
  70337. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  70338. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  70339. // L = (1/pi) * E * rho
  70340. //
  70341. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  70342. this.scale(1.0 / Math.PI);
  70343. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  70344. // (The pixel shader must apply albedo after texture fetches, etc).
  70345. };
  70346. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  70347. var result = new SphericalHarmonics();
  70348. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  70349. result.L1_1 = polynomial.y.scale(0.977204);
  70350. result.L10 = polynomial.z.scale(0.977204);
  70351. result.L11 = polynomial.x.scale(0.977204);
  70352. result.L2_2 = polynomial.xy.scale(1.16538);
  70353. result.L2_1 = polynomial.yz.scale(1.16538);
  70354. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  70355. result.L21 = polynomial.zx.scale(1.16538);
  70356. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  70357. result.scale(Math.PI);
  70358. return result;
  70359. };
  70360. return SphericalHarmonics;
  70361. }());
  70362. BABYLON.SphericalHarmonics = SphericalHarmonics;
  70363. })(BABYLON || (BABYLON = {}));
  70364. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  70365. var BABYLON;
  70366. (function (BABYLON) {
  70367. var FileFaceOrientation = /** @class */ (function () {
  70368. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  70369. this.name = name;
  70370. this.worldAxisForNormal = worldAxisForNormal;
  70371. this.worldAxisForFileX = worldAxisForFileX;
  70372. this.worldAxisForFileY = worldAxisForFileY;
  70373. }
  70374. return FileFaceOrientation;
  70375. }());
  70376. ;
  70377. /**
  70378. * Helper class dealing with the extraction of spherical polynomial dataArray
  70379. * from a cube map.
  70380. */
  70381. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  70382. function CubeMapToSphericalPolynomialTools() {
  70383. }
  70384. /**
  70385. * Converts a texture to the according Spherical Polynomial data.
  70386. * This extracts the first 3 orders only as they are the only one used in the lighting.
  70387. *
  70388. * @param texture The texture to extract the information from.
  70389. * @return The Spherical Polynomial data.
  70390. */
  70391. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  70392. if (!texture.isCube) {
  70393. // Only supports cube Textures currently.
  70394. return null;
  70395. }
  70396. var size = texture.getSize().width;
  70397. var right = texture.readPixels(0);
  70398. var left = texture.readPixels(1);
  70399. var up;
  70400. var down;
  70401. if (texture.isRenderTarget) {
  70402. up = texture.readPixels(3);
  70403. down = texture.readPixels(2);
  70404. }
  70405. else {
  70406. up = texture.readPixels(2);
  70407. down = texture.readPixels(3);
  70408. }
  70409. var front = texture.readPixels(4);
  70410. var back = texture.readPixels(5);
  70411. var gammaSpace = texture.gammaSpace;
  70412. // Always read as RGBA.
  70413. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  70414. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  70415. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  70416. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  70417. }
  70418. var cubeInfo = {
  70419. size: size,
  70420. right: right,
  70421. left: left,
  70422. up: up,
  70423. down: down,
  70424. front: front,
  70425. back: back,
  70426. format: format,
  70427. type: type,
  70428. gammaSpace: gammaSpace,
  70429. };
  70430. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  70431. };
  70432. /**
  70433. * Converts a cubemap to the according Spherical Polynomial data.
  70434. * This extracts the first 3 orders only as they are the only one used in the lighting.
  70435. *
  70436. * @param cubeInfo The Cube map to extract the information from.
  70437. * @return The Spherical Polynomial data.
  70438. */
  70439. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  70440. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  70441. var totalSolidAngle = 0.0;
  70442. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  70443. var du = 2.0 / cubeInfo.size;
  70444. var dv = du;
  70445. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  70446. var minUV = du * 0.5 - 1.0;
  70447. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  70448. var fileFace = this.FileFaces[faceIndex];
  70449. var dataArray = cubeInfo[fileFace.name];
  70450. var v = minUV;
  70451. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  70452. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  70453. // Because SP is still linear, so summation is fine in that basis.
  70454. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  70455. for (var y = 0; y < cubeInfo.size; y++) {
  70456. var u = minUV;
  70457. for (var x = 0; x < cubeInfo.size; x++) {
  70458. // World direction (not normalised)
  70459. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  70460. worldDirection.normalize();
  70461. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  70462. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  70463. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  70464. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  70465. // Handle Integer types.
  70466. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  70467. r /= 255;
  70468. g /= 255;
  70469. b /= 255;
  70470. }
  70471. // Handle Gamma space textures.
  70472. if (cubeInfo.gammaSpace) {
  70473. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  70474. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  70475. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  70476. }
  70477. var color = new BABYLON.Color3(r, g, b);
  70478. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  70479. totalSolidAngle += deltaSolidAngle;
  70480. u += du;
  70481. }
  70482. v += dv;
  70483. }
  70484. }
  70485. // Solid angle for entire sphere is 4*pi
  70486. var sphereSolidAngle = 4.0 * Math.PI;
  70487. // Adjust the solid angle to allow for how many faces we processed.
  70488. var facesProcessed = 6.0;
  70489. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  70490. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  70491. // This is needed because the numerical integration over the cube uses a
  70492. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  70493. // and also to compensate for accumulative error due to float precision in the summation.
  70494. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  70495. sphericalHarmonics.scale(correctionFactor);
  70496. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  70497. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  70498. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  70499. };
  70500. CubeMapToSphericalPolynomialTools.FileFaces = [
  70501. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  70502. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  70503. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  70504. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  70505. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  70506. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  70507. ];
  70508. return CubeMapToSphericalPolynomialTools;
  70509. }());
  70510. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  70511. })(BABYLON || (BABYLON = {}));
  70512. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  70513. var BABYLON;
  70514. (function (BABYLON) {
  70515. /**
  70516. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  70517. */
  70518. var PanoramaToCubeMapTools = /** @class */ (function () {
  70519. function PanoramaToCubeMapTools() {
  70520. }
  70521. /**
  70522. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  70523. *
  70524. * @param float32Array The source data.
  70525. * @param inputWidth The width of the input panorama.
  70526. * @param inputhHeight The height of the input panorama.
  70527. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  70528. * @return The cubemap data
  70529. */
  70530. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  70531. if (!float32Array) {
  70532. throw "ConvertPanoramaToCubemap: input cannot be null";
  70533. }
  70534. if (float32Array.length != inputWidth * inputHeight * 3) {
  70535. throw "ConvertPanoramaToCubemap: input size is wrong";
  70536. }
  70537. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  70538. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  70539. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  70540. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  70541. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  70542. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  70543. return {
  70544. front: textureFront,
  70545. back: textureBack,
  70546. left: textureLeft,
  70547. right: textureRight,
  70548. up: textureUp,
  70549. down: textureDown,
  70550. size: size,
  70551. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  70552. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  70553. gammaSpace: false,
  70554. };
  70555. };
  70556. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  70557. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  70558. var textureArray = new Float32Array(buffer);
  70559. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  70560. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  70561. var dy = 1 / texSize;
  70562. var fy = 0;
  70563. for (var y = 0; y < texSize; y++) {
  70564. var xv1 = faceData[0];
  70565. var xv2 = faceData[2];
  70566. for (var x = 0; x < texSize; x++) {
  70567. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  70568. v.normalize();
  70569. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  70570. // 3 channels per pixels
  70571. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  70572. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  70573. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  70574. xv1 = xv1.add(rotDX1);
  70575. xv2 = xv2.add(rotDX2);
  70576. }
  70577. fy += dy;
  70578. }
  70579. return textureArray;
  70580. };
  70581. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  70582. var theta = Math.atan2(vDir.z, vDir.x);
  70583. var phi = Math.acos(vDir.y);
  70584. while (theta < -Math.PI)
  70585. theta += 2 * Math.PI;
  70586. while (theta > Math.PI)
  70587. theta -= 2 * Math.PI;
  70588. var dx = theta / Math.PI;
  70589. var dy = phi / Math.PI;
  70590. // recenter.
  70591. dx = dx * 0.5 + 0.5;
  70592. var px = Math.round(dx * inputWidth);
  70593. if (px < 0)
  70594. px = 0;
  70595. else if (px >= inputWidth)
  70596. px = inputWidth - 1;
  70597. var py = Math.round(dy * inputHeight);
  70598. if (py < 0)
  70599. py = 0;
  70600. else if (py >= inputHeight)
  70601. py = inputHeight - 1;
  70602. var inputY = (inputHeight - py - 1);
  70603. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  70604. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  70605. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  70606. return {
  70607. r: r,
  70608. g: g,
  70609. b: b
  70610. };
  70611. };
  70612. PanoramaToCubeMapTools.FACE_FRONT = [
  70613. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  70614. new BABYLON.Vector3(1.0, -1.0, -1.0),
  70615. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  70616. new BABYLON.Vector3(1.0, 1.0, -1.0)
  70617. ];
  70618. PanoramaToCubeMapTools.FACE_BACK = [
  70619. new BABYLON.Vector3(1.0, -1.0, 1.0),
  70620. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  70621. new BABYLON.Vector3(1.0, 1.0, 1.0),
  70622. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  70623. ];
  70624. PanoramaToCubeMapTools.FACE_RIGHT = [
  70625. new BABYLON.Vector3(1.0, -1.0, -1.0),
  70626. new BABYLON.Vector3(1.0, -1.0, 1.0),
  70627. new BABYLON.Vector3(1.0, 1.0, -1.0),
  70628. new BABYLON.Vector3(1.0, 1.0, 1.0)
  70629. ];
  70630. PanoramaToCubeMapTools.FACE_LEFT = [
  70631. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  70632. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  70633. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  70634. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  70635. ];
  70636. PanoramaToCubeMapTools.FACE_DOWN = [
  70637. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  70638. new BABYLON.Vector3(1.0, 1.0, -1.0),
  70639. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  70640. new BABYLON.Vector3(1.0, 1.0, 1.0)
  70641. ];
  70642. PanoramaToCubeMapTools.FACE_UP = [
  70643. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  70644. new BABYLON.Vector3(1.0, -1.0, 1.0),
  70645. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  70646. new BABYLON.Vector3(1.0, -1.0, -1.0)
  70647. ];
  70648. return PanoramaToCubeMapTools;
  70649. }());
  70650. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  70651. })(BABYLON || (BABYLON = {}));
  70652. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  70653. var BABYLON;
  70654. (function (BABYLON) {
  70655. ;
  70656. /**
  70657. * This groups tools to convert HDR texture to native colors array.
  70658. */
  70659. var HDRTools = /** @class */ (function () {
  70660. function HDRTools() {
  70661. }
  70662. HDRTools.Ldexp = function (mantissa, exponent) {
  70663. if (exponent > 1023) {
  70664. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  70665. }
  70666. if (exponent < -1074) {
  70667. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  70668. }
  70669. return mantissa * Math.pow(2, exponent);
  70670. };
  70671. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  70672. if (exponent > 0) {
  70673. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  70674. float32array[index + 0] = red * exponent;
  70675. float32array[index + 1] = green * exponent;
  70676. float32array[index + 2] = blue * exponent;
  70677. }
  70678. else {
  70679. float32array[index + 0] = 0;
  70680. float32array[index + 1] = 0;
  70681. float32array[index + 2] = 0;
  70682. }
  70683. };
  70684. HDRTools.readStringLine = function (uint8array, startIndex) {
  70685. var line = "";
  70686. var character = "";
  70687. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  70688. character = String.fromCharCode(uint8array[i]);
  70689. if (character == "\n") {
  70690. break;
  70691. }
  70692. line += character;
  70693. }
  70694. return line;
  70695. };
  70696. /**
  70697. * Reads header information from an RGBE texture stored in a native array.
  70698. * More information on this format are available here:
  70699. * https://en.wikipedia.org/wiki/RGBE_image_format
  70700. *
  70701. * @param uint8array The binary file stored in native array.
  70702. * @return The header information.
  70703. */
  70704. HDRTools.RGBE_ReadHeader = function (uint8array) {
  70705. var height = 0;
  70706. var width = 0;
  70707. var line = this.readStringLine(uint8array, 0);
  70708. if (line[0] != '#' || line[1] != '?') {
  70709. throw "Bad HDR Format.";
  70710. }
  70711. var endOfHeader = false;
  70712. var findFormat = false;
  70713. var lineIndex = 0;
  70714. do {
  70715. lineIndex += (line.length + 1);
  70716. line = this.readStringLine(uint8array, lineIndex);
  70717. if (line == "FORMAT=32-bit_rle_rgbe") {
  70718. findFormat = true;
  70719. }
  70720. else if (line.length == 0) {
  70721. endOfHeader = true;
  70722. }
  70723. } while (!endOfHeader);
  70724. if (!findFormat) {
  70725. throw "HDR Bad header format, unsupported FORMAT";
  70726. }
  70727. lineIndex += (line.length + 1);
  70728. line = this.readStringLine(uint8array, lineIndex);
  70729. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  70730. var match = sizeRegexp.exec(line);
  70731. // TODO. Support +Y and -X if needed.
  70732. if (!match || match.length < 3) {
  70733. throw "HDR Bad header format, no size";
  70734. }
  70735. width = parseInt(match[2]);
  70736. height = parseInt(match[1]);
  70737. if (width < 8 || width > 0x7fff) {
  70738. throw "HDR Bad header format, unsupported size";
  70739. }
  70740. lineIndex += (line.length + 1);
  70741. return {
  70742. height: height,
  70743. width: width,
  70744. dataPosition: lineIndex
  70745. };
  70746. };
  70747. /**
  70748. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  70749. * This RGBE texture needs to store the information as a panorama.
  70750. *
  70751. * More information on this format are available here:
  70752. * https://en.wikipedia.org/wiki/RGBE_image_format
  70753. *
  70754. * @param buffer The binary file stored in an array buffer.
  70755. * @param size The expected size of the extracted cubemap.
  70756. * @return The Cube Map information.
  70757. */
  70758. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  70759. var uint8array = new Uint8Array(buffer);
  70760. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  70761. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  70762. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  70763. return cubeMapData;
  70764. };
  70765. /**
  70766. * Returns the pixels data extracted from an RGBE texture.
  70767. * This pixels will be stored left to right up to down in the R G B order in one array.
  70768. *
  70769. * More information on this format are available here:
  70770. * https://en.wikipedia.org/wiki/RGBE_image_format
  70771. *
  70772. * @param uint8array The binary file stored in an array buffer.
  70773. * @param hdrInfo The header information of the file.
  70774. * @return The pixels data in RGB right to left up to down order.
  70775. */
  70776. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  70777. // Keep for multi format supports.
  70778. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  70779. };
  70780. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  70781. var num_scanlines = hdrInfo.height;
  70782. var scanline_width = hdrInfo.width;
  70783. var a, b, c, d, count;
  70784. var dataIndex = hdrInfo.dataPosition;
  70785. var index = 0, endIndex = 0, i = 0;
  70786. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  70787. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  70788. // 3 channels of 4 bytes per pixel in float.
  70789. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  70790. var resultArray = new Float32Array(resultBuffer);
  70791. // read in each successive scanline
  70792. while (num_scanlines > 0) {
  70793. a = uint8array[dataIndex++];
  70794. b = uint8array[dataIndex++];
  70795. c = uint8array[dataIndex++];
  70796. d = uint8array[dataIndex++];
  70797. if (a != 2 || b != 2 || (c & 0x80)) {
  70798. // this file is not run length encoded
  70799. throw "HDR Bad header format, not RLE";
  70800. }
  70801. if (((c << 8) | d) != scanline_width) {
  70802. throw "HDR Bad header format, wrong scan line width";
  70803. }
  70804. index = 0;
  70805. // read each of the four channels for the scanline into the buffer
  70806. for (i = 0; i < 4; i++) {
  70807. endIndex = (i + 1) * scanline_width;
  70808. while (index < endIndex) {
  70809. a = uint8array[dataIndex++];
  70810. b = uint8array[dataIndex++];
  70811. if (a > 128) {
  70812. // a run of the same value
  70813. count = a - 128;
  70814. if ((count == 0) || (count > endIndex - index)) {
  70815. throw "HDR Bad Format, bad scanline data (run)";
  70816. }
  70817. while (count-- > 0) {
  70818. scanLineArray[index++] = b;
  70819. }
  70820. }
  70821. else {
  70822. // a non-run
  70823. count = a;
  70824. if ((count == 0) || (count > endIndex - index)) {
  70825. throw "HDR Bad Format, bad scanline data (non-run)";
  70826. }
  70827. scanLineArray[index++] = b;
  70828. if (--count > 0) {
  70829. for (var j = 0; j < count; j++) {
  70830. scanLineArray[index++] = uint8array[dataIndex++];
  70831. }
  70832. }
  70833. }
  70834. }
  70835. }
  70836. // now convert data from buffer into floats
  70837. for (i = 0; i < scanline_width; i++) {
  70838. a = scanLineArray[i];
  70839. b = scanLineArray[i + scanline_width];
  70840. c = scanLineArray[i + 2 * scanline_width];
  70841. d = scanLineArray[i + 3 * scanline_width];
  70842. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  70843. }
  70844. num_scanlines--;
  70845. }
  70846. return resultArray;
  70847. };
  70848. return HDRTools;
  70849. }());
  70850. BABYLON.HDRTools = HDRTools;
  70851. })(BABYLON || (BABYLON = {}));
  70852. //# sourceMappingURL=babylon.hdr.js.map
  70853. var BABYLON;
  70854. (function (BABYLON) {
  70855. /**
  70856. * This represents a texture coming from an HDR input.
  70857. *
  70858. * The only supported format is currently panorama picture stored in RGBE format.
  70859. * Example of such files can be found on HDRLib: http://hdrlib.com/
  70860. */
  70861. var HDRCubeTexture = /** @class */ (function (_super) {
  70862. __extends(HDRCubeTexture, _super);
  70863. /**
  70864. * Instantiates an HDRTexture from the following parameters.
  70865. *
  70866. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  70867. * @param scene The scene the texture will be used in
  70868. * @param size The cubemap 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.
  70869. * @param noMipmap Forces to not generate the mipmap if true
  70870. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  70871. * @param useInGammaSpace 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)
  70872. * @param usePMREMGenerator Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  70873. */
  70874. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  70875. if (noMipmap === void 0) { noMipmap = false; }
  70876. if (generateHarmonics === void 0) { generateHarmonics = true; }
  70877. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  70878. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  70879. if (onLoad === void 0) { onLoad = null; }
  70880. if (onError === void 0) { onError = null; }
  70881. var _this = _super.call(this, scene) || this;
  70882. _this._useInGammaSpace = false;
  70883. _this._generateHarmonics = true;
  70884. _this._isBABYLONPreprocessed = false;
  70885. _this._onLoad = null;
  70886. _this._onError = null;
  70887. /**
  70888. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  70889. */
  70890. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  70891. /**
  70892. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  70893. * This is usefull at run time to apply the good shader.
  70894. */
  70895. _this.isPMREM = false;
  70896. _this._isBlocking = true;
  70897. if (!url) {
  70898. return _this;
  70899. }
  70900. _this.name = url;
  70901. _this.url = url;
  70902. _this.hasAlpha = false;
  70903. _this.isCube = true;
  70904. _this._textureMatrix = BABYLON.Matrix.Identity();
  70905. _this._onLoad = onLoad;
  70906. _this._onError = onError;
  70907. _this.gammaSpace = false;
  70908. var caps = scene.getEngine().getCaps();
  70909. if (size) {
  70910. _this._isBABYLONPreprocessed = false;
  70911. _this._noMipmap = noMipmap;
  70912. _this._size = size;
  70913. _this._useInGammaSpace = useInGammaSpace;
  70914. _this._usePMREMGenerator = usePMREMGenerator &&
  70915. caps.textureLOD &&
  70916. caps.textureFloat &&
  70917. !_this._useInGammaSpace;
  70918. }
  70919. else {
  70920. _this._isBABYLONPreprocessed = true;
  70921. _this._noMipmap = false;
  70922. _this._useInGammaSpace = false;
  70923. _this._usePMREMGenerator = caps.textureLOD && caps.textureFloat &&
  70924. !_this._useInGammaSpace;
  70925. }
  70926. _this.isPMREM = _this._usePMREMGenerator;
  70927. _this._texture = _this._getFromCache(url, _this._noMipmap);
  70928. if (!_this._texture) {
  70929. if (!scene.useDelayedTextureLoading) {
  70930. _this.loadTexture();
  70931. }
  70932. else {
  70933. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  70934. }
  70935. }
  70936. return _this;
  70937. }
  70938. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  70939. /**
  70940. * Gets wether or not the texture is blocking during loading.
  70941. */
  70942. get: function () {
  70943. return this._isBlocking;
  70944. },
  70945. /**
  70946. * Sets wether or not the texture is blocking during loading.
  70947. */
  70948. set: function (value) {
  70949. this._isBlocking = value;
  70950. },
  70951. enumerable: true,
  70952. configurable: true
  70953. });
  70954. /**
  70955. * Occurs when the file is a preprocessed .babylon.hdr file.
  70956. */
  70957. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  70958. var _this = this;
  70959. var mipLevels = 0;
  70960. var floatArrayView = null;
  70961. var scene = this.getScene();
  70962. var mipmapGenerator = (!this._useInGammaSpace && scene && scene.getEngine().getCaps().textureFloat) ? function (data) {
  70963. var mips = new Array();
  70964. if (!floatArrayView) {
  70965. return mips;
  70966. }
  70967. var startIndex = 30;
  70968. for (var level = 0; level < mipLevels; level++) {
  70969. mips.push([]);
  70970. // Fill each pixel of the mip level.
  70971. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  70972. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  70973. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  70974. mips[level].push(faceData);
  70975. startIndex += faceSize;
  70976. }
  70977. }
  70978. return mips;
  70979. } : null;
  70980. var callback = function (buffer) {
  70981. var scene = _this.getScene();
  70982. if (!scene) {
  70983. return null;
  70984. }
  70985. // Create Native Array Views
  70986. var intArrayView = new Int32Array(buffer);
  70987. floatArrayView = new Float32Array(buffer);
  70988. // Fill header.
  70989. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  70990. _this._size = intArrayView[1]; // CubeMap max mip face size.
  70991. // Update Texture Information.
  70992. if (!_this._texture) {
  70993. return null;
  70994. }
  70995. _this._texture.updateSize(_this._size, _this._size);
  70996. // Fill polynomial information.
  70997. var sphericalPolynomial = new BABYLON.SphericalPolynomial();
  70998. sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  70999. sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  71000. sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  71001. sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  71002. sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  71003. sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  71004. sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  71005. sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  71006. sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  71007. _this.sphericalPolynomial = sphericalPolynomial;
  71008. // Fill pixel data.
  71009. mipLevels = intArrayView[29]; // Number of mip levels.
  71010. var startIndex = 30;
  71011. var data = [];
  71012. var faceSize = Math.pow(_this._size, 2) * 3;
  71013. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  71014. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  71015. startIndex += faceSize;
  71016. }
  71017. var results = [];
  71018. var byteArray = null;
  71019. // Push each faces.
  71020. for (var k = 0; k < 6; k++) {
  71021. var dataFace = null;
  71022. // To be deprecated.
  71023. if (version === 1) {
  71024. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y...
  71025. dataFace = data[j];
  71026. }
  71027. // If special cases.
  71028. if (!mipmapGenerator && dataFace) {
  71029. if (!scene.getEngine().getCaps().textureFloat) {
  71030. // 3 channels of 1 bytes per pixel in bytes.
  71031. var byteBuffer = new ArrayBuffer(faceSize);
  71032. byteArray = new Uint8Array(byteBuffer);
  71033. }
  71034. for (var i = 0; i < _this._size * _this._size; i++) {
  71035. // Put in gamma space if requested.
  71036. if (_this._useInGammaSpace) {
  71037. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  71038. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  71039. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  71040. }
  71041. // Convert to int texture for fallback.
  71042. if (byteArray) {
  71043. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  71044. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  71045. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  71046. // May use luminance instead if the result is not accurate.
  71047. var max = Math.max(Math.max(r, g), b);
  71048. if (max > 255) {
  71049. var scale = 255 / max;
  71050. r *= scale;
  71051. g *= scale;
  71052. b *= scale;
  71053. }
  71054. byteArray[(i * 3) + 0] = r;
  71055. byteArray[(i * 3) + 1] = g;
  71056. byteArray[(i * 3) + 2] = b;
  71057. }
  71058. }
  71059. }
  71060. // Fill the array accordingly.
  71061. if (byteArray) {
  71062. results.push(byteArray);
  71063. }
  71064. else {
  71065. results.push(dataFace);
  71066. }
  71067. }
  71068. return results;
  71069. };
  71070. if (scene) {
  71071. 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, mipmapGenerator, this._onLoad, this._onError);
  71072. }
  71073. };
  71074. /**
  71075. * Occurs when the file is raw .hdr file.
  71076. */
  71077. HDRCubeTexture.prototype.loadHDRTexture = function () {
  71078. var _this = this;
  71079. var callback = function (buffer) {
  71080. var scene = _this.getScene();
  71081. if (!scene) {
  71082. return null;
  71083. }
  71084. // Extract the raw linear data.
  71085. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  71086. // Generate harmonics if needed.
  71087. if (_this._generateHarmonics) {
  71088. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  71089. _this.sphericalPolynomial = sphericalPolynomial;
  71090. }
  71091. var results = [];
  71092. var byteArray = null;
  71093. // Push each faces.
  71094. for (var j = 0; j < 6; j++) {
  71095. // Create uintarray fallback.
  71096. if (!scene.getEngine().getCaps().textureFloat) {
  71097. // 3 channels of 1 bytes per pixel in bytes.
  71098. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  71099. byteArray = new Uint8Array(byteBuffer);
  71100. }
  71101. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  71102. // If special cases.
  71103. if (_this._useInGammaSpace || byteArray) {
  71104. for (var i = 0; i < _this._size * _this._size; i++) {
  71105. // Put in gamma space if requested.
  71106. if (_this._useInGammaSpace) {
  71107. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  71108. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  71109. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  71110. }
  71111. // Convert to int texture for fallback.
  71112. if (byteArray) {
  71113. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  71114. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  71115. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  71116. // May use luminance instead if the result is not accurate.
  71117. var max = Math.max(Math.max(r, g), b);
  71118. if (max > 255) {
  71119. var scale = 255 / max;
  71120. r *= scale;
  71121. g *= scale;
  71122. b *= scale;
  71123. }
  71124. byteArray[(i * 3) + 0] = r;
  71125. byteArray[(i * 3) + 1] = g;
  71126. byteArray[(i * 3) + 2] = b;
  71127. }
  71128. }
  71129. }
  71130. if (byteArray) {
  71131. results.push(byteArray);
  71132. }
  71133. else {
  71134. results.push(dataFace);
  71135. }
  71136. }
  71137. return results;
  71138. };
  71139. var mipmapGenerator = null;
  71140. // TODO. Implement In code PMREM Generator following the LYS toolset generation.
  71141. // if (!this._noMipmap &&
  71142. // this._usePMREMGenerator) {
  71143. // mipmapGenerator = (data: ArrayBufferView[]) => {
  71144. // // Custom setup of the generator matching with the PBR shader values.
  71145. // var generator = new BABYLON.PMREMGenerator(data,
  71146. // this._size,
  71147. // this._size,
  71148. // 0,
  71149. // 3,
  71150. // this.getScene().getEngine().getCaps().textureFloat,
  71151. // 2048,
  71152. // 0.25,
  71153. // false,
  71154. // true);
  71155. // return generator.filterCubeMap();
  71156. // };
  71157. // }
  71158. var scene = this.getScene();
  71159. if (scene) {
  71160. 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, mipmapGenerator, this._onLoad, this._onError);
  71161. }
  71162. };
  71163. /**
  71164. * Starts the loading process of the texture.
  71165. */
  71166. HDRCubeTexture.prototype.loadTexture = function () {
  71167. if (this._isBABYLONPreprocessed) {
  71168. this.loadBabylonTexture();
  71169. }
  71170. else {
  71171. this.loadHDRTexture();
  71172. }
  71173. };
  71174. HDRCubeTexture.prototype.clone = function () {
  71175. var scene = this.getScene();
  71176. if (!scene) {
  71177. return this;
  71178. }
  71179. var size = (this._isBABYLONPreprocessed ? null : this._size);
  71180. var newTexture = new HDRCubeTexture(this.url, scene, size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  71181. // Base texture
  71182. newTexture.level = this.level;
  71183. newTexture.wrapU = this.wrapU;
  71184. newTexture.wrapV = this.wrapV;
  71185. newTexture.coordinatesIndex = this.coordinatesIndex;
  71186. newTexture.coordinatesMode = this.coordinatesMode;
  71187. return newTexture;
  71188. };
  71189. // Methods
  71190. HDRCubeTexture.prototype.delayLoad = function () {
  71191. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  71192. return;
  71193. }
  71194. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  71195. this._texture = this._getFromCache(this.url, this._noMipmap);
  71196. if (!this._texture) {
  71197. this.loadTexture();
  71198. }
  71199. };
  71200. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  71201. return this._textureMatrix;
  71202. };
  71203. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  71204. this._textureMatrix = value;
  71205. };
  71206. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  71207. var texture = null;
  71208. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  71209. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  71210. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  71211. texture.name = parsedTexture.name;
  71212. texture.hasAlpha = parsedTexture.hasAlpha;
  71213. texture.level = parsedTexture.level;
  71214. texture.coordinatesMode = parsedTexture.coordinatesMode;
  71215. texture.isBlocking = parsedTexture.isBlocking;
  71216. }
  71217. return texture;
  71218. };
  71219. HDRCubeTexture.prototype.serialize = function () {
  71220. if (!this.name) {
  71221. return null;
  71222. }
  71223. var serializationObject = {};
  71224. serializationObject.name = this.name;
  71225. serializationObject.hasAlpha = this.hasAlpha;
  71226. serializationObject.isCube = true;
  71227. serializationObject.level = this.level;
  71228. serializationObject.size = this._size;
  71229. serializationObject.coordinatesMode = this.coordinatesMode;
  71230. serializationObject.useInGammaSpace = this._useInGammaSpace;
  71231. serializationObject.generateHarmonics = this._generateHarmonics;
  71232. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  71233. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  71234. serializationObject.customType = "BABYLON.HDRCubeTexture";
  71235. serializationObject.noMipmap = this._noMipmap;
  71236. serializationObject.isBlocking = this._isBlocking;
  71237. return serializationObject;
  71238. };
  71239. /**
  71240. * Saves as a file the data contained in the texture in a binary format.
  71241. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  71242. * as the spherical used in the lighting.
  71243. * @param url The HDR file url.
  71244. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  71245. * @param onError Method called if any error happens during download.
  71246. * @return The packed binary data.
  71247. */
  71248. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  71249. if (onError === void 0) { onError = null; }
  71250. var callback = function (buffer) {
  71251. var data = new Blob([buffer], { type: 'application/octet-stream' });
  71252. // Returns a URL you can use as a href.
  71253. var objUrl = window.URL.createObjectURL(data);
  71254. // Simulates a link to it and click to dowload.
  71255. var a = document.createElement("a");
  71256. document.body.appendChild(a);
  71257. a.style.display = "none";
  71258. a.href = objUrl;
  71259. a.download = "envmap.babylon.hdr";
  71260. a.click();
  71261. };
  71262. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  71263. };
  71264. /**
  71265. * Serializes the data contained in the texture in a binary format.
  71266. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  71267. * as the spherical used in the lighting.
  71268. * @param url The HDR file url.
  71269. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  71270. * @param onError Method called if any error happens during download.
  71271. * @return The packed binary data.
  71272. */
  71273. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  71274. if (onError === void 0) { onError = null; }
  71275. // Needs the url tho create the texture.
  71276. if (!url) {
  71277. return;
  71278. }
  71279. // Check Power of two size.
  71280. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  71281. return;
  71282. }
  71283. // Coming Back in 3.x.
  71284. BABYLON.Tools.Error("Generation of Babylon HDR is coming back in 3.2.");
  71285. };
  71286. HDRCubeTexture._facesMapping = [
  71287. "right",
  71288. "left",
  71289. "up",
  71290. "down",
  71291. "front",
  71292. "back"
  71293. ];
  71294. return HDRCubeTexture;
  71295. }(BABYLON.BaseTexture));
  71296. BABYLON.HDRCubeTexture = HDRCubeTexture;
  71297. })(BABYLON || (BABYLON = {}));
  71298. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  71299. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  71300. // Huge respect for a such great lib.
  71301. // Earcut license:
  71302. // Copyright (c) 2016, Mapbox
  71303. //
  71304. // Permission to use, copy, modify, and/or distribute this software for any purpose
  71305. // with or without fee is hereby granted, provided that the above copyright notice
  71306. // and this permission notice appear in all copies.
  71307. //
  71308. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  71309. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  71310. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  71311. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  71312. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  71313. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  71314. // THIS SOFTWARE.
  71315. var Earcut;
  71316. (function (Earcut) {
  71317. /**
  71318. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  71319. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  71320. * @param holeIndices is an array of hole indices if any (e.g. [5, 8] for a 12- vertice input would mean one hole with vertices 5–7 and another with 8–11).
  71321. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  71322. */
  71323. function earcut(data, holeIndices, dim) {
  71324. dim = dim || 2;
  71325. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = new Array();
  71326. if (!outerNode)
  71327. return triangles;
  71328. var minX = 0, minY = 0, maxX, maxY, x, y, size = 0;
  71329. if (hasHoles)
  71330. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  71331. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  71332. if (data.length > 80 * dim) {
  71333. minX = maxX = data[0];
  71334. minY = maxY = data[1];
  71335. for (var i = dim; i < outerLen; i += dim) {
  71336. x = data[i];
  71337. y = data[i + 1];
  71338. if (x < minX)
  71339. minX = x;
  71340. if (y < minY)
  71341. minY = y;
  71342. if (x > maxX)
  71343. maxX = x;
  71344. if (y > maxY)
  71345. maxY = y;
  71346. }
  71347. // minX, minY and size are later used to transform coords into integers for z-order calculation
  71348. size = Math.max(maxX - minX, maxY - minY);
  71349. }
  71350. earcutLinked(outerNode, triangles, dim, minX, minY, size, 0);
  71351. return triangles;
  71352. }
  71353. Earcut.earcut = earcut;
  71354. var Node = /** @class */ (function () {
  71355. function Node(i, x, y) {
  71356. this.i = i;
  71357. this.x = x;
  71358. this.y = y;
  71359. this.prev = null;
  71360. this.next = null;
  71361. this.z = null;
  71362. this.prevZ = null;
  71363. this.nextZ = null;
  71364. this.steiner = false;
  71365. }
  71366. return Node;
  71367. }());
  71368. // create a circular doubly linked list from polygon points in the specified winding order
  71369. function linkedList(data, start, end, dim, clockwise) {
  71370. var i, last = null;
  71371. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  71372. for (i = start; i < end; i += dim)
  71373. last = insertNode(i, data[i], data[i + 1], last);
  71374. }
  71375. else {
  71376. for (i = end - dim; i >= start; i -= dim)
  71377. last = insertNode(i, data[i], data[i + 1], last);
  71378. }
  71379. if (last && equals(last, last.next)) {
  71380. removeNode(last);
  71381. last = last.next;
  71382. }
  71383. return last;
  71384. }
  71385. // eliminate colinear or duplicate points
  71386. function filterPoints(start, end) {
  71387. if (!start)
  71388. return start;
  71389. if (!end)
  71390. end = start;
  71391. var p = start, again;
  71392. do {
  71393. again = false;
  71394. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  71395. removeNode(p);
  71396. p = end = p.prev;
  71397. if (p === p.next)
  71398. return undefined;
  71399. again = true;
  71400. }
  71401. else {
  71402. p = p.next;
  71403. }
  71404. } while (again || p !== end);
  71405. return end;
  71406. }
  71407. // main ear slicing loop which triangulates a polygon (given as a linked list)
  71408. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  71409. if (!ear)
  71410. return;
  71411. // interlink polygon nodes in z-order
  71412. if (!pass && size)
  71413. indexCurve(ear, minX, minY, size);
  71414. var stop = ear, prev, next;
  71415. // iterate through ears, slicing them one by one
  71416. while (ear.prev !== ear.next) {
  71417. prev = ear.prev;
  71418. next = ear.next;
  71419. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  71420. // cut off the triangle
  71421. triangles.push(prev.i / dim);
  71422. triangles.push(ear.i / dim);
  71423. triangles.push(next.i / dim);
  71424. removeNode(ear);
  71425. // skipping the next vertice leads to less sliver triangles
  71426. ear = next.next;
  71427. stop = next.next;
  71428. continue;
  71429. }
  71430. ear = next;
  71431. // if we looped through the whole remaining polygon and can't find any more ears
  71432. if (ear === stop) {
  71433. // try filtering points and slicing again
  71434. if (!pass) {
  71435. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  71436. // if this didn't work, try curing all small self-intersections locally
  71437. }
  71438. else if (pass === 1) {
  71439. ear = cureLocalIntersections(ear, triangles, dim);
  71440. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  71441. // as a last resort, try splitting the remaining polygon into two
  71442. }
  71443. else if (pass === 2) {
  71444. splitEarcut(ear, triangles, dim, minX, minY, size);
  71445. }
  71446. break;
  71447. }
  71448. }
  71449. }
  71450. // check whether a polygon node forms a valid ear with adjacent nodes
  71451. function isEar(ear) {
  71452. var a = ear.prev, b = ear, c = ear.next;
  71453. if (area(a, b, c) >= 0)
  71454. return false; // reflex, can't be an ear
  71455. // now make sure we don't have other points inside the potential ear
  71456. var p = ear.next.next;
  71457. while (p !== ear.prev) {
  71458. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  71459. area(p.prev, p, p.next) >= 0)
  71460. return false;
  71461. p = p.next;
  71462. }
  71463. return true;
  71464. }
  71465. function isEarHashed(ear, minX, minY, size) {
  71466. var a = ear.prev, b = ear, c = ear.next;
  71467. if (area(a, b, c) >= 0)
  71468. return false; // reflex, can't be an ear
  71469. // triangle bbox; min & max are calculated like this for speed
  71470. var minTX = a.x < b.x ? (a.x < c.x ? a.x : c.x) : (b.x < c.x ? b.x : c.x), minTY = a.y < b.y ? (a.y < c.y ? a.y : c.y) : (b.y < c.y ? b.y : c.y), maxTX = a.x > b.x ? (a.x > c.x ? a.x : c.x) : (b.x > c.x ? b.x : c.x), maxTY = a.y > b.y ? (a.y > c.y ? a.y : c.y) : (b.y > c.y ? b.y : c.y);
  71471. // z-order range for the current triangle bbox;
  71472. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  71473. // first look for points inside the triangle in increasing z-order
  71474. var p = ear.nextZ;
  71475. while (p && p.z <= maxZ) {
  71476. if (p !== ear.prev &&
  71477. p !== ear.next &&
  71478. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  71479. area(p.prev, p, p.next) >= 0)
  71480. return false;
  71481. p = p.nextZ;
  71482. }
  71483. // then look for points in decreasing z-order
  71484. p = ear.prevZ;
  71485. while (p && p.z >= minZ) {
  71486. if (p !== ear.prev &&
  71487. p !== ear.next &&
  71488. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  71489. area(p.prev, p, p.next) >= 0)
  71490. return false;
  71491. p = p.prevZ;
  71492. }
  71493. return true;
  71494. }
  71495. // go through all polygon nodes and cure small local self-intersections
  71496. function cureLocalIntersections(start, triangles, dim) {
  71497. var p = start;
  71498. do {
  71499. var a = p.prev, b = p.next.next;
  71500. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  71501. triangles.push(a.i / dim);
  71502. triangles.push(p.i / dim);
  71503. triangles.push(b.i / dim);
  71504. // remove two nodes involved
  71505. removeNode(p);
  71506. removeNode(p.next);
  71507. p = start = b;
  71508. }
  71509. p = p.next;
  71510. } while (p !== start);
  71511. return p;
  71512. }
  71513. // try splitting polygon into two and triangulate them independently
  71514. function splitEarcut(start, triangles, dim, minX, minY, size) {
  71515. // look for a valid diagonal that divides the polygon into two
  71516. var a = start;
  71517. do {
  71518. var b = a.next.next;
  71519. while (b !== a.prev) {
  71520. if (a.i !== b.i && isValidDiagonal(a, b)) {
  71521. // split the polygon in two by the diagonal
  71522. var c = splitPolygon(a, b);
  71523. // filter colinear points around the cuts
  71524. a = filterPoints(a, a.next);
  71525. c = filterPoints(c, c.next);
  71526. // run earcut on each half
  71527. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  71528. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  71529. return;
  71530. }
  71531. b = b.next;
  71532. }
  71533. a = a.next;
  71534. } while (a !== start);
  71535. }
  71536. // link every hole into the outer loop, producing a single-ring polygon without holes
  71537. function eliminateHoles(data, holeIndices, outerNode, dim) {
  71538. var queue = [], i, len, start, end, list;
  71539. for (i = 0, len = holeIndices.length; i < len; i++) {
  71540. start = holeIndices[i] * dim;
  71541. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  71542. list = linkedList(data, start, end, dim, false);
  71543. if (list === list.next)
  71544. list.steiner = true;
  71545. queue.push(getLeftmost(list));
  71546. }
  71547. queue.sort(compareX);
  71548. // process holes from left to right
  71549. for (i = 0; i < queue.length; i++) {
  71550. eliminateHole(queue[i], outerNode);
  71551. outerNode = filterPoints(outerNode, outerNode.next);
  71552. }
  71553. return outerNode;
  71554. }
  71555. function compareX(a, b) {
  71556. return a.x - b.x;
  71557. }
  71558. // find a bridge between vertices that connects hole with an outer ring and and link it
  71559. function eliminateHole(hole, outerNode) {
  71560. outerNode = findHoleBridge(hole, outerNode);
  71561. if (outerNode) {
  71562. var b = splitPolygon(outerNode, hole);
  71563. filterPoints(b, b.next);
  71564. }
  71565. }
  71566. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  71567. function findHoleBridge(hole, outerNode) {
  71568. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  71569. // find a segment intersected by a ray from the hole's leftmost point to the left;
  71570. // segment's endpoint with lesser x will be potential connection point
  71571. do {
  71572. if (hy <= p.y && hy >= p.next.y) {
  71573. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  71574. if (x <= hx && x > qx) {
  71575. qx = x;
  71576. if (x === hx) {
  71577. if (hy === p.y)
  71578. return p;
  71579. if (hy === p.next.y)
  71580. return p.next;
  71581. }
  71582. m = p.x < p.next.x ? p : p.next;
  71583. }
  71584. }
  71585. p = p.next;
  71586. } while (p !== outerNode);
  71587. if (!m)
  71588. return null;
  71589. if (hx === qx)
  71590. return m.prev; // hole touches outer segment; pick lower endpoint
  71591. // look for points inside the triangle of hole point, segment intersection and endpoint;
  71592. // if there are no points found, we have a valid connection;
  71593. // otherwise choose the point of the minimum angle with the ray as connection point
  71594. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  71595. p = m.next;
  71596. while (p !== stop) {
  71597. if (hx >= p.x &&
  71598. p.x >= mx &&
  71599. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  71600. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  71601. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  71602. m = p;
  71603. tanMin = tan;
  71604. }
  71605. }
  71606. p = p.next;
  71607. }
  71608. return m;
  71609. }
  71610. // interlink polygon nodes in z-order
  71611. function indexCurve(start, minX, minY, size) {
  71612. var p = start;
  71613. do {
  71614. if (p.z === null)
  71615. p.z = zOrder(p.x, p.y, minX, minY, size);
  71616. p.prevZ = p.prev;
  71617. p.nextZ = p.next;
  71618. p = p.next;
  71619. } while (p !== start);
  71620. p.prevZ.nextZ = null;
  71621. p.prevZ = null;
  71622. sortLinked(p);
  71623. }
  71624. // Simon Tatham's linked list merge sort algorithm
  71625. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  71626. function sortLinked(list) {
  71627. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  71628. do {
  71629. p = list;
  71630. list = null;
  71631. tail = null;
  71632. numMerges = 0;
  71633. while (p) {
  71634. numMerges++;
  71635. q = p;
  71636. pSize = 0;
  71637. for (i = 0; i < inSize; i++) {
  71638. pSize++;
  71639. q = q.nextZ;
  71640. if (!q)
  71641. break;
  71642. }
  71643. qSize = inSize;
  71644. while (pSize > 0 || (qSize > 0 && q)) {
  71645. if (pSize === 0) {
  71646. e = q;
  71647. q = q.nextZ;
  71648. qSize--;
  71649. }
  71650. else if (qSize === 0 || !q) {
  71651. e = p;
  71652. p = p.nextZ;
  71653. pSize--;
  71654. }
  71655. else if (p.z <= q.z) {
  71656. e = p;
  71657. p = p.nextZ;
  71658. pSize--;
  71659. }
  71660. else {
  71661. e = q;
  71662. q = q.nextZ;
  71663. qSize--;
  71664. }
  71665. if (tail)
  71666. tail.nextZ = e;
  71667. else
  71668. list = e;
  71669. e.prevZ = tail;
  71670. tail = e;
  71671. }
  71672. p = q;
  71673. }
  71674. tail.nextZ = null;
  71675. inSize *= 2;
  71676. } while (numMerges > 1);
  71677. return list;
  71678. }
  71679. // z-order of a point given coords and size of the data bounding box
  71680. function zOrder(x, y, minX, minY, size) {
  71681. // coords are transformed into non-negative 15-bit integer range
  71682. x = 32767 * (x - minX) / size;
  71683. y = 32767 * (y - minY) / size;
  71684. x = (x | (x << 8)) & 0x00FF00FF;
  71685. x = (x | (x << 4)) & 0x0F0F0F0F;
  71686. x = (x | (x << 2)) & 0x33333333;
  71687. x = (x | (x << 1)) & 0x55555555;
  71688. y = (y | (y << 8)) & 0x00FF00FF;
  71689. y = (y | (y << 4)) & 0x0F0F0F0F;
  71690. y = (y | (y << 2)) & 0x33333333;
  71691. y = (y | (y << 1)) & 0x55555555;
  71692. return x | (y << 1);
  71693. }
  71694. // find the leftmost node of a polygon ring
  71695. function getLeftmost(start) {
  71696. var p = start, leftmost = start;
  71697. do {
  71698. if (p.x < leftmost.x)
  71699. leftmost = p;
  71700. p = p.next;
  71701. } while (p !== start);
  71702. return leftmost;
  71703. }
  71704. // check if a point lies within a convex triangle
  71705. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  71706. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  71707. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  71708. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  71709. }
  71710. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  71711. function isValidDiagonal(a, b) {
  71712. return a.next.i !== b.i &&
  71713. a.prev.i !== b.i &&
  71714. !intersectsPolygon(a, b) &&
  71715. locallyInside(a, b) &&
  71716. locallyInside(b, a) &&
  71717. middleInside(a, b);
  71718. }
  71719. // signed area of a triangle
  71720. function area(p, q, r) {
  71721. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  71722. }
  71723. // check if two points are equal
  71724. function equals(p1, p2) {
  71725. return p1.x === p2.x && p1.y === p2.y;
  71726. }
  71727. // check if two segments intersect
  71728. function intersects(p1, q1, p2, q2) {
  71729. if ((equals(p1, q1) && equals(p2, q2)) ||
  71730. (equals(p1, q2) && equals(p2, q1)))
  71731. return true;
  71732. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  71733. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  71734. }
  71735. // check if a polygon diagonal intersects any polygon segments
  71736. function intersectsPolygon(a, b) {
  71737. var p = a;
  71738. do {
  71739. if (p.i !== a.i &&
  71740. p.next.i !== a.i &&
  71741. p.i !== b.i &&
  71742. p.next.i !== b.i &&
  71743. intersects(p, p.next, a, b))
  71744. return true;
  71745. p = p.next;
  71746. } while (p !== a);
  71747. return false;
  71748. }
  71749. // check if a polygon diagonal is locally inside the polygon
  71750. function locallyInside(a, b) {
  71751. return area(a.prev, a, a.next) < 0
  71752. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  71753. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  71754. }
  71755. // check if the middle point of a polygon diagonal is inside the polygon
  71756. function middleInside(a, b) {
  71757. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  71758. do {
  71759. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  71760. inside = !inside;
  71761. p = p.next;
  71762. } while (p !== a);
  71763. return inside;
  71764. }
  71765. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  71766. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  71767. function splitPolygon(a, b) {
  71768. var a2 = new Node(a.i, a.x, a.y), b2 = new Node(b.i, b.x, b.y), an = a.next, bp = b.prev;
  71769. a.next = b;
  71770. b.prev = a;
  71771. a2.next = an;
  71772. an.prev = a2;
  71773. b2.next = a2;
  71774. a2.prev = b2;
  71775. bp.next = b2;
  71776. b2.prev = bp;
  71777. return b2;
  71778. }
  71779. // create a node and optionally link it with previous one (in a circular doubly linked list)
  71780. function insertNode(i, x, y, last) {
  71781. var p = new Node(i, x, y);
  71782. if (!last) {
  71783. p.prev = p;
  71784. p.next = p;
  71785. }
  71786. else {
  71787. p.next = last.next;
  71788. p.prev = last;
  71789. last.next.prev = p;
  71790. last.next = p;
  71791. }
  71792. return p;
  71793. }
  71794. function removeNode(p) {
  71795. p.next.prev = p.prev;
  71796. p.prev.next = p.next;
  71797. if (p.prevZ)
  71798. p.prevZ.nextZ = p.nextZ;
  71799. if (p.nextZ)
  71800. p.nextZ.prevZ = p.prevZ;
  71801. }
  71802. /**
  71803. * return a percentage difference between the polygon area and its triangulation area;
  71804. * used to verify correctness of triangulation
  71805. */
  71806. function deviation(data, holeIndices, dim, triangles) {
  71807. var hasHoles = holeIndices && holeIndices.length;
  71808. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  71809. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  71810. if (hasHoles) {
  71811. for (var i = 0, len = holeIndices.length; i < len; i++) {
  71812. var start = holeIndices[i] * dim;
  71813. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  71814. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  71815. }
  71816. }
  71817. var trianglesArea = 0;
  71818. for (i = 0; i < triangles.length; i += 3) {
  71819. var a = triangles[i] * dim;
  71820. var b = triangles[i + 1] * dim;
  71821. var c = triangles[i + 2] * dim;
  71822. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  71823. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  71824. }
  71825. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  71826. }
  71827. Earcut.deviation = deviation;
  71828. ;
  71829. function signedArea(data, start, end, dim) {
  71830. var sum = 0;
  71831. for (var i = start, j = end - dim; i < end; i += dim) {
  71832. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  71833. j = i;
  71834. }
  71835. return sum;
  71836. }
  71837. /**
  71838. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  71839. */
  71840. function flatten(data) {
  71841. var dim = data[0][0].length, result = { vertices: new Array(), holes: new Array(), dimensions: dim }, holeIndex = 0;
  71842. for (var i = 0; i < data.length; i++) {
  71843. for (var j = 0; j < data[i].length; j++) {
  71844. for (var d = 0; d < dim; d++)
  71845. result.vertices.push(data[i][j][d]);
  71846. }
  71847. if (i > 0) {
  71848. holeIndex += data[i - 1].length;
  71849. result.holes.push(holeIndex);
  71850. }
  71851. }
  71852. return result;
  71853. }
  71854. Earcut.flatten = flatten;
  71855. ;
  71856. })(Earcut || (Earcut = {}));
  71857. //# sourceMappingURL=babylon.earcut.js.map
  71858. var BABYLON;
  71859. (function (BABYLON) {
  71860. var IndexedVector2 = /** @class */ (function (_super) {
  71861. __extends(IndexedVector2, _super);
  71862. function IndexedVector2(original, index) {
  71863. var _this = _super.call(this, original.x, original.y) || this;
  71864. _this.index = index;
  71865. return _this;
  71866. }
  71867. return IndexedVector2;
  71868. }(BABYLON.Vector2));
  71869. var PolygonPoints = /** @class */ (function () {
  71870. function PolygonPoints() {
  71871. this.elements = new Array();
  71872. }
  71873. PolygonPoints.prototype.add = function (originalPoints) {
  71874. var _this = this;
  71875. var result = new Array();
  71876. originalPoints.forEach(function (point) {
  71877. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  71878. var newPoint = new IndexedVector2(point, _this.elements.length);
  71879. result.push(newPoint);
  71880. _this.elements.push(newPoint);
  71881. }
  71882. });
  71883. return result;
  71884. };
  71885. PolygonPoints.prototype.computeBounds = function () {
  71886. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  71887. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  71888. this.elements.forEach(function (point) {
  71889. // x
  71890. if (point.x < lmin.x) {
  71891. lmin.x = point.x;
  71892. }
  71893. else if (point.x > lmax.x) {
  71894. lmax.x = point.x;
  71895. }
  71896. // y
  71897. if (point.y < lmin.y) {
  71898. lmin.y = point.y;
  71899. }
  71900. else if (point.y > lmax.y) {
  71901. lmax.y = point.y;
  71902. }
  71903. });
  71904. return {
  71905. min: lmin,
  71906. max: lmax,
  71907. width: lmax.x - lmin.x,
  71908. height: lmax.y - lmin.y
  71909. };
  71910. };
  71911. return PolygonPoints;
  71912. }());
  71913. var Polygon = /** @class */ (function () {
  71914. function Polygon() {
  71915. }
  71916. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  71917. return [
  71918. new BABYLON.Vector2(xmin, ymin),
  71919. new BABYLON.Vector2(xmax, ymin),
  71920. new BABYLON.Vector2(xmax, ymax),
  71921. new BABYLON.Vector2(xmin, ymax)
  71922. ];
  71923. };
  71924. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  71925. if (cx === void 0) { cx = 0; }
  71926. if (cy === void 0) { cy = 0; }
  71927. if (numberOfSides === void 0) { numberOfSides = 32; }
  71928. var result = new Array();
  71929. var angle = 0;
  71930. var increment = (Math.PI * 2) / numberOfSides;
  71931. for (var i = 0; i < numberOfSides; i++) {
  71932. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  71933. angle -= increment;
  71934. }
  71935. return result;
  71936. };
  71937. Polygon.Parse = function (input) {
  71938. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  71939. var i, result = [];
  71940. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  71941. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  71942. }
  71943. return result;
  71944. };
  71945. Polygon.StartingAt = function (x, y) {
  71946. return BABYLON.Path2.StartingAt(x, y);
  71947. };
  71948. return Polygon;
  71949. }());
  71950. BABYLON.Polygon = Polygon;
  71951. var PolygonMeshBuilder = /** @class */ (function () {
  71952. function PolygonMeshBuilder(name, contours, scene) {
  71953. this._points = new PolygonPoints();
  71954. this._outlinepoints = new PolygonPoints();
  71955. this._holes = new Array();
  71956. this._epoints = new Array();
  71957. this._eholes = new Array();
  71958. this._name = name;
  71959. this._scene = scene;
  71960. var points;
  71961. if (contours instanceof BABYLON.Path2) {
  71962. points = contours.getPoints();
  71963. }
  71964. else {
  71965. points = contours;
  71966. }
  71967. this._addToepoint(points);
  71968. this._points.add(points);
  71969. this._outlinepoints.add(points);
  71970. }
  71971. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  71972. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  71973. var p = points_1[_i];
  71974. this._epoints.push(p.x, p.y);
  71975. }
  71976. };
  71977. PolygonMeshBuilder.prototype.addHole = function (hole) {
  71978. this._points.add(hole);
  71979. var holepoints = new PolygonPoints();
  71980. holepoints.add(hole);
  71981. this._holes.push(holepoints);
  71982. this._eholes.push(this._epoints.length / 2);
  71983. this._addToepoint(hole);
  71984. return this;
  71985. };
  71986. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  71987. var _this = this;
  71988. if (updatable === void 0) { updatable = false; }
  71989. if (depth === void 0) { depth = 0; }
  71990. var result = new BABYLON.Mesh(this._name, this._scene);
  71991. var normals = new Array();
  71992. var positions = new Array();
  71993. var uvs = new Array();
  71994. var bounds = this._points.computeBounds();
  71995. this._points.elements.forEach(function (p) {
  71996. normals.push(0, 1.0, 0);
  71997. positions.push(p.x, 0, p.y);
  71998. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  71999. });
  72000. var indices = new Array();
  72001. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  72002. for (var i = 0; i < res.length; i++) {
  72003. indices.push(res[i]);
  72004. }
  72005. if (depth > 0) {
  72006. var positionscount = (positions.length / 3); //get the current pointcount
  72007. this._points.elements.forEach(function (p) {
  72008. normals.push(0, -1.0, 0);
  72009. positions.push(p.x, -depth, p.y);
  72010. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  72011. });
  72012. var totalCount = indices.length;
  72013. for (var i = 0; i < totalCount; i += 3) {
  72014. var i0 = indices[i + 0];
  72015. var i1 = indices[i + 1];
  72016. var i2 = indices[i + 2];
  72017. indices.push(i2 + positionscount);
  72018. indices.push(i1 + positionscount);
  72019. indices.push(i0 + positionscount);
  72020. }
  72021. //Add the sides
  72022. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  72023. this._holes.forEach(function (hole) {
  72024. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  72025. });
  72026. }
  72027. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  72028. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  72029. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  72030. result.setIndices(indices);
  72031. return result;
  72032. };
  72033. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  72034. var StartIndex = positions.length / 3;
  72035. var ulength = 0;
  72036. for (var i = 0; i < points.elements.length; i++) {
  72037. var p = points.elements[i];
  72038. var p1;
  72039. if ((i + 1) > points.elements.length - 1) {
  72040. p1 = points.elements[0];
  72041. }
  72042. else {
  72043. p1 = points.elements[i + 1];
  72044. }
  72045. positions.push(p.x, 0, p.y);
  72046. positions.push(p.x, -depth, p.y);
  72047. positions.push(p1.x, 0, p1.y);
  72048. positions.push(p1.x, -depth, p1.y);
  72049. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  72050. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  72051. var v3 = v2.subtract(v1);
  72052. var v4 = new BABYLON.Vector3(0, 1, 0);
  72053. var vn = BABYLON.Vector3.Cross(v3, v4);
  72054. vn = vn.normalize();
  72055. uvs.push(ulength / bounds.width, 0);
  72056. uvs.push(ulength / bounds.width, 1);
  72057. ulength += v3.length();
  72058. uvs.push((ulength / bounds.width), 0);
  72059. uvs.push((ulength / bounds.width), 1);
  72060. if (!flip) {
  72061. normals.push(-vn.x, -vn.y, -vn.z);
  72062. normals.push(-vn.x, -vn.y, -vn.z);
  72063. normals.push(-vn.x, -vn.y, -vn.z);
  72064. normals.push(-vn.x, -vn.y, -vn.z);
  72065. indices.push(StartIndex);
  72066. indices.push(StartIndex + 1);
  72067. indices.push(StartIndex + 2);
  72068. indices.push(StartIndex + 1);
  72069. indices.push(StartIndex + 3);
  72070. indices.push(StartIndex + 2);
  72071. }
  72072. else {
  72073. normals.push(vn.x, vn.y, vn.z);
  72074. normals.push(vn.x, vn.y, vn.z);
  72075. normals.push(vn.x, vn.y, vn.z);
  72076. normals.push(vn.x, vn.y, vn.z);
  72077. indices.push(StartIndex);
  72078. indices.push(StartIndex + 2);
  72079. indices.push(StartIndex + 1);
  72080. indices.push(StartIndex + 1);
  72081. indices.push(StartIndex + 2);
  72082. indices.push(StartIndex + 3);
  72083. }
  72084. StartIndex += 4;
  72085. }
  72086. ;
  72087. };
  72088. return PolygonMeshBuilder;
  72089. }());
  72090. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  72091. })(BABYLON || (BABYLON = {}));
  72092. //# sourceMappingURL=babylon.polygonMesh.js.map
  72093. var BABYLON;
  72094. (function (BABYLON) {
  72095. // Unique ID when we import meshes from Babylon to CSG
  72096. var currentCSGMeshId = 0;
  72097. // # class Vertex
  72098. // Represents a vertex of a polygon. Use your own vertex class instead of this
  72099. // one to provide additional features like texture coordinates and vertex
  72100. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  72101. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  72102. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  72103. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  72104. // is not used anywhere else.
  72105. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  72106. var Vertex = /** @class */ (function () {
  72107. function Vertex(pos, normal, uv) {
  72108. this.pos = pos;
  72109. this.normal = normal;
  72110. this.uv = uv;
  72111. }
  72112. Vertex.prototype.clone = function () {
  72113. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  72114. };
  72115. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  72116. // orientation of a polygon is flipped.
  72117. Vertex.prototype.flip = function () {
  72118. this.normal = this.normal.scale(-1);
  72119. };
  72120. // Create a new vertex between this vertex and `other` by linearly
  72121. // interpolating all properties using a parameter of `t`. Subclasses should
  72122. // override this to interpolate additional properties.
  72123. Vertex.prototype.interpolate = function (other, t) {
  72124. 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));
  72125. };
  72126. return Vertex;
  72127. }());
  72128. // # class Plane
  72129. // Represents a plane in 3D space.
  72130. var Plane = /** @class */ (function () {
  72131. function Plane(normal, w) {
  72132. this.normal = normal;
  72133. this.w = w;
  72134. }
  72135. Plane.FromPoints = function (a, b, c) {
  72136. var v0 = c.subtract(a);
  72137. var v1 = b.subtract(a);
  72138. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  72139. return null;
  72140. }
  72141. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  72142. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  72143. };
  72144. Plane.prototype.clone = function () {
  72145. return new Plane(this.normal.clone(), this.w);
  72146. };
  72147. Plane.prototype.flip = function () {
  72148. this.normal.scaleInPlace(-1);
  72149. this.w = -this.w;
  72150. };
  72151. // Split `polygon` by this plane if needed, then put the polygon or polygon
  72152. // fragments in the appropriate lists. Coplanar polygons go into either
  72153. // `coplanarFront` or `coplanarBack` depending on their orientation with
  72154. // respect to this plane. Polygons in front or in back of this plane go into
  72155. // either `front` or `back`.
  72156. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  72157. var COPLANAR = 0;
  72158. var FRONT = 1;
  72159. var BACK = 2;
  72160. var SPANNING = 3;
  72161. // Classify each point as well as the entire polygon into one of the above
  72162. // four classes.
  72163. var polygonType = 0;
  72164. var types = [];
  72165. var i;
  72166. var t;
  72167. for (i = 0; i < polygon.vertices.length; i++) {
  72168. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  72169. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  72170. polygonType |= type;
  72171. types.push(type);
  72172. }
  72173. // Put the polygon in the correct list, splitting it when necessary.
  72174. switch (polygonType) {
  72175. case COPLANAR:
  72176. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  72177. break;
  72178. case FRONT:
  72179. front.push(polygon);
  72180. break;
  72181. case BACK:
  72182. back.push(polygon);
  72183. break;
  72184. case SPANNING:
  72185. var f = [], b = [];
  72186. for (i = 0; i < polygon.vertices.length; i++) {
  72187. var j = (i + 1) % polygon.vertices.length;
  72188. var ti = types[i], tj = types[j];
  72189. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  72190. if (ti !== BACK)
  72191. f.push(vi);
  72192. if (ti !== FRONT)
  72193. b.push(ti !== BACK ? vi.clone() : vi);
  72194. if ((ti | tj) === SPANNING) {
  72195. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  72196. var v = vi.interpolate(vj, t);
  72197. f.push(v);
  72198. b.push(v.clone());
  72199. }
  72200. }
  72201. var poly;
  72202. if (f.length >= 3) {
  72203. poly = new Polygon(f, polygon.shared);
  72204. if (poly.plane)
  72205. front.push(poly);
  72206. }
  72207. if (b.length >= 3) {
  72208. poly = new Polygon(b, polygon.shared);
  72209. if (poly.plane)
  72210. back.push(poly);
  72211. }
  72212. break;
  72213. }
  72214. };
  72215. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  72216. // point is on the plane.
  72217. Plane.EPSILON = 1e-5;
  72218. return Plane;
  72219. }());
  72220. // # class Polygon
  72221. // Represents a convex polygon. The vertices used to initialize a polygon must
  72222. // be coplanar and form a convex loop.
  72223. //
  72224. // Each convex polygon has a `shared` property, which is shared between all
  72225. // polygons that are clones of each other or were split from the same polygon.
  72226. // This can be used to define per-polygon properties (such as surface color).
  72227. var Polygon = /** @class */ (function () {
  72228. function Polygon(vertices, shared) {
  72229. this.vertices = vertices;
  72230. this.shared = shared;
  72231. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  72232. }
  72233. Polygon.prototype.clone = function () {
  72234. var vertices = this.vertices.map(function (v) { return v.clone(); });
  72235. return new Polygon(vertices, this.shared);
  72236. };
  72237. Polygon.prototype.flip = function () {
  72238. this.vertices.reverse().map(function (v) { v.flip(); });
  72239. this.plane.flip();
  72240. };
  72241. return Polygon;
  72242. }());
  72243. // # class Node
  72244. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  72245. // by picking a polygon to split along. That polygon (and all other coplanar
  72246. // polygons) are added directly to that node and the other polygons are added to
  72247. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  72248. // no distinction between internal and leaf nodes.
  72249. var Node = /** @class */ (function () {
  72250. function Node(polygons) {
  72251. this.plane = null;
  72252. this.front = null;
  72253. this.back = null;
  72254. this.polygons = new Array();
  72255. if (polygons) {
  72256. this.build(polygons);
  72257. }
  72258. }
  72259. Node.prototype.clone = function () {
  72260. var node = new Node();
  72261. node.plane = this.plane && this.plane.clone();
  72262. node.front = this.front && this.front.clone();
  72263. node.back = this.back && this.back.clone();
  72264. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  72265. return node;
  72266. };
  72267. // Convert solid space to empty space and empty space to solid space.
  72268. Node.prototype.invert = function () {
  72269. for (var i = 0; i < this.polygons.length; i++) {
  72270. this.polygons[i].flip();
  72271. }
  72272. if (this.plane) {
  72273. this.plane.flip();
  72274. }
  72275. if (this.front) {
  72276. this.front.invert();
  72277. }
  72278. if (this.back) {
  72279. this.back.invert();
  72280. }
  72281. var temp = this.front;
  72282. this.front = this.back;
  72283. this.back = temp;
  72284. };
  72285. // Recursively remove all polygons in `polygons` that are inside this BSP
  72286. // tree.
  72287. Node.prototype.clipPolygons = function (polygons) {
  72288. if (!this.plane)
  72289. return polygons.slice();
  72290. var front = new Array(), back = new Array();
  72291. for (var i = 0; i < polygons.length; i++) {
  72292. this.plane.splitPolygon(polygons[i], front, back, front, back);
  72293. }
  72294. if (this.front) {
  72295. front = this.front.clipPolygons(front);
  72296. }
  72297. if (this.back) {
  72298. back = this.back.clipPolygons(back);
  72299. }
  72300. else {
  72301. back = [];
  72302. }
  72303. return front.concat(back);
  72304. };
  72305. // Remove all polygons in this BSP tree that are inside the other BSP tree
  72306. // `bsp`.
  72307. Node.prototype.clipTo = function (bsp) {
  72308. this.polygons = bsp.clipPolygons(this.polygons);
  72309. if (this.front)
  72310. this.front.clipTo(bsp);
  72311. if (this.back)
  72312. this.back.clipTo(bsp);
  72313. };
  72314. // Return a list of all polygons in this BSP tree.
  72315. Node.prototype.allPolygons = function () {
  72316. var polygons = this.polygons.slice();
  72317. if (this.front)
  72318. polygons = polygons.concat(this.front.allPolygons());
  72319. if (this.back)
  72320. polygons = polygons.concat(this.back.allPolygons());
  72321. return polygons;
  72322. };
  72323. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  72324. // new polygons are filtered down to the bottom of the tree and become new
  72325. // nodes there. Each set of polygons is partitioned using the first polygon
  72326. // (no heuristic is used to pick a good split).
  72327. Node.prototype.build = function (polygons) {
  72328. if (!polygons.length)
  72329. return;
  72330. if (!this.plane)
  72331. this.plane = polygons[0].plane.clone();
  72332. var front = new Array(), back = new Array();
  72333. for (var i = 0; i < polygons.length; i++) {
  72334. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  72335. }
  72336. if (front.length) {
  72337. if (!this.front)
  72338. this.front = new Node();
  72339. this.front.build(front);
  72340. }
  72341. if (back.length) {
  72342. if (!this.back)
  72343. this.back = new Node();
  72344. this.back.build(back);
  72345. }
  72346. };
  72347. return Node;
  72348. }());
  72349. var CSG = /** @class */ (function () {
  72350. function CSG() {
  72351. this.polygons = new Array();
  72352. }
  72353. // Convert BABYLON.Mesh to BABYLON.CSG
  72354. CSG.FromMesh = function (mesh) {
  72355. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  72356. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  72357. if (mesh instanceof BABYLON.Mesh) {
  72358. mesh.computeWorldMatrix(true);
  72359. matrix = mesh.getWorldMatrix();
  72360. meshPosition = mesh.position.clone();
  72361. meshRotation = mesh.rotation.clone();
  72362. if (mesh.rotationQuaternion) {
  72363. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  72364. }
  72365. meshScaling = mesh.scaling.clone();
  72366. }
  72367. else {
  72368. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  72369. }
  72370. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  72371. var subMeshes = mesh.subMeshes;
  72372. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  72373. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  72374. vertices = [];
  72375. for (var j = 0; j < 3; j++) {
  72376. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  72377. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  72378. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  72379. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  72380. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  72381. vertex = new Vertex(position, normal, uv);
  72382. vertices.push(vertex);
  72383. }
  72384. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  72385. // To handle the case of degenerated triangle
  72386. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  72387. if (polygon.plane)
  72388. polygons.push(polygon);
  72389. }
  72390. }
  72391. var csg = CSG.FromPolygons(polygons);
  72392. csg.matrix = matrix;
  72393. csg.position = meshPosition;
  72394. csg.rotation = meshRotation;
  72395. csg.scaling = meshScaling;
  72396. csg.rotationQuaternion = meshRotationQuaternion;
  72397. currentCSGMeshId++;
  72398. return csg;
  72399. };
  72400. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  72401. CSG.FromPolygons = function (polygons) {
  72402. var csg = new CSG();
  72403. csg.polygons = polygons;
  72404. return csg;
  72405. };
  72406. CSG.prototype.clone = function () {
  72407. var csg = new CSG();
  72408. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  72409. csg.copyTransformAttributes(this);
  72410. return csg;
  72411. };
  72412. CSG.prototype.union = function (csg) {
  72413. var a = new Node(this.clone().polygons);
  72414. var b = new Node(csg.clone().polygons);
  72415. a.clipTo(b);
  72416. b.clipTo(a);
  72417. b.invert();
  72418. b.clipTo(a);
  72419. b.invert();
  72420. a.build(b.allPolygons());
  72421. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  72422. };
  72423. CSG.prototype.unionInPlace = function (csg) {
  72424. var a = new Node(this.polygons);
  72425. var b = new Node(csg.polygons);
  72426. a.clipTo(b);
  72427. b.clipTo(a);
  72428. b.invert();
  72429. b.clipTo(a);
  72430. b.invert();
  72431. a.build(b.allPolygons());
  72432. this.polygons = a.allPolygons();
  72433. };
  72434. CSG.prototype.subtract = function (csg) {
  72435. var a = new Node(this.clone().polygons);
  72436. var b = new Node(csg.clone().polygons);
  72437. a.invert();
  72438. a.clipTo(b);
  72439. b.clipTo(a);
  72440. b.invert();
  72441. b.clipTo(a);
  72442. b.invert();
  72443. a.build(b.allPolygons());
  72444. a.invert();
  72445. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  72446. };
  72447. CSG.prototype.subtractInPlace = function (csg) {
  72448. var a = new Node(this.polygons);
  72449. var b = new Node(csg.polygons);
  72450. a.invert();
  72451. a.clipTo(b);
  72452. b.clipTo(a);
  72453. b.invert();
  72454. b.clipTo(a);
  72455. b.invert();
  72456. a.build(b.allPolygons());
  72457. a.invert();
  72458. this.polygons = a.allPolygons();
  72459. };
  72460. CSG.prototype.intersect = function (csg) {
  72461. var a = new Node(this.clone().polygons);
  72462. var b = new Node(csg.clone().polygons);
  72463. a.invert();
  72464. b.clipTo(a);
  72465. b.invert();
  72466. a.clipTo(b);
  72467. b.clipTo(a);
  72468. a.build(b.allPolygons());
  72469. a.invert();
  72470. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  72471. };
  72472. CSG.prototype.intersectInPlace = function (csg) {
  72473. var a = new Node(this.polygons);
  72474. var b = new Node(csg.polygons);
  72475. a.invert();
  72476. b.clipTo(a);
  72477. b.invert();
  72478. a.clipTo(b);
  72479. b.clipTo(a);
  72480. a.build(b.allPolygons());
  72481. a.invert();
  72482. this.polygons = a.allPolygons();
  72483. };
  72484. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  72485. // not modified.
  72486. CSG.prototype.inverse = function () {
  72487. var csg = this.clone();
  72488. csg.inverseInPlace();
  72489. return csg;
  72490. };
  72491. CSG.prototype.inverseInPlace = function () {
  72492. this.polygons.map(function (p) { p.flip(); });
  72493. };
  72494. // This is used to keep meshes transformations so they can be restored
  72495. // when we build back a Babylon Mesh
  72496. // NB : All CSG operations are performed in world coordinates
  72497. CSG.prototype.copyTransformAttributes = function (csg) {
  72498. this.matrix = csg.matrix;
  72499. this.position = csg.position;
  72500. this.rotation = csg.rotation;
  72501. this.scaling = csg.scaling;
  72502. this.rotationQuaternion = csg.rotationQuaternion;
  72503. return this;
  72504. };
  72505. // Build Raw mesh from CSG
  72506. // Coordinates here are in world space
  72507. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  72508. var matrix = this.matrix.clone();
  72509. matrix.invert();
  72510. 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;
  72511. if (keepSubMeshes) {
  72512. // Sort Polygons, since subMeshes are indices range
  72513. polygons.sort(function (a, b) {
  72514. if (a.shared.meshId === b.shared.meshId) {
  72515. return a.shared.subMeshId - b.shared.subMeshId;
  72516. }
  72517. else {
  72518. return a.shared.meshId - b.shared.meshId;
  72519. }
  72520. });
  72521. }
  72522. for (var i = 0, il = polygons.length; i < il; i++) {
  72523. polygon = polygons[i];
  72524. // Building SubMeshes
  72525. if (!subMesh_dict[polygon.shared.meshId]) {
  72526. subMesh_dict[polygon.shared.meshId] = {};
  72527. }
  72528. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  72529. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  72530. indexStart: +Infinity,
  72531. indexEnd: -Infinity,
  72532. materialIndex: polygon.shared.materialIndex
  72533. };
  72534. }
  72535. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  72536. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  72537. polygonIndices[0] = 0;
  72538. polygonIndices[1] = j - 1;
  72539. polygonIndices[2] = j;
  72540. for (var k = 0; k < 3; k++) {
  72541. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  72542. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  72543. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  72544. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  72545. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  72546. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  72547. // Check if 2 points can be merged
  72548. if (!(typeof vertex_idx !== 'undefined' &&
  72549. normals[vertex_idx * 3] === localNormal.x &&
  72550. normals[vertex_idx * 3 + 1] === localNormal.y &&
  72551. normals[vertex_idx * 3 + 2] === localNormal.z &&
  72552. uvs[vertex_idx * 2] === uv.x &&
  72553. uvs[vertex_idx * 2 + 1] === uv.y)) {
  72554. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  72555. uvs.push(uv.x, uv.y);
  72556. normals.push(normal.x, normal.y, normal.z);
  72557. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  72558. }
  72559. indices.push(vertex_idx);
  72560. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  72561. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  72562. currentIndex++;
  72563. }
  72564. }
  72565. }
  72566. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  72567. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  72568. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  72569. mesh.setIndices(indices, null);
  72570. if (keepSubMeshes) {
  72571. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  72572. var materialIndexOffset = 0, materialMaxIndex;
  72573. mesh.subMeshes = new Array();
  72574. for (var m in subMesh_dict) {
  72575. materialMaxIndex = -1;
  72576. for (var sm in subMesh_dict[m]) {
  72577. subMesh_obj = subMesh_dict[m][sm];
  72578. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  72579. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  72580. }
  72581. materialIndexOffset += ++materialMaxIndex;
  72582. }
  72583. }
  72584. return mesh;
  72585. };
  72586. // Build Mesh from CSG taking material and transforms into account
  72587. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  72588. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  72589. mesh.material = material;
  72590. mesh.position.copyFrom(this.position);
  72591. mesh.rotation.copyFrom(this.rotation);
  72592. if (this.rotationQuaternion) {
  72593. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  72594. }
  72595. mesh.scaling.copyFrom(this.scaling);
  72596. mesh.computeWorldMatrix(true);
  72597. return mesh;
  72598. };
  72599. return CSG;
  72600. }());
  72601. BABYLON.CSG = CSG;
  72602. })(BABYLON || (BABYLON = {}));
  72603. //# sourceMappingURL=babylon.csg.js.map
  72604. var BABYLON;
  72605. (function (BABYLON) {
  72606. var LensFlare = /** @class */ (function () {
  72607. function LensFlare(size, position, color, imgUrl, system) {
  72608. this.size = size;
  72609. this.position = position;
  72610. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  72611. this.color = color || new BABYLON.Color3(1, 1, 1);
  72612. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  72613. this._system = system;
  72614. system.lensFlares.push(this);
  72615. }
  72616. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  72617. return new LensFlare(size, position, color, imgUrl, system);
  72618. };
  72619. LensFlare.prototype.dispose = function () {
  72620. if (this.texture) {
  72621. this.texture.dispose();
  72622. }
  72623. // Remove from scene
  72624. var index = this._system.lensFlares.indexOf(this);
  72625. this._system.lensFlares.splice(index, 1);
  72626. };
  72627. ;
  72628. return LensFlare;
  72629. }());
  72630. BABYLON.LensFlare = LensFlare;
  72631. })(BABYLON || (BABYLON = {}));
  72632. //# sourceMappingURL=babylon.lensFlare.js.map
  72633. var BABYLON;
  72634. (function (BABYLON) {
  72635. var LensFlareSystem = /** @class */ (function () {
  72636. function LensFlareSystem(name, emitter, scene) {
  72637. this.name = name;
  72638. this.lensFlares = new Array();
  72639. this.borderLimit = 300;
  72640. this.viewportBorder = 0;
  72641. this.layerMask = 0x0FFFFFFF;
  72642. this._vertexBuffers = {};
  72643. this._isEnabled = true;
  72644. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  72645. this._emitter = emitter;
  72646. this.id = name;
  72647. scene.lensFlareSystems.push(this);
  72648. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  72649. var engine = scene.getEngine();
  72650. // VBO
  72651. var vertices = [];
  72652. vertices.push(1, 1);
  72653. vertices.push(-1, 1);
  72654. vertices.push(-1, -1);
  72655. vertices.push(1, -1);
  72656. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  72657. // Indices
  72658. var indices = [];
  72659. indices.push(0);
  72660. indices.push(1);
  72661. indices.push(2);
  72662. indices.push(0);
  72663. indices.push(2);
  72664. indices.push(3);
  72665. this._indexBuffer = engine.createIndexBuffer(indices);
  72666. // Effects
  72667. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  72668. }
  72669. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  72670. get: function () {
  72671. return this._isEnabled;
  72672. },
  72673. set: function (value) {
  72674. this._isEnabled = value;
  72675. },
  72676. enumerable: true,
  72677. configurable: true
  72678. });
  72679. LensFlareSystem.prototype.getScene = function () {
  72680. return this._scene;
  72681. };
  72682. LensFlareSystem.prototype.getEmitter = function () {
  72683. return this._emitter;
  72684. };
  72685. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  72686. this._emitter = newEmitter;
  72687. };
  72688. LensFlareSystem.prototype.getEmitterPosition = function () {
  72689. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  72690. };
  72691. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  72692. var position = this.getEmitterPosition();
  72693. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  72694. this._positionX = position.x;
  72695. this._positionY = position.y;
  72696. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  72697. if (this.viewportBorder > 0) {
  72698. globalViewport.x -= this.viewportBorder;
  72699. globalViewport.y -= this.viewportBorder;
  72700. globalViewport.width += this.viewportBorder * 2;
  72701. globalViewport.height += this.viewportBorder * 2;
  72702. position.x += this.viewportBorder;
  72703. position.y += this.viewportBorder;
  72704. this._positionX += this.viewportBorder;
  72705. this._positionY += this.viewportBorder;
  72706. }
  72707. if (position.z > 0) {
  72708. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  72709. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  72710. return true;
  72711. }
  72712. return true;
  72713. }
  72714. return false;
  72715. };
  72716. LensFlareSystem.prototype._isVisible = function () {
  72717. if (!this._isEnabled || !this._scene.activeCamera) {
  72718. return false;
  72719. }
  72720. var emitterPosition = this.getEmitterPosition();
  72721. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  72722. var distance = direction.length();
  72723. direction.normalize();
  72724. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  72725. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  72726. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  72727. };
  72728. LensFlareSystem.prototype.render = function () {
  72729. if (!this._effect.isReady() || !this._scene.activeCamera)
  72730. return false;
  72731. var engine = this._scene.getEngine();
  72732. var viewport = this._scene.activeCamera.viewport;
  72733. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  72734. // Position
  72735. if (!this.computeEffectivePosition(globalViewport)) {
  72736. return false;
  72737. }
  72738. // Visibility
  72739. if (!this._isVisible()) {
  72740. return false;
  72741. }
  72742. // Intensity
  72743. var awayX;
  72744. var awayY;
  72745. if (this._positionX < this.borderLimit + globalViewport.x) {
  72746. awayX = this.borderLimit + globalViewport.x - this._positionX;
  72747. }
  72748. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  72749. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  72750. }
  72751. else {
  72752. awayX = 0;
  72753. }
  72754. if (this._positionY < this.borderLimit + globalViewport.y) {
  72755. awayY = this.borderLimit + globalViewport.y - this._positionY;
  72756. }
  72757. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  72758. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  72759. }
  72760. else {
  72761. awayY = 0;
  72762. }
  72763. var away = (awayX > awayY) ? awayX : awayY;
  72764. away -= this.viewportBorder;
  72765. if (away > this.borderLimit) {
  72766. away = this.borderLimit;
  72767. }
  72768. var intensity = 1.0 - (away / this.borderLimit);
  72769. if (intensity < 0) {
  72770. return false;
  72771. }
  72772. if (intensity > 1.0) {
  72773. intensity = 1.0;
  72774. }
  72775. if (this.viewportBorder > 0) {
  72776. globalViewport.x += this.viewportBorder;
  72777. globalViewport.y += this.viewportBorder;
  72778. globalViewport.width -= this.viewportBorder * 2;
  72779. globalViewport.height -= this.viewportBorder * 2;
  72780. this._positionX -= this.viewportBorder;
  72781. this._positionY -= this.viewportBorder;
  72782. }
  72783. // Position
  72784. var centerX = globalViewport.x + globalViewport.width / 2;
  72785. var centerY = globalViewport.y + globalViewport.height / 2;
  72786. var distX = centerX - this._positionX;
  72787. var distY = centerY - this._positionY;
  72788. // Effects
  72789. engine.enableEffect(this._effect);
  72790. engine.setState(false);
  72791. engine.setDepthBuffer(false);
  72792. // VBOs
  72793. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  72794. // Flares
  72795. for (var index = 0; index < this.lensFlares.length; index++) {
  72796. var flare = this.lensFlares[index];
  72797. engine.setAlphaMode(flare.alphaMode);
  72798. var x = centerX - (distX * flare.position);
  72799. var y = centerY - (distY * flare.position);
  72800. var cw = flare.size;
  72801. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  72802. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  72803. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  72804. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  72805. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  72806. // Texture
  72807. this._effect.setTexture("textureSampler", flare.texture);
  72808. // Color
  72809. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  72810. // Draw order
  72811. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  72812. }
  72813. engine.setDepthBuffer(true);
  72814. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  72815. return true;
  72816. };
  72817. LensFlareSystem.prototype.dispose = function () {
  72818. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  72819. if (vertexBuffer) {
  72820. vertexBuffer.dispose();
  72821. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  72822. }
  72823. if (this._indexBuffer) {
  72824. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  72825. this._indexBuffer = null;
  72826. }
  72827. while (this.lensFlares.length) {
  72828. this.lensFlares[0].dispose();
  72829. }
  72830. // Remove from scene
  72831. var index = this._scene.lensFlareSystems.indexOf(this);
  72832. this._scene.lensFlareSystems.splice(index, 1);
  72833. };
  72834. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  72835. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  72836. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  72837. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  72838. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  72839. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  72840. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  72841. var parsedFlare = parsedLensFlareSystem.flares[index];
  72842. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  72843. }
  72844. return lensFlareSystem;
  72845. };
  72846. LensFlareSystem.prototype.serialize = function () {
  72847. var serializationObject = {};
  72848. serializationObject.id = this.id;
  72849. serializationObject.name = this.name;
  72850. serializationObject.emitterId = this.getEmitter().id;
  72851. serializationObject.borderLimit = this.borderLimit;
  72852. serializationObject.flares = [];
  72853. for (var index = 0; index < this.lensFlares.length; index++) {
  72854. var flare = this.lensFlares[index];
  72855. serializationObject.flares.push({
  72856. size: flare.size,
  72857. position: flare.position,
  72858. color: flare.color.asArray(),
  72859. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  72860. });
  72861. }
  72862. return serializationObject;
  72863. };
  72864. return LensFlareSystem;
  72865. }());
  72866. BABYLON.LensFlareSystem = LensFlareSystem;
  72867. })(BABYLON || (BABYLON = {}));
  72868. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  72869. var BABYLON;
  72870. (function (BABYLON) {
  72871. /**
  72872. * This is a holder class for the physics joint created by the physics plugin.
  72873. * It holds a set of functions to control the underlying joint.
  72874. */
  72875. var PhysicsJoint = /** @class */ (function () {
  72876. function PhysicsJoint(type, jointData) {
  72877. this.type = type;
  72878. this.jointData = jointData;
  72879. jointData.nativeParams = jointData.nativeParams || {};
  72880. }
  72881. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  72882. get: function () {
  72883. return this._physicsJoint;
  72884. },
  72885. set: function (newJoint) {
  72886. if (this._physicsJoint) {
  72887. //remove from the wolrd
  72888. }
  72889. this._physicsJoint = newJoint;
  72890. },
  72891. enumerable: true,
  72892. configurable: true
  72893. });
  72894. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  72895. set: function (physicsPlugin) {
  72896. this._physicsPlugin = physicsPlugin;
  72897. },
  72898. enumerable: true,
  72899. configurable: true
  72900. });
  72901. /**
  72902. * Execute a function that is physics-plugin specific.
  72903. * @param {Function} func the function that will be executed.
  72904. * It accepts two parameters: the physics world and the physics joint.
  72905. */
  72906. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  72907. func(this._physicsPlugin.world, this._physicsJoint);
  72908. };
  72909. //TODO check if the native joints are the same
  72910. //Joint Types
  72911. PhysicsJoint.DistanceJoint = 0;
  72912. PhysicsJoint.HingeJoint = 1;
  72913. PhysicsJoint.BallAndSocketJoint = 2;
  72914. PhysicsJoint.WheelJoint = 3;
  72915. PhysicsJoint.SliderJoint = 4;
  72916. //OIMO
  72917. PhysicsJoint.PrismaticJoint = 5;
  72918. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  72919. PhysicsJoint.UniversalJoint = 6;
  72920. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  72921. //Cannon
  72922. //Similar to a Ball-Joint. Different in params
  72923. PhysicsJoint.PointToPointJoint = 8;
  72924. //Cannon only at the moment
  72925. PhysicsJoint.SpringJoint = 9;
  72926. PhysicsJoint.LockJoint = 10;
  72927. return PhysicsJoint;
  72928. }());
  72929. BABYLON.PhysicsJoint = PhysicsJoint;
  72930. /**
  72931. * A class representing a physics distance joint.
  72932. */
  72933. var DistanceJoint = /** @class */ (function (_super) {
  72934. __extends(DistanceJoint, _super);
  72935. function DistanceJoint(jointData) {
  72936. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  72937. }
  72938. /**
  72939. * Update the predefined distance.
  72940. */
  72941. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  72942. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  72943. };
  72944. return DistanceJoint;
  72945. }(PhysicsJoint));
  72946. BABYLON.DistanceJoint = DistanceJoint;
  72947. var MotorEnabledJoint = /** @class */ (function (_super) {
  72948. __extends(MotorEnabledJoint, _super);
  72949. function MotorEnabledJoint(type, jointData) {
  72950. return _super.call(this, type, jointData) || this;
  72951. }
  72952. /**
  72953. * Set the motor values.
  72954. * Attention, this function is plugin specific. Engines won't react 100% the same.
  72955. * @param {number} force the force to apply
  72956. * @param {number} maxForce max force for this motor.
  72957. */
  72958. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  72959. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  72960. };
  72961. /**
  72962. * Set the motor's limits.
  72963. * Attention, this function is plugin specific. Engines won't react 100% the same.
  72964. */
  72965. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  72966. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  72967. };
  72968. return MotorEnabledJoint;
  72969. }(PhysicsJoint));
  72970. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  72971. /**
  72972. * This class represents a single hinge physics joint
  72973. */
  72974. var HingeJoint = /** @class */ (function (_super) {
  72975. __extends(HingeJoint, _super);
  72976. function HingeJoint(jointData) {
  72977. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  72978. }
  72979. /**
  72980. * Set the motor values.
  72981. * Attention, this function is plugin specific. Engines won't react 100% the same.
  72982. * @param {number} force the force to apply
  72983. * @param {number} maxForce max force for this motor.
  72984. */
  72985. HingeJoint.prototype.setMotor = function (force, maxForce) {
  72986. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  72987. };
  72988. /**
  72989. * Set the motor's limits.
  72990. * Attention, this function is plugin specific. Engines won't react 100% the same.
  72991. */
  72992. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  72993. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  72994. };
  72995. return HingeJoint;
  72996. }(MotorEnabledJoint));
  72997. BABYLON.HingeJoint = HingeJoint;
  72998. /**
  72999. * This class represents a dual hinge physics joint (same as wheel joint)
  73000. */
  73001. var Hinge2Joint = /** @class */ (function (_super) {
  73002. __extends(Hinge2Joint, _super);
  73003. function Hinge2Joint(jointData) {
  73004. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  73005. }
  73006. /**
  73007. * Set the motor values.
  73008. * Attention, this function is plugin specific. Engines won't react 100% the same.
  73009. * @param {number} force the force to apply
  73010. * @param {number} maxForce max force for this motor.
  73011. * @param {motorIndex} the motor's index, 0 or 1.
  73012. */
  73013. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  73014. if (motorIndex === void 0) { motorIndex = 0; }
  73015. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  73016. };
  73017. /**
  73018. * Set the motor limits.
  73019. * Attention, this function is plugin specific. Engines won't react 100% the same.
  73020. * @param {number} upperLimit the upper limit
  73021. * @param {number} lowerLimit lower limit
  73022. * @param {motorIndex} the motor's index, 0 or 1.
  73023. */
  73024. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  73025. if (motorIndex === void 0) { motorIndex = 0; }
  73026. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  73027. };
  73028. return Hinge2Joint;
  73029. }(MotorEnabledJoint));
  73030. BABYLON.Hinge2Joint = Hinge2Joint;
  73031. })(BABYLON || (BABYLON = {}));
  73032. //# sourceMappingURL=babylon.physicsJoint.js.map
  73033. var BABYLON;
  73034. (function (BABYLON) {
  73035. var PhysicsImpostor = /** @class */ (function () {
  73036. function PhysicsImpostor(object, type, _options, _scene) {
  73037. if (_options === void 0) { _options = { mass: 0 }; }
  73038. var _this = this;
  73039. this.object = object;
  73040. this.type = type;
  73041. this._options = _options;
  73042. this._scene = _scene;
  73043. this._bodyUpdateRequired = false;
  73044. this._onBeforePhysicsStepCallbacks = new Array();
  73045. this._onAfterPhysicsStepCallbacks = new Array();
  73046. this._onPhysicsCollideCallbacks = [];
  73047. this._deltaPosition = BABYLON.Vector3.Zero();
  73048. this._isDisposed = false;
  73049. //temp variables for parent rotation calculations
  73050. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  73051. this._tmpQuat = new BABYLON.Quaternion();
  73052. this._tmpQuat2 = new BABYLON.Quaternion();
  73053. /**
  73054. * this function is executed by the physics engine.
  73055. */
  73056. this.beforeStep = function () {
  73057. if (!_this._physicsEngine) {
  73058. return;
  73059. }
  73060. _this.object.translate(_this._deltaPosition, -1);
  73061. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  73062. _this.object.computeWorldMatrix(false);
  73063. if (_this.object.parent && _this.object.rotationQuaternion) {
  73064. _this.getParentsRotation();
  73065. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  73066. }
  73067. else {
  73068. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  73069. }
  73070. if (!_this._options.disableBidirectionalTransformation) {
  73071. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  73072. }
  73073. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  73074. func(_this);
  73075. });
  73076. };
  73077. /**
  73078. * this function is executed by the physics engine.
  73079. */
  73080. this.afterStep = function () {
  73081. if (!_this._physicsEngine) {
  73082. return;
  73083. }
  73084. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  73085. func(_this);
  73086. });
  73087. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  73088. // object has now its world rotation. needs to be converted to local.
  73089. if (_this.object.parent && _this.object.rotationQuaternion) {
  73090. _this.getParentsRotation();
  73091. _this._tmpQuat.conjugateInPlace();
  73092. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  73093. }
  73094. // take the position set and make it the absolute position of this object.
  73095. _this.object.setAbsolutePosition(_this.object.position);
  73096. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  73097. _this.object.translate(_this._deltaPosition, 1);
  73098. };
  73099. /**
  73100. * Legacy collision detection event support
  73101. */
  73102. this.onCollideEvent = null;
  73103. //event and body object due to cannon's event-based architecture.
  73104. this.onCollide = function (e) {
  73105. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  73106. return;
  73107. }
  73108. if (!_this._physicsEngine) {
  73109. return;
  73110. }
  73111. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  73112. if (otherImpostor) {
  73113. // Legacy collision detection event support
  73114. if (_this.onCollideEvent) {
  73115. _this.onCollideEvent(_this, otherImpostor);
  73116. }
  73117. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  73118. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  73119. }).forEach(function (obj) {
  73120. obj.callback(_this, otherImpostor);
  73121. });
  73122. }
  73123. };
  73124. //sanity check!
  73125. if (!this.object) {
  73126. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  73127. return;
  73128. }
  73129. //legacy support for old syntax.
  73130. if (!this._scene && object.getScene) {
  73131. this._scene = object.getScene();
  73132. }
  73133. if (!this._scene) {
  73134. return;
  73135. }
  73136. this._physicsEngine = this._scene.getPhysicsEngine();
  73137. if (!this._physicsEngine) {
  73138. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  73139. }
  73140. else {
  73141. //set the object's quaternion, if not set
  73142. if (!this.object.rotationQuaternion) {
  73143. if (this.object.rotation) {
  73144. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  73145. }
  73146. else {
  73147. this.object.rotationQuaternion = new BABYLON.Quaternion();
  73148. }
  73149. }
  73150. //default options params
  73151. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  73152. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  73153. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  73154. this._joints = [];
  73155. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  73156. if (!this.object.parent || this._options.ignoreParent) {
  73157. this._init();
  73158. }
  73159. else if (this.object.parent.physicsImpostor) {
  73160. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  73161. }
  73162. }
  73163. }
  73164. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  73165. get: function () {
  73166. return this._isDisposed;
  73167. },
  73168. enumerable: true,
  73169. configurable: true
  73170. });
  73171. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  73172. get: function () {
  73173. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  73174. },
  73175. set: function (value) {
  73176. this.setMass(value);
  73177. },
  73178. enumerable: true,
  73179. configurable: true
  73180. });
  73181. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  73182. get: function () {
  73183. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  73184. },
  73185. set: function (value) {
  73186. if (!this._physicsEngine) {
  73187. return;
  73188. }
  73189. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  73190. },
  73191. enumerable: true,
  73192. configurable: true
  73193. });
  73194. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  73195. get: function () {
  73196. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  73197. },
  73198. set: function (value) {
  73199. if (!this._physicsEngine) {
  73200. return;
  73201. }
  73202. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  73203. },
  73204. enumerable: true,
  73205. configurable: true
  73206. });
  73207. /**
  73208. * This function will completly initialize this impostor.
  73209. * It will create a new body - but only if this mesh has no parent.
  73210. * If it has, this impostor will not be used other than to define the impostor
  73211. * of the child mesh.
  73212. */
  73213. PhysicsImpostor.prototype._init = function () {
  73214. if (!this._physicsEngine) {
  73215. return;
  73216. }
  73217. this._physicsEngine.removeImpostor(this);
  73218. this.physicsBody = null;
  73219. this._parent = this._parent || this._getPhysicsParent();
  73220. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  73221. this._physicsEngine.addImpostor(this);
  73222. }
  73223. };
  73224. PhysicsImpostor.prototype._getPhysicsParent = function () {
  73225. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  73226. var parentMesh = this.object.parent;
  73227. return parentMesh.physicsImpostor;
  73228. }
  73229. return null;
  73230. };
  73231. /**
  73232. * Should a new body be generated.
  73233. */
  73234. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  73235. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  73236. };
  73237. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  73238. this.forceUpdate();
  73239. };
  73240. /**
  73241. * Force a regeneration of this or the parent's impostor's body.
  73242. * Use under cautious - This will remove all joints already implemented.
  73243. */
  73244. PhysicsImpostor.prototype.forceUpdate = function () {
  73245. this._init();
  73246. if (this.parent && !this._options.ignoreParent) {
  73247. this.parent.forceUpdate();
  73248. }
  73249. };
  73250. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  73251. /*public get mesh(): AbstractMesh {
  73252. return this._mesh;
  73253. }*/
  73254. /**
  73255. * Gets the body that holds this impostor. Either its own, or its parent.
  73256. */
  73257. get: function () {
  73258. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  73259. },
  73260. /**
  73261. * Set the physics body. Used mainly by the physics engine/plugin
  73262. */
  73263. set: function (physicsBody) {
  73264. if (this._physicsBody && this._physicsEngine) {
  73265. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  73266. }
  73267. this._physicsBody = physicsBody;
  73268. this.resetUpdateFlags();
  73269. },
  73270. enumerable: true,
  73271. configurable: true
  73272. });
  73273. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  73274. get: function () {
  73275. return !this._options.ignoreParent && this._parent ? this._parent : null;
  73276. },
  73277. set: function (value) {
  73278. this._parent = value;
  73279. },
  73280. enumerable: true,
  73281. configurable: true
  73282. });
  73283. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  73284. this._bodyUpdateRequired = false;
  73285. };
  73286. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  73287. if (this.object.getBoundingInfo) {
  73288. var q = this.object.rotationQuaternion;
  73289. //reset rotation
  73290. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  73291. //calculate the world matrix with no rotation
  73292. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  73293. var boundingInfo = this.object.getBoundingInfo();
  73294. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  73295. //bring back the rotation
  73296. this.object.rotationQuaternion = q;
  73297. //calculate the world matrix with the new rotation
  73298. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  73299. return size;
  73300. }
  73301. else {
  73302. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  73303. }
  73304. };
  73305. PhysicsImpostor.prototype.getObjectCenter = function () {
  73306. if (this.object.getBoundingInfo) {
  73307. var boundingInfo = this.object.getBoundingInfo();
  73308. return boundingInfo.boundingBox.centerWorld;
  73309. }
  73310. else {
  73311. return this.object.position;
  73312. }
  73313. };
  73314. /**
  73315. * Get a specific parametes from the options parameter.
  73316. */
  73317. PhysicsImpostor.prototype.getParam = function (paramName) {
  73318. return this._options[paramName];
  73319. };
  73320. /**
  73321. * Sets a specific parameter in the options given to the physics plugin
  73322. */
  73323. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  73324. this._options[paramName] = value;
  73325. this._bodyUpdateRequired = true;
  73326. };
  73327. /**
  73328. * Specifically change the body's mass option. Won't recreate the physics body object
  73329. */
  73330. PhysicsImpostor.prototype.setMass = function (mass) {
  73331. if (this.getParam("mass") !== mass) {
  73332. this.setParam("mass", mass);
  73333. }
  73334. if (this._physicsEngine) {
  73335. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  73336. }
  73337. };
  73338. PhysicsImpostor.prototype.getLinearVelocity = function () {
  73339. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  73340. };
  73341. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  73342. if (this._physicsEngine) {
  73343. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  73344. }
  73345. };
  73346. PhysicsImpostor.prototype.getAngularVelocity = function () {
  73347. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  73348. };
  73349. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  73350. if (this._physicsEngine) {
  73351. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  73352. }
  73353. };
  73354. /**
  73355. * Execute a function with the physics plugin native code.
  73356. * Provide a function the will have two variables - the world object and the physics body object.
  73357. */
  73358. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  73359. if (this._physicsEngine) {
  73360. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  73361. }
  73362. };
  73363. /**
  73364. * Register a function that will be executed before the physics world is stepping forward.
  73365. */
  73366. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  73367. this._onBeforePhysicsStepCallbacks.push(func);
  73368. };
  73369. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  73370. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  73371. if (index > -1) {
  73372. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  73373. }
  73374. else {
  73375. BABYLON.Tools.Warn("Function to remove was not found");
  73376. }
  73377. };
  73378. /**
  73379. * Register a function that will be executed after the physics step
  73380. */
  73381. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  73382. this._onAfterPhysicsStepCallbacks.push(func);
  73383. };
  73384. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  73385. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  73386. if (index > -1) {
  73387. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  73388. }
  73389. else {
  73390. BABYLON.Tools.Warn("Function to remove was not found");
  73391. }
  73392. };
  73393. /**
  73394. * register a function that will be executed when this impostor collides against a different body.
  73395. */
  73396. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  73397. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  73398. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  73399. };
  73400. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  73401. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  73402. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  73403. if (index > -1) {
  73404. this._onPhysicsCollideCallbacks.splice(index, 1);
  73405. }
  73406. else {
  73407. BABYLON.Tools.Warn("Function to remove was not found");
  73408. }
  73409. };
  73410. PhysicsImpostor.prototype.getParentsRotation = function () {
  73411. var parent = this.object.parent;
  73412. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  73413. while (parent) {
  73414. if (parent.rotationQuaternion) {
  73415. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  73416. }
  73417. else {
  73418. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  73419. }
  73420. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  73421. parent = parent.parent;
  73422. }
  73423. return this._tmpQuat;
  73424. };
  73425. /**
  73426. * Apply a force
  73427. */
  73428. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  73429. if (this._physicsEngine) {
  73430. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  73431. }
  73432. return this;
  73433. };
  73434. /**
  73435. * Apply an impulse
  73436. */
  73437. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  73438. if (this._physicsEngine) {
  73439. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  73440. }
  73441. return this;
  73442. };
  73443. /**
  73444. * A help function to create a joint.
  73445. */
  73446. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  73447. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  73448. this.addJoint(otherImpostor, joint);
  73449. return this;
  73450. };
  73451. /**
  73452. * Add a joint to this impostor with a different impostor.
  73453. */
  73454. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  73455. this._joints.push({
  73456. otherImpostor: otherImpostor,
  73457. joint: joint
  73458. });
  73459. if (this._physicsEngine) {
  73460. this._physicsEngine.addJoint(this, otherImpostor, joint);
  73461. }
  73462. return this;
  73463. };
  73464. /**
  73465. * Will keep this body still, in a sleep mode.
  73466. */
  73467. PhysicsImpostor.prototype.sleep = function () {
  73468. if (this._physicsEngine) {
  73469. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  73470. }
  73471. return this;
  73472. };
  73473. /**
  73474. * Wake the body up.
  73475. */
  73476. PhysicsImpostor.prototype.wakeUp = function () {
  73477. if (this._physicsEngine) {
  73478. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  73479. }
  73480. return this;
  73481. };
  73482. PhysicsImpostor.prototype.clone = function (newObject) {
  73483. if (!newObject)
  73484. return null;
  73485. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  73486. };
  73487. PhysicsImpostor.prototype.dispose = function () {
  73488. var _this = this;
  73489. //no dispose if no physics engine is available.
  73490. if (!this._physicsEngine) {
  73491. return;
  73492. }
  73493. this._joints.forEach(function (j) {
  73494. if (_this._physicsEngine) {
  73495. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  73496. }
  73497. });
  73498. //dispose the physics body
  73499. this._physicsEngine.removeImpostor(this);
  73500. if (this.parent) {
  73501. this.parent.forceUpdate();
  73502. }
  73503. else {
  73504. /*this._object.getChildMeshes().forEach(function(mesh) {
  73505. if (mesh.physicsImpostor) {
  73506. if (disposeChildren) {
  73507. mesh.physicsImpostor.dispose();
  73508. mesh.physicsImpostor = null;
  73509. }
  73510. }
  73511. })*/
  73512. }
  73513. this._isDisposed = true;
  73514. };
  73515. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  73516. this._deltaPosition.copyFrom(position);
  73517. };
  73518. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  73519. if (!this._deltaRotation) {
  73520. this._deltaRotation = new BABYLON.Quaternion();
  73521. }
  73522. this._deltaRotation.copyFrom(rotation);
  73523. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  73524. };
  73525. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  73526. if (this._physicsEngine) {
  73527. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  73528. }
  73529. return this;
  73530. };
  73531. PhysicsImpostor.prototype.getRadius = function () {
  73532. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  73533. };
  73534. /**
  73535. * Sync a bone with this impostor
  73536. * @param bone The bone to sync to the impostor.
  73537. * @param boneMesh The mesh that the bone is influencing.
  73538. * @param jointPivot The pivot of the joint / bone in local space.
  73539. * @param distToJoint Optional distance from the impostor to the joint.
  73540. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  73541. */
  73542. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  73543. var tempVec = PhysicsImpostor._tmpVecs[0];
  73544. var mesh = this.object;
  73545. if (mesh.rotationQuaternion) {
  73546. if (adjustRotation) {
  73547. var tempQuat = PhysicsImpostor._tmpQuat;
  73548. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  73549. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  73550. }
  73551. else {
  73552. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  73553. }
  73554. }
  73555. tempVec.x = 0;
  73556. tempVec.y = 0;
  73557. tempVec.z = 0;
  73558. if (jointPivot) {
  73559. tempVec.x = jointPivot.x;
  73560. tempVec.y = jointPivot.y;
  73561. tempVec.z = jointPivot.z;
  73562. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  73563. if (distToJoint === undefined || distToJoint === null) {
  73564. distToJoint = jointPivot.length();
  73565. }
  73566. tempVec.x *= distToJoint;
  73567. tempVec.y *= distToJoint;
  73568. tempVec.z *= distToJoint;
  73569. }
  73570. if (bone.getParent()) {
  73571. tempVec.addInPlace(mesh.getAbsolutePosition());
  73572. bone.setAbsolutePosition(tempVec, boneMesh);
  73573. }
  73574. else {
  73575. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  73576. boneMesh.position.x -= tempVec.x;
  73577. boneMesh.position.y -= tempVec.y;
  73578. boneMesh.position.z -= tempVec.z;
  73579. }
  73580. };
  73581. /**
  73582. * Sync impostor to a bone
  73583. * @param bone The bone that the impostor will be synced to.
  73584. * @param boneMesh The mesh that the bone is influencing.
  73585. * @param jointPivot The pivot of the joint / bone in local space.
  73586. * @param distToJoint Optional distance from the impostor to the joint.
  73587. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  73588. * @param boneAxis Optional vector3 axis the bone is aligned with
  73589. */
  73590. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  73591. var mesh = this.object;
  73592. if (mesh.rotationQuaternion) {
  73593. if (adjustRotation) {
  73594. var tempQuat = PhysicsImpostor._tmpQuat;
  73595. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  73596. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  73597. }
  73598. else {
  73599. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  73600. }
  73601. }
  73602. var pos = PhysicsImpostor._tmpVecs[0];
  73603. var boneDir = PhysicsImpostor._tmpVecs[1];
  73604. if (!boneAxis) {
  73605. boneAxis = PhysicsImpostor._tmpVecs[2];
  73606. boneAxis.x = 0;
  73607. boneAxis.y = 1;
  73608. boneAxis.z = 0;
  73609. }
  73610. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  73611. bone.getAbsolutePositionToRef(boneMesh, pos);
  73612. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  73613. distToJoint = jointPivot.length();
  73614. }
  73615. if (distToJoint !== undefined && distToJoint !== null) {
  73616. pos.x += boneDir.x * distToJoint;
  73617. pos.y += boneDir.y * distToJoint;
  73618. pos.z += boneDir.z * distToJoint;
  73619. }
  73620. mesh.setAbsolutePosition(pos);
  73621. };
  73622. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  73623. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  73624. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  73625. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  73626. //Impostor types
  73627. PhysicsImpostor.NoImpostor = 0;
  73628. PhysicsImpostor.SphereImpostor = 1;
  73629. PhysicsImpostor.BoxImpostor = 2;
  73630. PhysicsImpostor.PlaneImpostor = 3;
  73631. PhysicsImpostor.MeshImpostor = 4;
  73632. PhysicsImpostor.CylinderImpostor = 7;
  73633. PhysicsImpostor.ParticleImpostor = 8;
  73634. PhysicsImpostor.HeightmapImpostor = 9;
  73635. return PhysicsImpostor;
  73636. }());
  73637. BABYLON.PhysicsImpostor = PhysicsImpostor;
  73638. })(BABYLON || (BABYLON = {}));
  73639. //# sourceMappingURL=babylon.physicsImpostor.js.map
  73640. var BABYLON;
  73641. (function (BABYLON) {
  73642. var PhysicsEngine = /** @class */ (function () {
  73643. function PhysicsEngine(gravity, _physicsPlugin) {
  73644. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  73645. this._physicsPlugin = _physicsPlugin;
  73646. //new methods and parameters
  73647. this._impostors = [];
  73648. this._joints = [];
  73649. if (!this._physicsPlugin.isSupported()) {
  73650. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  73651. + "Please make sure it is included.");
  73652. }
  73653. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  73654. this.setGravity(gravity);
  73655. this.setTimeStep();
  73656. }
  73657. PhysicsEngine.prototype.setGravity = function (gravity) {
  73658. this.gravity = gravity;
  73659. this._physicsPlugin.setGravity(this.gravity);
  73660. };
  73661. /**
  73662. * Set the time step of the physics engine.
  73663. * default is 1/60.
  73664. * To slow it down, enter 1/600 for example.
  73665. * To speed it up, 1/30
  73666. * @param {number} newTimeStep the new timestep to apply to this world.
  73667. */
  73668. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  73669. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  73670. this._physicsPlugin.setTimeStep(newTimeStep);
  73671. };
  73672. /**
  73673. * Get the time step of the physics engine.
  73674. */
  73675. PhysicsEngine.prototype.getTimeStep = function () {
  73676. return this._physicsPlugin.getTimeStep();
  73677. };
  73678. PhysicsEngine.prototype.dispose = function () {
  73679. this._impostors.forEach(function (impostor) {
  73680. impostor.dispose();
  73681. });
  73682. this._physicsPlugin.dispose();
  73683. };
  73684. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  73685. return this._physicsPlugin.name;
  73686. };
  73687. /**
  73688. * Adding a new impostor for the impostor tracking.
  73689. * This will be done by the impostor itself.
  73690. * @param {PhysicsImpostor} impostor the impostor to add
  73691. */
  73692. PhysicsEngine.prototype.addImpostor = function (impostor) {
  73693. impostor.uniqueId = this._impostors.push(impostor);
  73694. //if no parent, generate the body
  73695. if (!impostor.parent) {
  73696. this._physicsPlugin.generatePhysicsBody(impostor);
  73697. }
  73698. };
  73699. /**
  73700. * Remove an impostor from the engine.
  73701. * This impostor and its mesh will not longer be updated by the physics engine.
  73702. * @param {PhysicsImpostor} impostor the impostor to remove
  73703. */
  73704. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  73705. var index = this._impostors.indexOf(impostor);
  73706. if (index > -1) {
  73707. var removed = this._impostors.splice(index, 1);
  73708. //Is it needed?
  73709. if (removed.length) {
  73710. //this will also remove it from the world.
  73711. removed[0].physicsBody = null;
  73712. }
  73713. }
  73714. };
  73715. /**
  73716. * Add a joint to the physics engine
  73717. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  73718. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  73719. * @param {PhysicsJoint} the joint that will connect both impostors.
  73720. */
  73721. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  73722. var impostorJoint = {
  73723. mainImpostor: mainImpostor,
  73724. connectedImpostor: connectedImpostor,
  73725. joint: joint
  73726. };
  73727. joint.physicsPlugin = this._physicsPlugin;
  73728. this._joints.push(impostorJoint);
  73729. this._physicsPlugin.generateJoint(impostorJoint);
  73730. };
  73731. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  73732. var matchingJoints = this._joints.filter(function (impostorJoint) {
  73733. return (impostorJoint.connectedImpostor === connectedImpostor
  73734. && impostorJoint.joint === joint
  73735. && impostorJoint.mainImpostor === mainImpostor);
  73736. });
  73737. if (matchingJoints.length) {
  73738. this._physicsPlugin.removeJoint(matchingJoints[0]);
  73739. //TODO remove it from the list as well
  73740. }
  73741. };
  73742. /**
  73743. * Called by the scene. no need to call it.
  73744. */
  73745. PhysicsEngine.prototype._step = function (delta) {
  73746. var _this = this;
  73747. //check if any mesh has no body / requires an update
  73748. this._impostors.forEach(function (impostor) {
  73749. if (impostor.isBodyInitRequired()) {
  73750. _this._physicsPlugin.generatePhysicsBody(impostor);
  73751. }
  73752. });
  73753. if (delta > 0.1) {
  73754. delta = 0.1;
  73755. }
  73756. else if (delta <= 0) {
  73757. delta = 1.0 / 60.0;
  73758. }
  73759. this._physicsPlugin.executeStep(delta, this._impostors);
  73760. };
  73761. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  73762. return this._physicsPlugin;
  73763. };
  73764. PhysicsEngine.prototype.getImpostors = function () {
  73765. return this._impostors;
  73766. };
  73767. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  73768. for (var i = 0; i < this._impostors.length; ++i) {
  73769. if (this._impostors[i].object === object) {
  73770. return this._impostors[i];
  73771. }
  73772. }
  73773. return null;
  73774. };
  73775. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  73776. for (var i = 0; i < this._impostors.length; ++i) {
  73777. if (this._impostors[i].physicsBody === body) {
  73778. return this._impostors[i];
  73779. }
  73780. }
  73781. return null;
  73782. };
  73783. // Statics
  73784. PhysicsEngine.Epsilon = 0.001;
  73785. return PhysicsEngine;
  73786. }());
  73787. BABYLON.PhysicsEngine = PhysicsEngine;
  73788. })(BABYLON || (BABYLON = {}));
  73789. //# sourceMappingURL=babylon.physicsEngine.js.map
  73790. var BABYLON;
  73791. (function (BABYLON) {
  73792. var PhysicsHelper = /** @class */ (function () {
  73793. function PhysicsHelper(scene) {
  73794. this._scene = scene;
  73795. this._physicsEngine = this._scene.getPhysicsEngine();
  73796. if (!this._physicsEngine) {
  73797. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  73798. }
  73799. }
  73800. /**
  73801. * @param {Vector3} origin the origin of the explosion
  73802. * @param {number} radius the explosion radius
  73803. * @param {number} strength the explosion strength
  73804. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  73805. */
  73806. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  73807. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  73808. if (!this._physicsEngine) {
  73809. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  73810. return null;
  73811. }
  73812. var impostors = this._physicsEngine.getImpostors();
  73813. if (impostors.length === 0) {
  73814. return null;
  73815. }
  73816. var event = new PhysicsRadialExplosionEvent(this._scene);
  73817. impostors.forEach(function (impostor) {
  73818. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  73819. if (!impostorForceAndContactPoint) {
  73820. return;
  73821. }
  73822. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  73823. });
  73824. event.dispose(false);
  73825. return event;
  73826. };
  73827. /**
  73828. * @param {Vector3} origin the origin of the explosion
  73829. * @param {number} radius the explosion radius
  73830. * @param {number} strength the explosion strength
  73831. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  73832. */
  73833. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  73834. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  73835. if (!this._physicsEngine) {
  73836. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  73837. return null;
  73838. }
  73839. var impostors = this._physicsEngine.getImpostors();
  73840. if (impostors.length === 0) {
  73841. return null;
  73842. }
  73843. var event = new PhysicsRadialExplosionEvent(this._scene);
  73844. impostors.forEach(function (impostor) {
  73845. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  73846. if (!impostorForceAndContactPoint) {
  73847. return;
  73848. }
  73849. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  73850. });
  73851. event.dispose(false);
  73852. return event;
  73853. };
  73854. /**
  73855. * @param {Vector3} origin the origin of the explosion
  73856. * @param {number} radius the explosion radius
  73857. * @param {number} strength the explosion strength
  73858. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  73859. */
  73860. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  73861. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  73862. if (!this._physicsEngine) {
  73863. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  73864. return null;
  73865. }
  73866. var impostors = this._physicsEngine.getImpostors();
  73867. if (impostors.length === 0) {
  73868. return null;
  73869. }
  73870. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  73871. event.dispose(false);
  73872. return event;
  73873. };
  73874. /**
  73875. * @param {Vector3} origin the origin of the updraft
  73876. * @param {number} radius the radius of the updraft
  73877. * @param {number} strength the strength of the updraft
  73878. * @param {number} height the height of the updraft
  73879. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  73880. */
  73881. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  73882. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  73883. if (!this._physicsEngine) {
  73884. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  73885. return null;
  73886. }
  73887. if (this._physicsEngine.getImpostors().length === 0) {
  73888. return null;
  73889. }
  73890. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  73891. event.dispose(false);
  73892. return event;
  73893. };
  73894. /**
  73895. * @param {Vector3} origin the of the vortex
  73896. * @param {number} radius the radius of the vortex
  73897. * @param {number} strength the strength of the vortex
  73898. * @param {number} height the height of the vortex
  73899. */
  73900. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  73901. if (!this._physicsEngine) {
  73902. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  73903. return null;
  73904. }
  73905. if (this._physicsEngine.getImpostors().length === 0) {
  73906. return null;
  73907. }
  73908. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  73909. event.dispose(false);
  73910. return event;
  73911. };
  73912. return PhysicsHelper;
  73913. }());
  73914. BABYLON.PhysicsHelper = PhysicsHelper;
  73915. /***** Radial explosion *****/
  73916. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  73917. function PhysicsRadialExplosionEvent(scene) {
  73918. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  73919. this._rays = [];
  73920. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  73921. this._scene = scene;
  73922. }
  73923. /**
  73924. * Returns the data related to the radial explosion event (sphere & rays).
  73925. * @returns {PhysicsRadialExplosionEventData}
  73926. */
  73927. PhysicsRadialExplosionEvent.prototype.getData = function () {
  73928. this._dataFetched = true;
  73929. return {
  73930. sphere: this._sphere,
  73931. rays: this._rays,
  73932. };
  73933. };
  73934. /**
  73935. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  73936. * @param impostor
  73937. * @param {Vector3} origin the origin of the explosion
  73938. * @param {number} radius the explosion radius
  73939. * @param {number} strength the explosion strength
  73940. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  73941. * @returns {Nullable<PhysicsForceAndContactPoint>}
  73942. */
  73943. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  73944. if (impostor.mass === 0) {
  73945. return null;
  73946. }
  73947. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  73948. return null;
  73949. }
  73950. if (impostor.object.getClassName() !== 'Mesh') {
  73951. return null;
  73952. }
  73953. var impostorObject = impostor.object;
  73954. var impostorObjectCenter = impostor.getObjectCenter();
  73955. var direction = impostorObjectCenter.subtract(origin);
  73956. var ray = new BABYLON.Ray(origin, direction, radius);
  73957. this._rays.push(ray);
  73958. var hit = ray.intersectsMesh(impostorObject);
  73959. var contactPoint = hit.pickedPoint;
  73960. if (!contactPoint) {
  73961. return null;
  73962. }
  73963. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  73964. if (distanceFromOrigin > radius) {
  73965. return null;
  73966. }
  73967. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  73968. ? strength
  73969. : strength * (1 - (distanceFromOrigin / radius));
  73970. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  73971. return { force: force, contactPoint: contactPoint };
  73972. };
  73973. /**
  73974. * Disposes the sphere.
  73975. * @param {bolean} force
  73976. */
  73977. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  73978. var _this = this;
  73979. if (force === void 0) { force = true; }
  73980. if (force) {
  73981. this._sphere.dispose();
  73982. }
  73983. else {
  73984. setTimeout(function () {
  73985. if (!_this._dataFetched) {
  73986. _this._sphere.dispose();
  73987. }
  73988. }, 0);
  73989. }
  73990. };
  73991. /*** Helpers ***/
  73992. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  73993. if (!this._sphere) {
  73994. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  73995. this._sphere.isVisible = false;
  73996. }
  73997. };
  73998. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  73999. var impostorObject = impostor.object;
  74000. this._prepareSphere();
  74001. this._sphere.position = origin;
  74002. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  74003. this._sphere._updateBoundingInfo();
  74004. this._sphere.computeWorldMatrix(true);
  74005. return this._sphere.intersectsMesh(impostorObject, true);
  74006. };
  74007. return PhysicsRadialExplosionEvent;
  74008. }());
  74009. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  74010. /***** Gravitational Field *****/
  74011. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  74012. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  74013. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  74014. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  74015. this._physicsHelper = physicsHelper;
  74016. this._scene = scene;
  74017. this._origin = origin;
  74018. this._radius = radius;
  74019. this._strength = strength;
  74020. this._falloff = falloff;
  74021. this._tickCallback = this._tick.bind(this);
  74022. }
  74023. /**
  74024. * Returns the data related to the gravitational field event (sphere).
  74025. * @returns {PhysicsGravitationalFieldEventData}
  74026. */
  74027. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  74028. this._dataFetched = true;
  74029. return {
  74030. sphere: this._sphere,
  74031. };
  74032. };
  74033. /**
  74034. * Enables the gravitational field.
  74035. */
  74036. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  74037. this._tickCallback.call(this);
  74038. this._scene.registerBeforeRender(this._tickCallback);
  74039. };
  74040. /**
  74041. * Disables the gravitational field.
  74042. */
  74043. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  74044. this._scene.unregisterBeforeRender(this._tickCallback);
  74045. };
  74046. /**
  74047. * Disposes the sphere.
  74048. * @param {bolean} force
  74049. */
  74050. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  74051. var _this = this;
  74052. if (force === void 0) { force = true; }
  74053. if (force) {
  74054. this._sphere.dispose();
  74055. }
  74056. else {
  74057. setTimeout(function () {
  74058. if (!_this._dataFetched) {
  74059. _this._sphere.dispose();
  74060. }
  74061. }, 0);
  74062. }
  74063. };
  74064. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  74065. // Since the params won't change, we fetch the event only once
  74066. if (this._sphere) {
  74067. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  74068. }
  74069. else {
  74070. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  74071. if (radialExplosionEvent) {
  74072. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  74073. }
  74074. }
  74075. };
  74076. return PhysicsGravitationalFieldEvent;
  74077. }());
  74078. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  74079. /***** Updraft *****/
  74080. var PhysicsUpdraftEvent = /** @class */ (function () {
  74081. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  74082. this._scene = _scene;
  74083. this._origin = _origin;
  74084. this._radius = _radius;
  74085. this._strength = _strength;
  74086. this._height = _height;
  74087. this._updraftMode = _updraftMode;
  74088. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  74089. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  74090. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  74091. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  74092. this._physicsEngine = this._scene.getPhysicsEngine();
  74093. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  74094. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  74095. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  74096. this._originDirection = this._origin.subtract(this._originTop).normalize();
  74097. }
  74098. this._tickCallback = this._tick.bind(this);
  74099. }
  74100. /**
  74101. * Returns the data related to the updraft event (cylinder).
  74102. * @returns {PhysicsUpdraftEventData}
  74103. */
  74104. PhysicsUpdraftEvent.prototype.getData = function () {
  74105. this._dataFetched = true;
  74106. return {
  74107. cylinder: this._cylinder,
  74108. };
  74109. };
  74110. /**
  74111. * Enables the updraft.
  74112. */
  74113. PhysicsUpdraftEvent.prototype.enable = function () {
  74114. this._tickCallback.call(this);
  74115. this._scene.registerBeforeRender(this._tickCallback);
  74116. };
  74117. /**
  74118. * Disables the cortex.
  74119. */
  74120. PhysicsUpdraftEvent.prototype.disable = function () {
  74121. this._scene.unregisterBeforeRender(this._tickCallback);
  74122. };
  74123. /**
  74124. * Disposes the sphere.
  74125. * @param {bolean} force
  74126. */
  74127. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  74128. var _this = this;
  74129. if (force === void 0) { force = true; }
  74130. if (force) {
  74131. this._cylinder.dispose();
  74132. }
  74133. else {
  74134. setTimeout(function () {
  74135. if (!_this._dataFetched) {
  74136. _this._cylinder.dispose();
  74137. }
  74138. }, 0);
  74139. }
  74140. };
  74141. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  74142. if (impostor.mass === 0) {
  74143. return null;
  74144. }
  74145. if (!this._intersectsWithCylinder(impostor)) {
  74146. return null;
  74147. }
  74148. var impostorObjectCenter = impostor.getObjectCenter();
  74149. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  74150. var direction = this._originDirection;
  74151. }
  74152. else {
  74153. var direction = impostorObjectCenter.subtract(this._originTop);
  74154. }
  74155. var multiplier = this._strength * -1;
  74156. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  74157. return { force: force, contactPoint: impostorObjectCenter };
  74158. };
  74159. PhysicsUpdraftEvent.prototype._tick = function () {
  74160. var _this = this;
  74161. this._physicsEngine.getImpostors().forEach(function (impostor) {
  74162. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  74163. if (!impostorForceAndContactPoint) {
  74164. return;
  74165. }
  74166. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  74167. });
  74168. };
  74169. /*** Helpers ***/
  74170. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  74171. if (!this._cylinder) {
  74172. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  74173. height: this._height,
  74174. diameter: this._radius * 2,
  74175. }, this._scene);
  74176. this._cylinder.isVisible = false;
  74177. }
  74178. };
  74179. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  74180. var impostorObject = impostor.object;
  74181. this._prepareCylinder();
  74182. this._cylinder.position = this._cylinderPosition;
  74183. return this._cylinder.intersectsMesh(impostorObject, true);
  74184. };
  74185. return PhysicsUpdraftEvent;
  74186. }());
  74187. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  74188. /***** Vortex *****/
  74189. var PhysicsVortexEvent = /** @class */ (function () {
  74190. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  74191. this._scene = _scene;
  74192. this._origin = _origin;
  74193. this._radius = _radius;
  74194. this._strength = _strength;
  74195. this._height = _height;
  74196. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  74197. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  74198. this._updraftMultiplier = 0.02;
  74199. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  74200. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  74201. this._physicsEngine = this._scene.getPhysicsEngine();
  74202. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  74203. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  74204. this._tickCallback = this._tick.bind(this);
  74205. }
  74206. /**
  74207. * Returns the data related to the vortex event (cylinder).
  74208. * @returns {PhysicsVortexEventData}
  74209. */
  74210. PhysicsVortexEvent.prototype.getData = function () {
  74211. this._dataFetched = true;
  74212. return {
  74213. cylinder: this._cylinder,
  74214. };
  74215. };
  74216. /**
  74217. * Enables the vortex.
  74218. */
  74219. PhysicsVortexEvent.prototype.enable = function () {
  74220. this._tickCallback.call(this);
  74221. this._scene.registerBeforeRender(this._tickCallback);
  74222. };
  74223. /**
  74224. * Disables the cortex.
  74225. */
  74226. PhysicsVortexEvent.prototype.disable = function () {
  74227. this._scene.unregisterBeforeRender(this._tickCallback);
  74228. };
  74229. /**
  74230. * Disposes the sphere.
  74231. * @param {bolean} force
  74232. */
  74233. PhysicsVortexEvent.prototype.dispose = function (force) {
  74234. var _this = this;
  74235. if (force === void 0) { force = true; }
  74236. if (force) {
  74237. this._cylinder.dispose();
  74238. }
  74239. else {
  74240. setTimeout(function () {
  74241. if (!_this._dataFetched) {
  74242. _this._cylinder.dispose();
  74243. }
  74244. }, 0);
  74245. }
  74246. };
  74247. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  74248. if (impostor.mass === 0) {
  74249. return null;
  74250. }
  74251. if (!this._intersectsWithCylinder(impostor)) {
  74252. return null;
  74253. }
  74254. if (impostor.object.getClassName() !== 'Mesh') {
  74255. return null;
  74256. }
  74257. var impostorObject = impostor.object;
  74258. var impostorObjectCenter = impostor.getObjectCenter();
  74259. 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)
  74260. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  74261. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  74262. var hit = ray.intersectsMesh(impostorObject);
  74263. var contactPoint = hit.pickedPoint;
  74264. if (!contactPoint) {
  74265. return null;
  74266. }
  74267. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  74268. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  74269. var directionToOrigin = contactPoint.normalize();
  74270. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  74271. directionToOrigin = directionToOrigin.negate();
  74272. }
  74273. // TODO: find a more physically based solution
  74274. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  74275. var forceX = directionToOrigin.x * this._strength / 8;
  74276. var forceY = directionToOrigin.y * this._updraftMultiplier;
  74277. var forceZ = directionToOrigin.z * this._strength / 8;
  74278. }
  74279. else {
  74280. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  74281. var forceY = this._originTop.y * this._updraftMultiplier;
  74282. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  74283. }
  74284. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  74285. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  74286. return { force: force, contactPoint: impostorObjectCenter };
  74287. };
  74288. PhysicsVortexEvent.prototype._tick = function () {
  74289. var _this = this;
  74290. this._physicsEngine.getImpostors().forEach(function (impostor) {
  74291. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  74292. if (!impostorForceAndContactPoint) {
  74293. return;
  74294. }
  74295. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  74296. });
  74297. };
  74298. /*** Helpers ***/
  74299. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  74300. if (!this._cylinder) {
  74301. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  74302. height: this._height,
  74303. diameter: this._radius * 2,
  74304. }, this._scene);
  74305. this._cylinder.isVisible = false;
  74306. }
  74307. };
  74308. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  74309. var impostorObject = impostor.object;
  74310. this._prepareCylinder();
  74311. this._cylinder.position = this._cylinderPosition;
  74312. return this._cylinder.intersectsMesh(impostorObject, true);
  74313. };
  74314. return PhysicsVortexEvent;
  74315. }());
  74316. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  74317. /***** Enums *****/
  74318. /**
  74319. * The strenght of the force in correspondence to the distance of the affected object
  74320. */
  74321. var PhysicsRadialImpulseFalloff;
  74322. (function (PhysicsRadialImpulseFalloff) {
  74323. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  74324. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear"; // impulse gets weaker if it's further from the origin
  74325. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  74326. /**
  74327. * The strenght of the force in correspondence to the distance of the affected object
  74328. */
  74329. var PhysicsUpdraftMode;
  74330. (function (PhysicsUpdraftMode) {
  74331. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  74332. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular"; // once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder
  74333. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  74334. })(BABYLON || (BABYLON = {}));
  74335. //# sourceMappingURL=babylon.physicsHelper.js.map
  74336. var BABYLON;
  74337. (function (BABYLON) {
  74338. var CannonJSPlugin = /** @class */ (function () {
  74339. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  74340. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  74341. if (iterations === void 0) { iterations = 10; }
  74342. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  74343. this.name = "CannonJSPlugin";
  74344. this._physicsMaterials = new Array();
  74345. this._fixedTimeStep = 1 / 60;
  74346. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  74347. this.BJSCANNON = typeof CANNON !== 'undefined' ? CANNON : (typeof require !== 'undefined' ? require('cannon') : undefined);
  74348. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  74349. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  74350. this._tmpPosition = BABYLON.Vector3.Zero();
  74351. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  74352. this._tmpUnityRotation = new BABYLON.Quaternion();
  74353. if (!this.isSupported()) {
  74354. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  74355. return;
  74356. }
  74357. this._extendNamespace();
  74358. this.world = new this.BJSCANNON.World();
  74359. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  74360. this.world.solver.iterations = iterations;
  74361. }
  74362. CannonJSPlugin.prototype.setGravity = function (gravity) {
  74363. this.world.gravity.copy(gravity);
  74364. };
  74365. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  74366. this._fixedTimeStep = timeStep;
  74367. };
  74368. CannonJSPlugin.prototype.getTimeStep = function () {
  74369. return this._fixedTimeStep;
  74370. };
  74371. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  74372. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  74373. };
  74374. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  74375. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  74376. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  74377. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  74378. };
  74379. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  74380. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  74381. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  74382. impostor.physicsBody.applyForce(impulse, worldPoint);
  74383. };
  74384. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  74385. //parent-child relationship. Does this impostor has a parent impostor?
  74386. if (impostor.parent) {
  74387. if (impostor.physicsBody) {
  74388. this.removePhysicsBody(impostor);
  74389. //TODO is that needed?
  74390. impostor.forceUpdate();
  74391. }
  74392. return;
  74393. }
  74394. //should a new body be created for this impostor?
  74395. if (impostor.isBodyInitRequired()) {
  74396. var shape = this._createShape(impostor);
  74397. //unregister events, if body is being changed
  74398. var oldBody = impostor.physicsBody;
  74399. if (oldBody) {
  74400. this.removePhysicsBody(impostor);
  74401. }
  74402. //create the body and material
  74403. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  74404. var bodyCreationObject = {
  74405. mass: impostor.getParam("mass"),
  74406. material: material
  74407. };
  74408. // A simple extend, in case native options were used.
  74409. var nativeOptions = impostor.getParam("nativeOptions");
  74410. for (var key in nativeOptions) {
  74411. if (nativeOptions.hasOwnProperty(key)) {
  74412. bodyCreationObject[key] = nativeOptions[key];
  74413. }
  74414. }
  74415. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  74416. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  74417. this.world.addEventListener("preStep", impostor.beforeStep);
  74418. this.world.addEventListener("postStep", impostor.afterStep);
  74419. impostor.physicsBody.addShape(shape);
  74420. this.world.add(impostor.physicsBody);
  74421. //try to keep the body moving in the right direction by taking old properties.
  74422. //Should be tested!
  74423. if (oldBody) {
  74424. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  74425. impostor.physicsBody[param].copy(oldBody[param]);
  74426. });
  74427. }
  74428. this._processChildMeshes(impostor);
  74429. }
  74430. //now update the body's transformation
  74431. this._updatePhysicsBodyTransformation(impostor);
  74432. };
  74433. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  74434. var _this = this;
  74435. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  74436. var currentRotation = mainImpostor.object.rotationQuaternion;
  74437. if (meshChildren.length) {
  74438. var processMesh = function (localPosition, mesh) {
  74439. if (!currentRotation || !mesh.rotationQuaternion) {
  74440. return;
  74441. }
  74442. var childImpostor = mesh.getPhysicsImpostor();
  74443. if (childImpostor) {
  74444. var parent = childImpostor.parent;
  74445. if (parent !== mainImpostor) {
  74446. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  74447. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  74448. if (childImpostor.physicsBody) {
  74449. _this.removePhysicsBody(childImpostor);
  74450. childImpostor.physicsBody = null;
  74451. }
  74452. childImpostor.parent = mainImpostor;
  74453. childImpostor.resetUpdateFlags();
  74454. 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));
  74455. //Add the mass of the children.
  74456. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  74457. }
  74458. }
  74459. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  74460. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  74461. };
  74462. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  74463. }
  74464. };
  74465. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  74466. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  74467. this.world.removeEventListener("preStep", impostor.beforeStep);
  74468. this.world.removeEventListener("postStep", impostor.afterStep);
  74469. this.world.remove(impostor.physicsBody);
  74470. };
  74471. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  74472. var mainBody = impostorJoint.mainImpostor.physicsBody;
  74473. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  74474. if (!mainBody || !connectedBody) {
  74475. return;
  74476. }
  74477. var constraint;
  74478. var jointData = impostorJoint.joint.jointData;
  74479. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  74480. var constraintData = {
  74481. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  74482. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  74483. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  74484. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  74485. maxForce: jointData.nativeParams.maxForce,
  74486. collideConnected: !!jointData.collision
  74487. };
  74488. switch (impostorJoint.joint.type) {
  74489. case BABYLON.PhysicsJoint.HingeJoint:
  74490. case BABYLON.PhysicsJoint.Hinge2Joint:
  74491. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  74492. break;
  74493. case BABYLON.PhysicsJoint.DistanceJoint:
  74494. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  74495. break;
  74496. case BABYLON.PhysicsJoint.SpringJoint:
  74497. var springData = jointData;
  74498. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  74499. restLength: springData.length,
  74500. stiffness: springData.stiffness,
  74501. damping: springData.damping,
  74502. localAnchorA: constraintData.pivotA,
  74503. localAnchorB: constraintData.pivotB
  74504. });
  74505. break;
  74506. case BABYLON.PhysicsJoint.LockJoint:
  74507. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  74508. break;
  74509. case BABYLON.PhysicsJoint.PointToPointJoint:
  74510. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  74511. default:
  74512. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  74513. break;
  74514. }
  74515. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  74516. constraint.collideConnected = !!jointData.collision;
  74517. impostorJoint.joint.physicsJoint = constraint;
  74518. //don't add spring as constraint, as it is not one.
  74519. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  74520. this.world.addConstraint(constraint);
  74521. }
  74522. else {
  74523. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  74524. constraint.applyForce();
  74525. });
  74526. }
  74527. };
  74528. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  74529. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  74530. };
  74531. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  74532. var index;
  74533. var mat;
  74534. for (index = 0; index < this._physicsMaterials.length; index++) {
  74535. mat = this._physicsMaterials[index];
  74536. if (mat.friction === friction && mat.restitution === restitution) {
  74537. return mat;
  74538. }
  74539. }
  74540. var currentMat = new this.BJSCANNON.Material(name);
  74541. currentMat.friction = friction;
  74542. currentMat.restitution = restitution;
  74543. this._physicsMaterials.push(currentMat);
  74544. return currentMat;
  74545. };
  74546. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  74547. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  74548. };
  74549. CannonJSPlugin.prototype._createShape = function (impostor) {
  74550. var object = impostor.object;
  74551. var returnValue;
  74552. var extendSize = impostor.getObjectExtendSize();
  74553. switch (impostor.type) {
  74554. case BABYLON.PhysicsImpostor.SphereImpostor:
  74555. var radiusX = extendSize.x;
  74556. var radiusY = extendSize.y;
  74557. var radiusZ = extendSize.z;
  74558. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  74559. break;
  74560. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  74561. case BABYLON.PhysicsImpostor.CylinderImpostor:
  74562. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  74563. break;
  74564. case BABYLON.PhysicsImpostor.BoxImpostor:
  74565. var box = extendSize.scale(0.5);
  74566. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  74567. break;
  74568. case BABYLON.PhysicsImpostor.PlaneImpostor:
  74569. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  74570. returnValue = new this.BJSCANNON.Plane();
  74571. break;
  74572. case BABYLON.PhysicsImpostor.MeshImpostor:
  74573. // should transform the vertex data to world coordinates!!
  74574. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  74575. var rawFaces = object.getIndices ? object.getIndices() : [];
  74576. if (!rawVerts)
  74577. return;
  74578. // get only scale! so the object could transform correctly.
  74579. var oldPosition = object.position.clone();
  74580. var oldRotation = object.rotation && object.rotation.clone();
  74581. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  74582. object.position.copyFromFloats(0, 0, 0);
  74583. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  74584. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  74585. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  74586. var transform = object.computeWorldMatrix(true);
  74587. // convert rawVerts to object space
  74588. var temp = new Array();
  74589. var index;
  74590. for (index = 0; index < rawVerts.length; index += 3) {
  74591. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  74592. }
  74593. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  74594. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  74595. //now set back the transformation!
  74596. object.position.copyFrom(oldPosition);
  74597. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  74598. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  74599. break;
  74600. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  74601. var oldPosition2 = object.position.clone();
  74602. var oldRotation2 = object.rotation && object.rotation.clone();
  74603. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  74604. object.position.copyFromFloats(0, 0, 0);
  74605. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  74606. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  74607. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  74608. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  74609. returnValue = this._createHeightmap(object);
  74610. object.position.copyFrom(oldPosition2);
  74611. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  74612. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  74613. object.computeWorldMatrix(true);
  74614. break;
  74615. case BABYLON.PhysicsImpostor.ParticleImpostor:
  74616. returnValue = new this.BJSCANNON.Particle();
  74617. break;
  74618. }
  74619. return returnValue;
  74620. };
  74621. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  74622. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  74623. var transform = object.computeWorldMatrix(true);
  74624. // convert rawVerts to object space
  74625. var temp = new Array();
  74626. var index;
  74627. for (index = 0; index < pos.length; index += 3) {
  74628. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  74629. }
  74630. pos = temp;
  74631. var matrix = new Array();
  74632. //For now pointDepth will not be used and will be automatically calculated.
  74633. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  74634. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  74635. var boundingInfo = object.getBoundingInfo();
  74636. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  74637. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  74638. var elementSize = dim * 2 / arraySize;
  74639. for (var i = 0; i < pos.length; i = i + 3) {
  74640. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  74641. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  74642. var y = -pos[i + 2] + minY;
  74643. if (!matrix[x]) {
  74644. matrix[x] = [];
  74645. }
  74646. if (!matrix[x][z]) {
  74647. matrix[x][z] = y;
  74648. }
  74649. matrix[x][z] = Math.max(y, matrix[x][z]);
  74650. }
  74651. for (var x = 0; x <= arraySize; ++x) {
  74652. if (!matrix[x]) {
  74653. var loc = 1;
  74654. while (!matrix[(x + loc) % arraySize]) {
  74655. loc++;
  74656. }
  74657. matrix[x] = matrix[(x + loc) % arraySize].slice();
  74658. //console.log("missing x", x);
  74659. }
  74660. for (var z = 0; z <= arraySize; ++z) {
  74661. if (!matrix[x][z]) {
  74662. var loc = 1;
  74663. var newValue;
  74664. while (newValue === undefined) {
  74665. newValue = matrix[x][(z + loc++) % arraySize];
  74666. }
  74667. matrix[x][z] = newValue;
  74668. }
  74669. }
  74670. }
  74671. var shape = new this.BJSCANNON.Heightfield(matrix, {
  74672. elementSize: elementSize
  74673. });
  74674. //For future reference, needed for body transformation
  74675. shape.minY = minY;
  74676. return shape;
  74677. };
  74678. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  74679. var object = impostor.object;
  74680. //make sure it is updated...
  74681. object.computeWorldMatrix && object.computeWorldMatrix(true);
  74682. // The delta between the mesh position and the mesh bounding box center
  74683. var bInfo = object.getBoundingInfo();
  74684. if (!bInfo)
  74685. return;
  74686. var center = impostor.getObjectCenter();
  74687. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  74688. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  74689. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  74690. this._tmpPosition.copyFrom(center);
  74691. var quaternion = object.rotationQuaternion;
  74692. if (!quaternion) {
  74693. return;
  74694. }
  74695. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  74696. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  74697. //-90 DEG in X, precalculated
  74698. quaternion = quaternion.multiply(this._minus90X);
  74699. //Invert! (Precalculated, 90 deg in X)
  74700. //No need to clone. this will never change.
  74701. impostor.setDeltaRotation(this._plus90X);
  74702. }
  74703. //If it is a heightfield, if should be centered.
  74704. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  74705. var mesh = object;
  74706. var boundingInfo = mesh.getBoundingInfo();
  74707. //calculate the correct body position:
  74708. var rotationQuaternion = mesh.rotationQuaternion;
  74709. mesh.rotationQuaternion = this._tmpUnityRotation;
  74710. mesh.computeWorldMatrix(true);
  74711. //get original center with no rotation
  74712. var c = center.clone();
  74713. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  74714. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  74715. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  74716. mesh.setPreTransformMatrix(p);
  74717. mesh.computeWorldMatrix(true);
  74718. //calculate the translation
  74719. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  74720. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  74721. //add it inverted to the delta
  74722. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  74723. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  74724. //rotation is back
  74725. mesh.rotationQuaternion = rotationQuaternion;
  74726. mesh.setPreTransformMatrix(oldPivot);
  74727. mesh.computeWorldMatrix(true);
  74728. }
  74729. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  74730. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  74731. //this._tmpPosition.copyFrom(object.position);
  74732. }
  74733. impostor.setDeltaPosition(this._tmpDeltaPosition);
  74734. //Now update the impostor object
  74735. impostor.physicsBody.position.copy(this._tmpPosition);
  74736. impostor.physicsBody.quaternion.copy(quaternion);
  74737. };
  74738. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  74739. impostor.object.position.copyFrom(impostor.physicsBody.position);
  74740. if (impostor.object.rotationQuaternion) {
  74741. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  74742. }
  74743. };
  74744. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  74745. impostor.physicsBody.position.copy(newPosition);
  74746. impostor.physicsBody.quaternion.copy(newRotation);
  74747. };
  74748. CannonJSPlugin.prototype.isSupported = function () {
  74749. return this.BJSCANNON !== undefined;
  74750. };
  74751. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  74752. impostor.physicsBody.velocity.copy(velocity);
  74753. };
  74754. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  74755. impostor.physicsBody.angularVelocity.copy(velocity);
  74756. };
  74757. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  74758. var v = impostor.physicsBody.velocity;
  74759. if (!v) {
  74760. return null;
  74761. }
  74762. return new BABYLON.Vector3(v.x, v.y, v.z);
  74763. };
  74764. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  74765. var v = impostor.physicsBody.angularVelocity;
  74766. if (!v) {
  74767. return null;
  74768. }
  74769. return new BABYLON.Vector3(v.x, v.y, v.z);
  74770. };
  74771. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  74772. impostor.physicsBody.mass = mass;
  74773. impostor.physicsBody.updateMassProperties();
  74774. };
  74775. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  74776. return impostor.physicsBody.mass;
  74777. };
  74778. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  74779. return impostor.physicsBody.material.friction;
  74780. };
  74781. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  74782. impostor.physicsBody.material.friction = friction;
  74783. };
  74784. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  74785. return impostor.physicsBody.material.restitution;
  74786. };
  74787. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  74788. impostor.physicsBody.material.restitution = restitution;
  74789. };
  74790. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  74791. impostor.physicsBody.sleep();
  74792. };
  74793. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  74794. impostor.physicsBody.wakeUp();
  74795. };
  74796. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  74797. joint.physicsJoint.distance = maxDistance;
  74798. };
  74799. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  74800. // if (!motorIndex) {
  74801. // joint.physicsJoint.enableMotor();
  74802. // }
  74803. // }
  74804. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  74805. // if (!motorIndex) {
  74806. // joint.physicsJoint.disableMotor();
  74807. // }
  74808. // }
  74809. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  74810. if (!motorIndex) {
  74811. joint.physicsJoint.enableMotor();
  74812. joint.physicsJoint.setMotorSpeed(speed);
  74813. if (maxForce) {
  74814. this.setLimit(joint, maxForce);
  74815. }
  74816. }
  74817. };
  74818. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  74819. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  74820. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  74821. };
  74822. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  74823. var body = impostor.physicsBody;
  74824. mesh.position.x = body.position.x;
  74825. mesh.position.y = body.position.y;
  74826. mesh.position.z = body.position.z;
  74827. if (mesh.rotationQuaternion) {
  74828. mesh.rotationQuaternion.x = body.quaternion.x;
  74829. mesh.rotationQuaternion.y = body.quaternion.y;
  74830. mesh.rotationQuaternion.z = body.quaternion.z;
  74831. mesh.rotationQuaternion.w = body.quaternion.w;
  74832. }
  74833. };
  74834. CannonJSPlugin.prototype.getRadius = function (impostor) {
  74835. var shape = impostor.physicsBody.shapes[0];
  74836. return shape.boundingSphereRadius;
  74837. };
  74838. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  74839. var shape = impostor.physicsBody.shapes[0];
  74840. result.x = shape.halfExtents.x * 2;
  74841. result.y = shape.halfExtents.y * 2;
  74842. result.z = shape.halfExtents.z * 2;
  74843. };
  74844. CannonJSPlugin.prototype.dispose = function () {
  74845. };
  74846. CannonJSPlugin.prototype._extendNamespace = function () {
  74847. //this will force cannon to execute at least one step when using interpolation
  74848. var step_tmp1 = new this.BJSCANNON.Vec3();
  74849. var Engine = this.BJSCANNON;
  74850. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  74851. maxSubSteps = maxSubSteps || 10;
  74852. timeSinceLastCalled = timeSinceLastCalled || 0;
  74853. if (timeSinceLastCalled === 0) {
  74854. this.internalStep(dt);
  74855. this.time += dt;
  74856. }
  74857. else {
  74858. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  74859. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  74860. var t0 = performance.now();
  74861. for (var i = 0; i !== internalSteps; i++) {
  74862. this.internalStep(dt);
  74863. if (performance.now() - t0 > dt * 1000) {
  74864. break;
  74865. }
  74866. }
  74867. this.time += timeSinceLastCalled;
  74868. var h = this.time % dt;
  74869. var h_div_dt = h / dt;
  74870. var interpvelo = step_tmp1;
  74871. var bodies = this.bodies;
  74872. for (var j = 0; j !== bodies.length; j++) {
  74873. var b = bodies[j];
  74874. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  74875. b.position.vsub(b.previousPosition, interpvelo);
  74876. interpvelo.scale(h_div_dt, interpvelo);
  74877. b.position.vadd(interpvelo, b.interpolatedPosition);
  74878. }
  74879. else {
  74880. b.interpolatedPosition.copy(b.position);
  74881. b.interpolatedQuaternion.copy(b.quaternion);
  74882. }
  74883. }
  74884. }
  74885. };
  74886. };
  74887. return CannonJSPlugin;
  74888. }());
  74889. BABYLON.CannonJSPlugin = CannonJSPlugin;
  74890. })(BABYLON || (BABYLON = {}));
  74891. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  74892. var BABYLON;
  74893. (function (BABYLON) {
  74894. var OimoJSPlugin = /** @class */ (function () {
  74895. function OimoJSPlugin(iterations) {
  74896. this.name = "OimoJSPlugin";
  74897. this._tmpImpostorsArray = [];
  74898. this._tmpPositionVector = BABYLON.Vector3.Zero();
  74899. this.BJSOIMO = typeof OIMO !== 'undefined' ? OIMO : (typeof require !== 'undefined' ? require('./Oimo') : undefined);
  74900. this.world = new this.BJSOIMO.World(1 / 60, 2, iterations, true);
  74901. this.world.worldscale(1);
  74902. this.world.clear();
  74903. //making sure no stats are calculated
  74904. this.world.isNoStat = true;
  74905. }
  74906. OimoJSPlugin.prototype.setGravity = function (gravity) {
  74907. this.world.gravity.copy(gravity);
  74908. };
  74909. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  74910. this.world.timeStep = timeStep;
  74911. };
  74912. OimoJSPlugin.prototype.getTimeStep = function () {
  74913. return this.world.timeStep;
  74914. };
  74915. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  74916. var _this = this;
  74917. impostors.forEach(function (impostor) {
  74918. impostor.beforeStep();
  74919. });
  74920. this.world.step();
  74921. impostors.forEach(function (impostor) {
  74922. impostor.afterStep();
  74923. //update the ordered impostors array
  74924. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  74925. });
  74926. //check for collisions
  74927. var contact = this.world.contacts;
  74928. while (contact !== null) {
  74929. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  74930. contact = contact.next;
  74931. continue;
  74932. }
  74933. //is this body colliding with any other? get the impostor
  74934. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  74935. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  74936. if (!mainImpostor || !collidingImpostor) {
  74937. contact = contact.next;
  74938. continue;
  74939. }
  74940. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  74941. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  74942. contact = contact.next;
  74943. }
  74944. };
  74945. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  74946. var mass = impostor.physicsBody.massInfo.mass;
  74947. impostor.physicsBody.applyImpulse(contactPoint.scale(this.BJSOIMO.INV_SCALE), force.scale(this.BJSOIMO.INV_SCALE * mass));
  74948. };
  74949. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  74950. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  74951. this.applyImpulse(impostor, force, contactPoint);
  74952. };
  74953. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  74954. var _this = this;
  74955. //parent-child relationship. Does this impostor has a parent impostor?
  74956. if (impostor.parent) {
  74957. if (impostor.physicsBody) {
  74958. this.removePhysicsBody(impostor);
  74959. //TODO is that needed?
  74960. impostor.forceUpdate();
  74961. }
  74962. return;
  74963. }
  74964. if (impostor.isBodyInitRequired()) {
  74965. var bodyConfig = {
  74966. name: impostor.uniqueId,
  74967. //Oimo must have mass, also for static objects.
  74968. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  74969. size: [],
  74970. type: [],
  74971. pos: [],
  74972. rot: [],
  74973. move: impostor.getParam("mass") !== 0,
  74974. //Supporting older versions of Oimo
  74975. world: this.world
  74976. };
  74977. var impostors = [impostor];
  74978. var addToArray = function (parent) {
  74979. if (!parent.getChildMeshes)
  74980. return;
  74981. parent.getChildMeshes().forEach(function (m) {
  74982. if (m.physicsImpostor) {
  74983. impostors.push(m.physicsImpostor);
  74984. //m.physicsImpostor._init();
  74985. }
  74986. });
  74987. };
  74988. addToArray(impostor.object);
  74989. var checkWithEpsilon_1 = function (value) {
  74990. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  74991. };
  74992. impostors.forEach(function (i) {
  74993. if (!impostor.object.rotationQuaternion) {
  74994. return;
  74995. }
  74996. //get the correct bounding box
  74997. var oldQuaternion = i.object.rotationQuaternion;
  74998. var rot = new _this.BJSOIMO.Euler().setFromQuaternion({
  74999. x: impostor.object.rotationQuaternion.x,
  75000. y: impostor.object.rotationQuaternion.y,
  75001. z: impostor.object.rotationQuaternion.z,
  75002. s: impostor.object.rotationQuaternion.w
  75003. });
  75004. var extendSize = i.getObjectExtendSize();
  75005. if (i === impostor) {
  75006. var center = impostor.getObjectCenter();
  75007. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  75008. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  75009. //Can also use Array.prototype.push.apply
  75010. bodyConfig.pos.push(center.x);
  75011. bodyConfig.pos.push(center.y);
  75012. bodyConfig.pos.push(center.z);
  75013. //tmp solution
  75014. bodyConfig.rot.push(rot.x / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  75015. bodyConfig.rot.push(rot.y / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  75016. bodyConfig.rot.push(rot.z / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  75017. }
  75018. else {
  75019. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  75020. bodyConfig.pos.push(localPosition.x);
  75021. bodyConfig.pos.push(localPosition.y);
  75022. bodyConfig.pos.push(localPosition.z);
  75023. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  75024. bodyConfig.rot.push(0);
  75025. bodyConfig.rot.push(0);
  75026. bodyConfig.rot.push(0);
  75027. }
  75028. // register mesh
  75029. switch (i.type) {
  75030. case BABYLON.PhysicsImpostor.ParticleImpostor:
  75031. BABYLON.Tools.Warn("No Particle support in this.BJSOIMO.js. using SphereImpostor instead");
  75032. case BABYLON.PhysicsImpostor.SphereImpostor:
  75033. var radiusX = extendSize.x;
  75034. var radiusY = extendSize.y;
  75035. var radiusZ = extendSize.z;
  75036. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  75037. bodyConfig.type.push('sphere');
  75038. //due to the way oimo works with compounds, add 3 times
  75039. bodyConfig.size.push(size);
  75040. bodyConfig.size.push(size);
  75041. bodyConfig.size.push(size);
  75042. break;
  75043. case BABYLON.PhysicsImpostor.CylinderImpostor:
  75044. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  75045. var sizeY = checkWithEpsilon_1(extendSize.y);
  75046. bodyConfig.type.push('cylinder');
  75047. bodyConfig.size.push(sizeX);
  75048. bodyConfig.size.push(sizeY);
  75049. //due to the way oimo works with compounds, add one more value.
  75050. bodyConfig.size.push(sizeY);
  75051. break;
  75052. case BABYLON.PhysicsImpostor.PlaneImpostor:
  75053. case BABYLON.PhysicsImpostor.BoxImpostor:
  75054. default:
  75055. var sizeX = checkWithEpsilon_1(extendSize.x);
  75056. var sizeY = checkWithEpsilon_1(extendSize.y);
  75057. var sizeZ = checkWithEpsilon_1(extendSize.z);
  75058. bodyConfig.type.push('box');
  75059. bodyConfig.size.push(sizeX);
  75060. bodyConfig.size.push(sizeY);
  75061. bodyConfig.size.push(sizeZ);
  75062. break;
  75063. }
  75064. //actually not needed, but hey...
  75065. i.object.rotationQuaternion = oldQuaternion;
  75066. });
  75067. impostor.physicsBody = new this.BJSOIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  75068. }
  75069. else {
  75070. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  75071. }
  75072. impostor.setDeltaPosition(this._tmpPositionVector);
  75073. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  75074. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  75075. };
  75076. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  75077. //impostor.physicsBody.dispose();
  75078. //Same as : (older oimo versions)
  75079. this.world.removeRigidBody(impostor.physicsBody);
  75080. };
  75081. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  75082. var mainBody = impostorJoint.mainImpostor.physicsBody;
  75083. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  75084. if (!mainBody || !connectedBody) {
  75085. return;
  75086. }
  75087. var jointData = impostorJoint.joint.jointData;
  75088. var options = jointData.nativeParams || {};
  75089. var type;
  75090. var nativeJointData = {
  75091. body1: mainBody,
  75092. body2: connectedBody,
  75093. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  75094. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  75095. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  75096. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  75097. min: options.min,
  75098. max: options.max,
  75099. collision: options.collision || jointData.collision,
  75100. spring: options.spring,
  75101. //supporting older version of Oimo
  75102. world: this.world
  75103. };
  75104. switch (impostorJoint.joint.type) {
  75105. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  75106. type = "jointBall";
  75107. break;
  75108. case BABYLON.PhysicsJoint.SpringJoint:
  75109. BABYLON.Tools.Warn("this.BJSOIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  75110. var springData = jointData;
  75111. nativeJointData.min = springData.length || nativeJointData.min;
  75112. //Max should also be set, just make sure it is at least min
  75113. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  75114. case BABYLON.PhysicsJoint.DistanceJoint:
  75115. type = "jointDistance";
  75116. nativeJointData.max = jointData.maxDistance;
  75117. break;
  75118. case BABYLON.PhysicsJoint.PrismaticJoint:
  75119. type = "jointPrisme";
  75120. break;
  75121. case BABYLON.PhysicsJoint.SliderJoint:
  75122. type = "jointSlide";
  75123. break;
  75124. case BABYLON.PhysicsJoint.WheelJoint:
  75125. type = "jointWheel";
  75126. break;
  75127. case BABYLON.PhysicsJoint.HingeJoint:
  75128. default:
  75129. type = "jointHinge";
  75130. break;
  75131. }
  75132. nativeJointData.type = type;
  75133. impostorJoint.joint.physicsJoint = new this.BJSOIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  75134. };
  75135. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  75136. //Bug in Oimo prevents us from disposing a joint in the playground
  75137. //joint.joint.physicsJoint.dispose();
  75138. //So we will bruteforce it!
  75139. try {
  75140. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  75141. }
  75142. catch (e) {
  75143. BABYLON.Tools.Warn(e);
  75144. }
  75145. };
  75146. OimoJSPlugin.prototype.isSupported = function () {
  75147. return this.BJSOIMO !== undefined;
  75148. };
  75149. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  75150. if (!impostor.physicsBody.sleeping) {
  75151. //TODO check that
  75152. if (impostor.physicsBody.shapes.next) {
  75153. var parentShape = this._getLastShape(impostor.physicsBody);
  75154. impostor.object.position.x = parentShape.position.x * this.BJSOIMO.WORLD_SCALE;
  75155. impostor.object.position.y = parentShape.position.y * this.BJSOIMO.WORLD_SCALE;
  75156. impostor.object.position.z = parentShape.position.z * this.BJSOIMO.WORLD_SCALE;
  75157. }
  75158. else {
  75159. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  75160. }
  75161. if (impostor.object.rotationQuaternion) {
  75162. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  75163. impostor.object.rotationQuaternion.normalize();
  75164. }
  75165. }
  75166. };
  75167. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  75168. var body = impostor.physicsBody;
  75169. body.position.init(newPosition.x * this.BJSOIMO.INV_SCALE, newPosition.y * this.BJSOIMO.INV_SCALE, newPosition.z * this.BJSOIMO.INV_SCALE);
  75170. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  75171. body.syncShapes();
  75172. body.awake();
  75173. };
  75174. OimoJSPlugin.prototype._getLastShape = function (body) {
  75175. var lastShape = body.shapes;
  75176. while (lastShape.next) {
  75177. lastShape = lastShape.next;
  75178. }
  75179. return lastShape;
  75180. };
  75181. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  75182. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  75183. };
  75184. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  75185. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  75186. };
  75187. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  75188. var v = impostor.physicsBody.linearVelocity;
  75189. if (!v) {
  75190. return null;
  75191. }
  75192. return new BABYLON.Vector3(v.x, v.y, v.z);
  75193. };
  75194. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  75195. var v = impostor.physicsBody.angularVelocity;
  75196. if (!v) {
  75197. return null;
  75198. }
  75199. return new BABYLON.Vector3(v.x, v.y, v.z);
  75200. };
  75201. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  75202. var staticBody = mass === 0;
  75203. //this will actually set the body's density and not its mass.
  75204. //But this is how oimo treats the mass variable.
  75205. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  75206. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  75207. };
  75208. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  75209. return impostor.physicsBody.shapes.density;
  75210. };
  75211. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  75212. return impostor.physicsBody.shapes.friction;
  75213. };
  75214. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  75215. impostor.physicsBody.shapes.friction = friction;
  75216. };
  75217. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  75218. return impostor.physicsBody.shapes.restitution;
  75219. };
  75220. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  75221. impostor.physicsBody.shapes.restitution = restitution;
  75222. };
  75223. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  75224. impostor.physicsBody.sleep();
  75225. };
  75226. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  75227. impostor.physicsBody.awake();
  75228. };
  75229. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  75230. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  75231. if (minDistance !== void 0) {
  75232. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  75233. }
  75234. };
  75235. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  75236. //TODO separate rotational and transational motors.
  75237. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  75238. if (motor) {
  75239. motor.setMotor(speed, maxForce);
  75240. }
  75241. };
  75242. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  75243. //TODO separate rotational and transational motors.
  75244. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  75245. if (motor) {
  75246. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  75247. }
  75248. };
  75249. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  75250. var body = impostor.physicsBody;
  75251. mesh.position.x = body.position.x;
  75252. mesh.position.y = body.position.y;
  75253. mesh.position.z = body.position.z;
  75254. if (mesh.rotationQuaternion) {
  75255. mesh.rotationQuaternion.x = body.orientation.x;
  75256. mesh.rotationQuaternion.y = body.orientation.y;
  75257. mesh.rotationQuaternion.z = body.orientation.z;
  75258. mesh.rotationQuaternion.w = body.orientation.s;
  75259. }
  75260. };
  75261. OimoJSPlugin.prototype.getRadius = function (impostor) {
  75262. return impostor.physicsBody.shapes.radius;
  75263. };
  75264. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  75265. var shape = impostor.physicsBody.shapes;
  75266. result.x = shape.halfWidth * 2;
  75267. result.y = shape.halfHeight * 2;
  75268. result.z = shape.halfDepth * 2;
  75269. };
  75270. OimoJSPlugin.prototype.dispose = function () {
  75271. this.world.clear();
  75272. };
  75273. return OimoJSPlugin;
  75274. }());
  75275. BABYLON.OimoJSPlugin = OimoJSPlugin;
  75276. })(BABYLON || (BABYLON = {}));
  75277. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  75278. var BABYLON;
  75279. (function (BABYLON) {
  75280. /*
  75281. * Based on jsTGALoader - Javascript loader for TGA file
  75282. * By Vincent Thibault
  75283. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  75284. */
  75285. var TGATools = /** @class */ (function () {
  75286. function TGATools() {
  75287. }
  75288. TGATools.GetTGAHeader = function (data) {
  75289. var offset = 0;
  75290. var header = {
  75291. id_length: data[offset++],
  75292. colormap_type: data[offset++],
  75293. image_type: data[offset++],
  75294. colormap_index: data[offset++] | data[offset++] << 8,
  75295. colormap_length: data[offset++] | data[offset++] << 8,
  75296. colormap_size: data[offset++],
  75297. origin: [
  75298. data[offset++] | data[offset++] << 8,
  75299. data[offset++] | data[offset++] << 8
  75300. ],
  75301. width: data[offset++] | data[offset++] << 8,
  75302. height: data[offset++] | data[offset++] << 8,
  75303. pixel_size: data[offset++],
  75304. flags: data[offset++]
  75305. };
  75306. return header;
  75307. };
  75308. TGATools.UploadContent = function (gl, data) {
  75309. // Not enough data to contain header ?
  75310. if (data.length < 19) {
  75311. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  75312. return;
  75313. }
  75314. // Read Header
  75315. var offset = 18;
  75316. var header = TGATools.GetTGAHeader(data);
  75317. // Assume it's a valid Targa file.
  75318. if (header.id_length + offset > data.length) {
  75319. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  75320. return;
  75321. }
  75322. // Skip not needed data
  75323. offset += header.id_length;
  75324. var use_rle = false;
  75325. var use_pal = false;
  75326. var use_grey = false;
  75327. // Get some informations.
  75328. switch (header.image_type) {
  75329. case TGATools._TYPE_RLE_INDEXED:
  75330. use_rle = true;
  75331. case TGATools._TYPE_INDEXED:
  75332. use_pal = true;
  75333. break;
  75334. case TGATools._TYPE_RLE_RGB:
  75335. use_rle = true;
  75336. case TGATools._TYPE_RGB:
  75337. // use_rgb = true;
  75338. break;
  75339. case TGATools._TYPE_RLE_GREY:
  75340. use_rle = true;
  75341. case TGATools._TYPE_GREY:
  75342. use_grey = true;
  75343. break;
  75344. }
  75345. var pixel_data;
  75346. // var numAlphaBits = header.flags & 0xf;
  75347. var pixel_size = header.pixel_size >> 3;
  75348. var pixel_total = header.width * header.height * pixel_size;
  75349. // Read palettes
  75350. var palettes;
  75351. if (use_pal) {
  75352. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  75353. }
  75354. // Read LRE
  75355. if (use_rle) {
  75356. pixel_data = new Uint8Array(pixel_total);
  75357. var c, count, i;
  75358. var localOffset = 0;
  75359. var pixels = new Uint8Array(pixel_size);
  75360. while (offset < pixel_total && localOffset < pixel_total) {
  75361. c = data[offset++];
  75362. count = (c & 0x7f) + 1;
  75363. // RLE pixels
  75364. if (c & 0x80) {
  75365. // Bind pixel tmp array
  75366. for (i = 0; i < pixel_size; ++i) {
  75367. pixels[i] = data[offset++];
  75368. }
  75369. // Copy pixel array
  75370. for (i = 0; i < count; ++i) {
  75371. pixel_data.set(pixels, localOffset + i * pixel_size);
  75372. }
  75373. localOffset += pixel_size * count;
  75374. }
  75375. else {
  75376. count *= pixel_size;
  75377. for (i = 0; i < count; ++i) {
  75378. pixel_data[localOffset + i] = data[offset++];
  75379. }
  75380. localOffset += count;
  75381. }
  75382. }
  75383. }
  75384. else {
  75385. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  75386. }
  75387. // Load to texture
  75388. var x_start, y_start, x_step, y_step, y_end, x_end;
  75389. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  75390. default:
  75391. case TGATools._ORIGIN_UL:
  75392. x_start = 0;
  75393. x_step = 1;
  75394. x_end = header.width;
  75395. y_start = 0;
  75396. y_step = 1;
  75397. y_end = header.height;
  75398. break;
  75399. case TGATools._ORIGIN_BL:
  75400. x_start = 0;
  75401. x_step = 1;
  75402. x_end = header.width;
  75403. y_start = header.height - 1;
  75404. y_step = -1;
  75405. y_end = -1;
  75406. break;
  75407. case TGATools._ORIGIN_UR:
  75408. x_start = header.width - 1;
  75409. x_step = -1;
  75410. x_end = -1;
  75411. y_start = 0;
  75412. y_step = 1;
  75413. y_end = header.height;
  75414. break;
  75415. case TGATools._ORIGIN_BR:
  75416. x_start = header.width - 1;
  75417. x_step = -1;
  75418. x_end = -1;
  75419. y_start = header.height - 1;
  75420. y_step = -1;
  75421. y_end = -1;
  75422. break;
  75423. }
  75424. // Load the specify method
  75425. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  75426. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  75427. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  75428. };
  75429. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  75430. var image = pixel_data, colormap = palettes;
  75431. var width = header.width, height = header.height;
  75432. var color, i = 0, x, y;
  75433. var imageData = new Uint8Array(width * height * 4);
  75434. for (y = y_start; y !== y_end; y += y_step) {
  75435. for (x = x_start; x !== x_end; x += x_step, i++) {
  75436. color = image[i];
  75437. imageData[(x + width * y) * 4 + 3] = 255;
  75438. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  75439. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  75440. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  75441. }
  75442. }
  75443. return imageData;
  75444. };
  75445. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  75446. var image = pixel_data;
  75447. var width = header.width, height = header.height;
  75448. var color, i = 0, x, y;
  75449. var imageData = new Uint8Array(width * height * 4);
  75450. for (y = y_start; y !== y_end; y += y_step) {
  75451. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  75452. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  75453. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  75454. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  75455. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  75456. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  75457. }
  75458. }
  75459. return imageData;
  75460. };
  75461. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  75462. var image = pixel_data;
  75463. var width = header.width, height = header.height;
  75464. var i = 0, x, y;
  75465. var imageData = new Uint8Array(width * height * 4);
  75466. for (y = y_start; y !== y_end; y += y_step) {
  75467. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  75468. imageData[(x + width * y) * 4 + 3] = 255;
  75469. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  75470. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  75471. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  75472. }
  75473. }
  75474. return imageData;
  75475. };
  75476. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  75477. var image = pixel_data;
  75478. var width = header.width, height = header.height;
  75479. var i = 0, x, y;
  75480. var imageData = new Uint8Array(width * height * 4);
  75481. for (y = y_start; y !== y_end; y += y_step) {
  75482. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  75483. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  75484. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  75485. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  75486. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  75487. }
  75488. }
  75489. return imageData;
  75490. };
  75491. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  75492. var image = pixel_data;
  75493. var width = header.width, height = header.height;
  75494. var color, i = 0, x, y;
  75495. var imageData = new Uint8Array(width * height * 4);
  75496. for (y = y_start; y !== y_end; y += y_step) {
  75497. for (x = x_start; x !== x_end; x += x_step, i++) {
  75498. color = image[i];
  75499. imageData[(x + width * y) * 4 + 0] = color;
  75500. imageData[(x + width * y) * 4 + 1] = color;
  75501. imageData[(x + width * y) * 4 + 2] = color;
  75502. imageData[(x + width * y) * 4 + 3] = 255;
  75503. }
  75504. }
  75505. return imageData;
  75506. };
  75507. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  75508. var image = pixel_data;
  75509. var width = header.width, height = header.height;
  75510. var i = 0, x, y;
  75511. var imageData = new Uint8Array(width * height * 4);
  75512. for (y = y_start; y !== y_end; y += y_step) {
  75513. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  75514. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  75515. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  75516. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  75517. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  75518. }
  75519. }
  75520. return imageData;
  75521. };
  75522. //private static _TYPE_NO_DATA = 0;
  75523. TGATools._TYPE_INDEXED = 1;
  75524. TGATools._TYPE_RGB = 2;
  75525. TGATools._TYPE_GREY = 3;
  75526. TGATools._TYPE_RLE_INDEXED = 9;
  75527. TGATools._TYPE_RLE_RGB = 10;
  75528. TGATools._TYPE_RLE_GREY = 11;
  75529. TGATools._ORIGIN_MASK = 0x30;
  75530. TGATools._ORIGIN_SHIFT = 0x04;
  75531. TGATools._ORIGIN_BL = 0x00;
  75532. TGATools._ORIGIN_BR = 0x01;
  75533. TGATools._ORIGIN_UL = 0x02;
  75534. TGATools._ORIGIN_UR = 0x03;
  75535. return TGATools;
  75536. }());
  75537. BABYLON.TGATools = TGATools;
  75538. })(BABYLON || (BABYLON = {}));
  75539. //# sourceMappingURL=babylon.tga.js.map
  75540. var BABYLON;
  75541. (function (BABYLON) {
  75542. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  75543. // All values and structures referenced from:
  75544. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  75545. var DDS_MAGIC = 0x20534444;
  75546. var
  75547. //DDSD_CAPS = 0x1,
  75548. //DDSD_HEIGHT = 0x2,
  75549. //DDSD_WIDTH = 0x4,
  75550. //DDSD_PITCH = 0x8,
  75551. //DDSD_PIXELFORMAT = 0x1000,
  75552. DDSD_MIPMAPCOUNT = 0x20000;
  75553. //DDSD_LINEARSIZE = 0x80000,
  75554. //DDSD_DEPTH = 0x800000;
  75555. // var DDSCAPS_COMPLEX = 0x8,
  75556. // DDSCAPS_MIPMAP = 0x400000,
  75557. // DDSCAPS_TEXTURE = 0x1000;
  75558. var DDSCAPS2_CUBEMAP = 0x200;
  75559. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  75560. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  75561. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  75562. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  75563. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  75564. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  75565. // DDSCAPS2_VOLUME = 0x200000;
  75566. var
  75567. //DDPF_ALPHAPIXELS = 0x1,
  75568. //DDPF_ALPHA = 0x2,
  75569. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  75570. //DDPF_YUV = 0x200,
  75571. DDPF_LUMINANCE = 0x20000;
  75572. function FourCCToInt32(value) {
  75573. return value.charCodeAt(0) +
  75574. (value.charCodeAt(1) << 8) +
  75575. (value.charCodeAt(2) << 16) +
  75576. (value.charCodeAt(3) << 24);
  75577. }
  75578. function Int32ToFourCC(value) {
  75579. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  75580. }
  75581. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  75582. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  75583. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  75584. var FOURCC_DX10 = FourCCToInt32("DX10");
  75585. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  75586. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  75587. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  75588. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  75589. var headerLengthInt = 31; // The header length in 32 bit ints
  75590. // Offsets into the header array
  75591. var off_magic = 0;
  75592. var off_size = 1;
  75593. var off_flags = 2;
  75594. var off_height = 3;
  75595. var off_width = 4;
  75596. var off_mipmapCount = 7;
  75597. var off_pfFlags = 20;
  75598. var off_pfFourCC = 21;
  75599. var off_RGBbpp = 22;
  75600. var off_RMask = 23;
  75601. var off_GMask = 24;
  75602. var off_BMask = 25;
  75603. var off_AMask = 26;
  75604. // var off_caps1 = 27;
  75605. var off_caps2 = 28;
  75606. // var off_caps3 = 29;
  75607. // var off_caps4 = 30;
  75608. var off_dxgiFormat = 32;
  75609. ;
  75610. var DDSTools = /** @class */ (function () {
  75611. function DDSTools() {
  75612. }
  75613. DDSTools.GetDDSInfo = function (arrayBuffer) {
  75614. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  75615. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  75616. var mipmapCount = 1;
  75617. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  75618. mipmapCount = Math.max(1, header[off_mipmapCount]);
  75619. }
  75620. var fourCC = header[off_pfFourCC];
  75621. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  75622. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  75623. switch (fourCC) {
  75624. case FOURCC_D3DFMT_R16G16B16A16F:
  75625. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  75626. break;
  75627. case FOURCC_D3DFMT_R32G32B32A32F:
  75628. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  75629. break;
  75630. case FOURCC_DX10:
  75631. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  75632. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  75633. break;
  75634. }
  75635. }
  75636. return {
  75637. width: header[off_width],
  75638. height: header[off_height],
  75639. mipmapCount: mipmapCount,
  75640. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  75641. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  75642. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  75643. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  75644. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  75645. dxgiFormat: dxgiFormat,
  75646. textureType: textureType
  75647. };
  75648. };
  75649. DDSTools._ToHalfFloat = function (value) {
  75650. if (!DDSTools._FloatView) {
  75651. DDSTools._FloatView = new Float32Array(1);
  75652. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  75653. }
  75654. DDSTools._FloatView[0] = value;
  75655. var x = DDSTools._Int32View[0];
  75656. var bits = (x >> 16) & 0x8000; /* Get the sign */
  75657. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  75658. var e = (x >> 23) & 0xff; /* Using int is faster here */
  75659. /* If zero, or denormal, or exponent underflows too much for a denormal
  75660. * half, return signed zero. */
  75661. if (e < 103) {
  75662. return bits;
  75663. }
  75664. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  75665. if (e > 142) {
  75666. bits |= 0x7c00;
  75667. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  75668. * not Inf, so make sure we set one mantissa bit too. */
  75669. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  75670. return bits;
  75671. }
  75672. /* If exponent underflows but not too much, return a denormal */
  75673. if (e < 113) {
  75674. m |= 0x0800;
  75675. /* Extra rounding may overflow and set mantissa to 0 and exponent
  75676. * to 1, which is OK. */
  75677. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  75678. return bits;
  75679. }
  75680. bits |= ((e - 112) << 10) | (m >> 1);
  75681. bits += m & 1;
  75682. return bits;
  75683. };
  75684. DDSTools._FromHalfFloat = function (value) {
  75685. var s = (value & 0x8000) >> 15;
  75686. var e = (value & 0x7C00) >> 10;
  75687. var f = value & 0x03FF;
  75688. if (e === 0) {
  75689. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  75690. }
  75691. else if (e == 0x1F) {
  75692. return f ? NaN : ((s ? -1 : 1) * Infinity);
  75693. }
  75694. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  75695. };
  75696. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  75697. var destArray = new Float32Array(dataLength);
  75698. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  75699. var index = 0;
  75700. for (var y = 0; y < height; y++) {
  75701. for (var x = 0; x < width; x++) {
  75702. var srcPos = (x + y * width) * 4;
  75703. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  75704. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  75705. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  75706. if (DDSTools.StoreLODInAlphaChannel) {
  75707. destArray[index + 3] = lod;
  75708. }
  75709. else {
  75710. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  75711. }
  75712. index += 4;
  75713. }
  75714. }
  75715. return destArray;
  75716. };
  75717. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  75718. if (DDSTools.StoreLODInAlphaChannel) {
  75719. var destArray = new Uint16Array(dataLength);
  75720. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  75721. var index = 0;
  75722. for (var y = 0; y < height; y++) {
  75723. for (var x = 0; x < width; x++) {
  75724. var srcPos = (x + y * width) * 4;
  75725. destArray[index] = srcData[srcPos];
  75726. destArray[index + 1] = srcData[srcPos + 1];
  75727. destArray[index + 2] = srcData[srcPos + 2];
  75728. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  75729. index += 4;
  75730. }
  75731. }
  75732. return destArray;
  75733. }
  75734. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  75735. };
  75736. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  75737. if (DDSTools.StoreLODInAlphaChannel) {
  75738. var destArray = new Float32Array(dataLength);
  75739. var srcData = new Float32Array(arrayBuffer, dataOffset);
  75740. var index = 0;
  75741. for (var y = 0; y < height; y++) {
  75742. for (var x = 0; x < width; x++) {
  75743. var srcPos = (x + y * width) * 4;
  75744. destArray[index] = srcData[srcPos];
  75745. destArray[index + 1] = srcData[srcPos + 1];
  75746. destArray[index + 2] = srcData[srcPos + 2];
  75747. destArray[index + 3] = lod;
  75748. index += 4;
  75749. }
  75750. }
  75751. return destArray;
  75752. }
  75753. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  75754. };
  75755. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  75756. var destArray = new Uint8Array(dataLength);
  75757. var srcData = new Float32Array(arrayBuffer, dataOffset);
  75758. var index = 0;
  75759. for (var y = 0; y < height; y++) {
  75760. for (var x = 0; x < width; x++) {
  75761. var srcPos = (x + y * width) * 4;
  75762. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  75763. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  75764. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  75765. if (DDSTools.StoreLODInAlphaChannel) {
  75766. destArray[index + 3] = lod;
  75767. }
  75768. else {
  75769. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  75770. }
  75771. index += 4;
  75772. }
  75773. }
  75774. return destArray;
  75775. };
  75776. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  75777. var destArray = new Uint8Array(dataLength);
  75778. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  75779. var index = 0;
  75780. for (var y = 0; y < height; y++) {
  75781. for (var x = 0; x < width; x++) {
  75782. var srcPos = (x + y * width) * 4;
  75783. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  75784. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  75785. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  75786. if (DDSTools.StoreLODInAlphaChannel) {
  75787. destArray[index + 3] = lod;
  75788. }
  75789. else {
  75790. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  75791. }
  75792. index += 4;
  75793. }
  75794. }
  75795. return destArray;
  75796. };
  75797. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  75798. var byteArray = new Uint8Array(dataLength);
  75799. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  75800. var index = 0;
  75801. for (var y = 0; y < height; y++) {
  75802. for (var x = 0; x < width; x++) {
  75803. var srcPos = (x + y * width) * 4;
  75804. byteArray[index] = srcData[srcPos + rOffset];
  75805. byteArray[index + 1] = srcData[srcPos + gOffset];
  75806. byteArray[index + 2] = srcData[srcPos + bOffset];
  75807. byteArray[index + 3] = srcData[srcPos + aOffset];
  75808. index += 4;
  75809. }
  75810. }
  75811. return byteArray;
  75812. };
  75813. DDSTools._ExtractLongWordOrder = function (value) {
  75814. if (value === 0 || value === 255 || value === -16777216) {
  75815. return 0;
  75816. }
  75817. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  75818. };
  75819. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  75820. var byteArray = new Uint8Array(dataLength);
  75821. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  75822. var index = 0;
  75823. for (var y = 0; y < height; y++) {
  75824. for (var x = 0; x < width; x++) {
  75825. var srcPos = (x + y * width) * 3;
  75826. byteArray[index] = srcData[srcPos + rOffset];
  75827. byteArray[index + 1] = srcData[srcPos + gOffset];
  75828. byteArray[index + 2] = srcData[srcPos + bOffset];
  75829. index += 3;
  75830. }
  75831. }
  75832. return byteArray;
  75833. };
  75834. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  75835. var byteArray = new Uint8Array(dataLength);
  75836. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  75837. var index = 0;
  75838. for (var y = 0; y < height; y++) {
  75839. for (var x = 0; x < width; x++) {
  75840. var srcPos = (x + y * width);
  75841. byteArray[index] = srcData[srcPos];
  75842. index++;
  75843. }
  75844. }
  75845. return byteArray;
  75846. };
  75847. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  75848. if (lodIndex === void 0) { lodIndex = -1; }
  75849. var ext = engine.getCaps().s3tc;
  75850. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  75851. var fourCC, width, height, dataLength = 0, dataOffset;
  75852. var byteArray, mipmapCount, mip;
  75853. var internalFormat = 0;
  75854. var format = 0;
  75855. var blockBytes = 1;
  75856. if (header[off_magic] !== DDS_MAGIC) {
  75857. BABYLON.Tools.Error("Invalid magic number in DDS header");
  75858. return;
  75859. }
  75860. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  75861. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  75862. return;
  75863. }
  75864. if (info.isCompressed && !ext) {
  75865. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  75866. return;
  75867. }
  75868. var bpp = header[off_RGBbpp];
  75869. dataOffset = header[off_size] + 4;
  75870. var computeFormats = false;
  75871. if (info.isFourCC) {
  75872. fourCC = header[off_pfFourCC];
  75873. switch (fourCC) {
  75874. case FOURCC_DXT1:
  75875. blockBytes = 8;
  75876. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  75877. break;
  75878. case FOURCC_DXT3:
  75879. blockBytes = 16;
  75880. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  75881. break;
  75882. case FOURCC_DXT5:
  75883. blockBytes = 16;
  75884. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  75885. break;
  75886. case FOURCC_D3DFMT_R16G16B16A16F:
  75887. computeFormats = true;
  75888. break;
  75889. case FOURCC_D3DFMT_R32G32B32A32F:
  75890. computeFormats = true;
  75891. break;
  75892. case FOURCC_DX10:
  75893. // There is an additionnal header so dataOffset need to be changed
  75894. dataOffset += 5 * 4; // 5 uints
  75895. var supported = false;
  75896. switch (info.dxgiFormat) {
  75897. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  75898. computeFormats = true;
  75899. supported = true;
  75900. break;
  75901. case DXGI_FORMAT_B8G8R8X8_UNORM:
  75902. info.isRGB = true;
  75903. info.isFourCC = false;
  75904. bpp = 32;
  75905. supported = true;
  75906. break;
  75907. }
  75908. if (supported) {
  75909. break;
  75910. }
  75911. default:
  75912. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  75913. return;
  75914. }
  75915. }
  75916. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  75917. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  75918. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  75919. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  75920. if (computeFormats) {
  75921. format = engine._getWebGLTextureType(info.textureType);
  75922. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  75923. }
  75924. mipmapCount = 1;
  75925. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  75926. mipmapCount = Math.max(1, header[off_mipmapCount]);
  75927. }
  75928. for (var face = 0; face < faces; face++) {
  75929. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  75930. width = header[off_width];
  75931. height = header[off_height];
  75932. for (mip = 0; mip < mipmapCount; ++mip) {
  75933. if (lodIndex === -1 || lodIndex === mip) {
  75934. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  75935. var i = (lodIndex === -1) ? mip : 0;
  75936. if (!info.isCompressed && info.isFourCC) {
  75937. dataLength = width * height * 4;
  75938. var floatArray = null;
  75939. if (engine.badOS || engine.badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) {
  75940. if (bpp === 128) {
  75941. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  75942. }
  75943. else if (bpp === 64) {
  75944. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  75945. }
  75946. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  75947. format = engine._getWebGLTextureType(info.textureType);
  75948. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  75949. }
  75950. else {
  75951. if (bpp === 128) {
  75952. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  75953. }
  75954. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  75955. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  75956. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  75957. format = engine._getWebGLTextureType(info.textureType);
  75958. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  75959. }
  75960. else {
  75961. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  75962. }
  75963. }
  75964. if (floatArray) {
  75965. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  75966. }
  75967. }
  75968. else if (info.isRGB) {
  75969. if (bpp === 24) {
  75970. dataLength = width * height * 3;
  75971. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  75972. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  75973. }
  75974. else {
  75975. dataLength = width * height * 4;
  75976. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  75977. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  75978. }
  75979. }
  75980. else if (info.isLuminance) {
  75981. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  75982. var unpaddedRowSize = width;
  75983. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  75984. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  75985. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  75986. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  75987. }
  75988. else {
  75989. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  75990. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  75991. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  75992. }
  75993. }
  75994. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  75995. width *= 0.5;
  75996. height *= 0.5;
  75997. width = Math.max(1.0, width);
  75998. height = Math.max(1.0, height);
  75999. }
  76000. if (currentFace !== undefined) {
  76001. // Loading a single face
  76002. break;
  76003. }
  76004. }
  76005. };
  76006. DDSTools.StoreLODInAlphaChannel = false;
  76007. return DDSTools;
  76008. }());
  76009. BABYLON.DDSTools = DDSTools;
  76010. })(BABYLON || (BABYLON = {}));
  76011. //# sourceMappingURL=babylon.dds.js.map
  76012. var BABYLON;
  76013. (function (BABYLON) {
  76014. /**
  76015. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  76016. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  76017. */
  76018. var KhronosTextureContainer = /** @class */ (function () {
  76019. /**
  76020. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  76021. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  76022. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  76023. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  76024. */
  76025. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  76026. this.arrayBuffer = arrayBuffer;
  76027. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  76028. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  76029. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  76030. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  76031. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  76032. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  76033. BABYLON.Tools.Error("texture missing KTX identifier");
  76034. return;
  76035. }
  76036. // load the reset of the header in native 32 bit int
  76037. var header = new Int32Array(this.arrayBuffer, 12, 13);
  76038. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  76039. var oppositeEndianess = header[0] === 0x01020304;
  76040. // read all the header elements in order they exist in the file, without modification (sans endainness)
  76041. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  76042. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  76043. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  76044. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  76045. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  76046. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  76047. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  76048. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  76049. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  76050. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  76051. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  76052. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  76053. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  76054. if (this.glType !== 0) {
  76055. BABYLON.Tools.Error("only compressed formats currently supported");
  76056. return;
  76057. }
  76058. else {
  76059. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  76060. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  76061. }
  76062. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  76063. BABYLON.Tools.Error("only 2D textures currently supported");
  76064. return;
  76065. }
  76066. if (this.numberOfArrayElements !== 0) {
  76067. BABYLON.Tools.Error("texture arrays not currently supported");
  76068. return;
  76069. }
  76070. if (this.numberOfFaces !== facesExpected) {
  76071. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  76072. return;
  76073. }
  76074. // we now have a completely validated file, so could use existence of loadType as success
  76075. // would need to make this more elaborate & adjust checks above to support more than one load type
  76076. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  76077. }
  76078. // not as fast hardware based, but will probably never need to use
  76079. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  76080. return ((val & 0xFF) << 24)
  76081. | ((val & 0xFF00) << 8)
  76082. | ((val >> 8) & 0xFF00)
  76083. | ((val >> 24) & 0xFF);
  76084. };
  76085. /**
  76086. * It is assumed that the texture has already been created & is currently bound
  76087. */
  76088. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  76089. switch (this.loadType) {
  76090. case KhronosTextureContainer.COMPRESSED_2D:
  76091. this._upload2DCompressedLevels(gl, loadMipmaps);
  76092. break;
  76093. case KhronosTextureContainer.TEX_2D:
  76094. case KhronosTextureContainer.COMPRESSED_3D:
  76095. case KhronosTextureContainer.TEX_3D:
  76096. }
  76097. };
  76098. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  76099. // initialize width & height for level 1
  76100. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  76101. var width = this.pixelWidth;
  76102. var height = this.pixelHeight;
  76103. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  76104. for (var level = 0; level < mipmapCount; level++) {
  76105. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  76106. for (var face = 0; face < this.numberOfFaces; face++) {
  76107. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  76108. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  76109. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  76110. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  76111. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  76112. }
  76113. width = Math.max(1.0, width * 0.5);
  76114. height = Math.max(1.0, height * 0.5);
  76115. }
  76116. };
  76117. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  76118. // load types
  76119. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  76120. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  76121. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  76122. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  76123. return KhronosTextureContainer;
  76124. }());
  76125. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  76126. })(BABYLON || (BABYLON = {}));
  76127. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  76128. var BABYLON;
  76129. (function (BABYLON) {
  76130. var Debug = /** @class */ (function () {
  76131. function Debug() {
  76132. }
  76133. Debug.AxesViewer = /** @class */ (function () {
  76134. function AxesViewer(scene, scaleLines) {
  76135. if (scaleLines === void 0) { scaleLines = 1; }
  76136. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  76137. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  76138. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  76139. this.scaleLines = 1;
  76140. this.scaleLines = scaleLines;
  76141. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  76142. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  76143. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  76144. this._xmesh.renderingGroupId = 2;
  76145. this._ymesh.renderingGroupId = 2;
  76146. this._zmesh.renderingGroupId = 2;
  76147. this._xmesh.material.checkReadyOnlyOnce = true;
  76148. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  76149. this._ymesh.material.checkReadyOnlyOnce = true;
  76150. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  76151. this._zmesh.material.checkReadyOnlyOnce = true;
  76152. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  76153. this.scene = scene;
  76154. }
  76155. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  76156. var scaleLines = this.scaleLines;
  76157. if (this._xmesh) {
  76158. this._xmesh.position.copyFrom(position);
  76159. }
  76160. if (this._ymesh) {
  76161. this._ymesh.position.copyFrom(position);
  76162. }
  76163. if (this._zmesh) {
  76164. this._zmesh.position.copyFrom(position);
  76165. }
  76166. var point2 = this._xline[1];
  76167. point2.x = xaxis.x * scaleLines;
  76168. point2.y = xaxis.y * scaleLines;
  76169. point2.z = xaxis.z * scaleLines;
  76170. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  76171. point2 = this._yline[1];
  76172. point2.x = yaxis.x * scaleLines;
  76173. point2.y = yaxis.y * scaleLines;
  76174. point2.z = yaxis.z * scaleLines;
  76175. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  76176. point2 = this._zline[1];
  76177. point2.x = zaxis.x * scaleLines;
  76178. point2.y = zaxis.y * scaleLines;
  76179. point2.z = zaxis.z * scaleLines;
  76180. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  76181. };
  76182. AxesViewer.prototype.dispose = function () {
  76183. if (this._xmesh) {
  76184. this._xmesh.dispose();
  76185. }
  76186. if (this._ymesh) {
  76187. this._ymesh.dispose();
  76188. }
  76189. if (this._zmesh) {
  76190. this._zmesh.dispose();
  76191. }
  76192. this._xmesh = null;
  76193. this._ymesh = null;
  76194. this._zmesh = null;
  76195. this.scene = null;
  76196. };
  76197. return AxesViewer;
  76198. }());
  76199. Debug.BoneAxesViewer = /** @class */ (function (_super) {
  76200. __extends(BoneAxesViewer, _super);
  76201. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  76202. if (scaleLines === void 0) { scaleLines = 1; }
  76203. var _this = _super.call(this, scene, scaleLines) || this;
  76204. _this.pos = BABYLON.Vector3.Zero();
  76205. _this.xaxis = BABYLON.Vector3.Zero();
  76206. _this.yaxis = BABYLON.Vector3.Zero();
  76207. _this.zaxis = BABYLON.Vector3.Zero();
  76208. _this.mesh = mesh;
  76209. _this.bone = bone;
  76210. return _this;
  76211. }
  76212. BoneAxesViewer.prototype.update = function () {
  76213. if (!this.mesh || !this.bone) {
  76214. return;
  76215. }
  76216. var bone = this.bone;
  76217. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  76218. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  76219. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  76220. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  76221. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  76222. };
  76223. BoneAxesViewer.prototype.dispose = function () {
  76224. if (this.mesh) {
  76225. this.mesh = null;
  76226. this.bone = null;
  76227. _super.prototype.dispose.call(this);
  76228. }
  76229. };
  76230. return BoneAxesViewer;
  76231. }(Debug.AxesViewer));
  76232. Debug.PhysicsViewer = /** @class */ (function () {
  76233. function PhysicsViewer(scene) {
  76234. this._impostors = [];
  76235. this._meshes = [];
  76236. this._numMeshes = 0;
  76237. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  76238. var physicEngine = this._scene.getPhysicsEngine();
  76239. if (physicEngine) {
  76240. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  76241. }
  76242. }
  76243. PhysicsViewer.prototype._updateDebugMeshes = function () {
  76244. var plugin = this._physicsEnginePlugin;
  76245. for (var i = 0; i < this._numMeshes; i++) {
  76246. var impostor = this._impostors[i];
  76247. if (!impostor) {
  76248. continue;
  76249. }
  76250. if (impostor.isDisposed) {
  76251. this.hideImpostor(this._impostors[i--]);
  76252. }
  76253. else {
  76254. var mesh = this._meshes[i];
  76255. if (mesh && plugin) {
  76256. plugin.syncMeshWithImpostor(mesh, impostor);
  76257. }
  76258. }
  76259. }
  76260. };
  76261. PhysicsViewer.prototype.showImpostor = function (impostor) {
  76262. if (!this._scene) {
  76263. return;
  76264. }
  76265. for (var i = 0; i < this._numMeshes; i++) {
  76266. if (this._impostors[i] == impostor) {
  76267. return;
  76268. }
  76269. }
  76270. var debugMesh = this._getDebugMesh(impostor, this._scene);
  76271. if (debugMesh) {
  76272. this._impostors[this._numMeshes] = impostor;
  76273. this._meshes[this._numMeshes] = debugMesh;
  76274. if (this._numMeshes === 0) {
  76275. this._renderFunction = this._updateDebugMeshes.bind(this);
  76276. this._scene.registerBeforeRender(this._renderFunction);
  76277. }
  76278. this._numMeshes++;
  76279. }
  76280. };
  76281. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  76282. if (!impostor || !this._scene) {
  76283. return;
  76284. }
  76285. var removed = false;
  76286. for (var i = 0; i < this._numMeshes; i++) {
  76287. if (this._impostors[i] == impostor) {
  76288. var mesh = this._meshes[i];
  76289. if (!mesh) {
  76290. continue;
  76291. }
  76292. this._scene.removeMesh(mesh);
  76293. mesh.dispose();
  76294. this._numMeshes--;
  76295. if (this._numMeshes > 0) {
  76296. this._meshes[i] = this._meshes[this._numMeshes];
  76297. this._impostors[i] = this._impostors[this._numMeshes];
  76298. this._meshes[this._numMeshes] = null;
  76299. this._impostors[this._numMeshes] = null;
  76300. }
  76301. else {
  76302. this._meshes[0] = null;
  76303. this._impostors[0] = null;
  76304. }
  76305. removed = true;
  76306. break;
  76307. }
  76308. }
  76309. if (removed && this._numMeshes === 0) {
  76310. this._scene.unregisterBeforeRender(this._renderFunction);
  76311. }
  76312. };
  76313. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  76314. if (!this._debugMaterial) {
  76315. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  76316. this._debugMaterial.wireframe = true;
  76317. }
  76318. return this._debugMaterial;
  76319. };
  76320. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  76321. if (!this._debugBoxMesh) {
  76322. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  76323. this._debugBoxMesh.renderingGroupId = 1;
  76324. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  76325. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  76326. scene.removeMesh(this._debugBoxMesh);
  76327. }
  76328. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  76329. };
  76330. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  76331. if (!this._debugSphereMesh) {
  76332. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  76333. this._debugSphereMesh.renderingGroupId = 1;
  76334. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  76335. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  76336. scene.removeMesh(this._debugSphereMesh);
  76337. }
  76338. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  76339. };
  76340. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  76341. var mesh = null;
  76342. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  76343. mesh = this._getDebugBoxMesh(scene);
  76344. impostor.getBoxSizeToRef(mesh.scaling);
  76345. }
  76346. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  76347. mesh = this._getDebugSphereMesh(scene);
  76348. var radius = impostor.getRadius();
  76349. mesh.scaling.x = radius * 2;
  76350. mesh.scaling.y = radius * 2;
  76351. mesh.scaling.z = radius * 2;
  76352. }
  76353. return mesh;
  76354. };
  76355. PhysicsViewer.prototype.dispose = function () {
  76356. for (var i = 0; i < this._numMeshes; i++) {
  76357. this.hideImpostor(this._impostors[i]);
  76358. }
  76359. if (this._debugBoxMesh) {
  76360. this._debugBoxMesh.dispose();
  76361. }
  76362. if (this._debugSphereMesh) {
  76363. this._debugSphereMesh.dispose();
  76364. }
  76365. if (this._debugMaterial) {
  76366. this._debugMaterial.dispose();
  76367. }
  76368. this._impostors.length = 0;
  76369. this._scene = null;
  76370. this._physicsEnginePlugin = null;
  76371. };
  76372. return PhysicsViewer;
  76373. }());
  76374. Debug.SkeletonViewer = /** @class */ (function () {
  76375. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  76376. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  76377. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  76378. this.skeleton = skeleton;
  76379. this.mesh = mesh;
  76380. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  76381. this.renderingGroupId = renderingGroupId;
  76382. this.color = BABYLON.Color3.White();
  76383. this._debugLines = new Array();
  76384. this._isEnabled = false;
  76385. this._scene = scene;
  76386. this.update();
  76387. this._renderFunction = this.update.bind(this);
  76388. }
  76389. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  76390. get: function () {
  76391. return this._isEnabled;
  76392. },
  76393. set: function (value) {
  76394. if (this._isEnabled === value) {
  76395. return;
  76396. }
  76397. this._isEnabled = value;
  76398. if (value) {
  76399. this._scene.registerBeforeRender(this._renderFunction);
  76400. }
  76401. else {
  76402. this._scene.unregisterBeforeRender(this._renderFunction);
  76403. }
  76404. },
  76405. enumerable: true,
  76406. configurable: true
  76407. });
  76408. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  76409. if (x === void 0) { x = 0; }
  76410. if (y === void 0) { y = 0; }
  76411. if (z === void 0) { z = 0; }
  76412. var tmat = BABYLON.Tmp.Matrix[0];
  76413. var parentBone = bone.getParent();
  76414. tmat.copyFrom(bone.getLocalMatrix());
  76415. if (x !== 0 || y !== 0 || z !== 0) {
  76416. var tmat2 = BABYLON.Tmp.Matrix[1];
  76417. BABYLON.Matrix.IdentityToRef(tmat2);
  76418. tmat2.m[12] = x;
  76419. tmat2.m[13] = y;
  76420. tmat2.m[14] = z;
  76421. tmat2.multiplyToRef(tmat, tmat);
  76422. }
  76423. if (parentBone) {
  76424. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  76425. }
  76426. tmat.multiplyToRef(meshMat, tmat);
  76427. position.x = tmat.m[12];
  76428. position.y = tmat.m[13];
  76429. position.z = tmat.m[14];
  76430. };
  76431. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  76432. var len = bones.length;
  76433. var meshPos = this.mesh.position;
  76434. for (var i = 0; i < len; i++) {
  76435. var bone = bones[i];
  76436. var points = this._debugLines[i];
  76437. if (!points) {
  76438. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  76439. this._debugLines[i] = points;
  76440. }
  76441. this._getBonePosition(points[0], bone, meshMat);
  76442. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  76443. points[0].subtractInPlace(meshPos);
  76444. points[1].subtractInPlace(meshPos);
  76445. }
  76446. };
  76447. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  76448. var len = bones.length;
  76449. var boneNum = 0;
  76450. var meshPos = this.mesh.position;
  76451. for (var i = len - 1; i >= 0; i--) {
  76452. var childBone = bones[i];
  76453. var parentBone = childBone.getParent();
  76454. if (!parentBone) {
  76455. continue;
  76456. }
  76457. var points = this._debugLines[boneNum];
  76458. if (!points) {
  76459. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  76460. this._debugLines[boneNum] = points;
  76461. }
  76462. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  76463. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  76464. points[0].subtractInPlace(meshPos);
  76465. points[1].subtractInPlace(meshPos);
  76466. boneNum++;
  76467. }
  76468. };
  76469. SkeletonViewer.prototype.update = function () {
  76470. if (this.autoUpdateBonesMatrices) {
  76471. this.skeleton.computeAbsoluteTransforms();
  76472. }
  76473. if (this.skeleton.bones[0].length === undefined) {
  76474. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  76475. }
  76476. else {
  76477. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  76478. }
  76479. if (!this._debugMesh) {
  76480. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  76481. this._debugMesh.renderingGroupId = this.renderingGroupId;
  76482. }
  76483. else {
  76484. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  76485. }
  76486. this._debugMesh.position.copyFrom(this.mesh.position);
  76487. this._debugMesh.color = this.color;
  76488. };
  76489. SkeletonViewer.prototype.dispose = function () {
  76490. if (this._debugMesh) {
  76491. this.isEnabled = false;
  76492. this._debugMesh.dispose();
  76493. this._debugMesh = null;
  76494. }
  76495. };
  76496. return SkeletonViewer;
  76497. }());
  76498. return Debug;
  76499. }());
  76500. BABYLON.Debug = Debug;
  76501. })(BABYLON || (BABYLON = {}));
  76502. //# sourceMappingURL=babylon.debugModules.js.map
  76503. var BABYLON;
  76504. (function (BABYLON) {
  76505. var RayHelper = /** @class */ (function () {
  76506. function RayHelper(ray) {
  76507. this.ray = ray;
  76508. }
  76509. RayHelper.CreateAndShow = function (ray, scene, color) {
  76510. var helper = new RayHelper(ray);
  76511. helper.show(scene, color);
  76512. return helper;
  76513. };
  76514. RayHelper.prototype.show = function (scene, color) {
  76515. if (!this._renderFunction && this.ray) {
  76516. var ray = this.ray;
  76517. this._renderFunction = this._render.bind(this);
  76518. this._scene = scene;
  76519. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  76520. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  76521. if (this._renderFunction) {
  76522. this._scene.registerBeforeRender(this._renderFunction);
  76523. }
  76524. }
  76525. if (color && this._renderLine) {
  76526. this._renderLine.color.copyFrom(color);
  76527. }
  76528. };
  76529. RayHelper.prototype.hide = function () {
  76530. if (this._renderFunction && this._scene) {
  76531. this._scene.unregisterBeforeRender(this._renderFunction);
  76532. this._scene = null;
  76533. this._renderFunction = null;
  76534. if (this._renderLine) {
  76535. this._renderLine.dispose();
  76536. this._renderLine = null;
  76537. }
  76538. this._renderPoints = [];
  76539. }
  76540. };
  76541. RayHelper.prototype._render = function () {
  76542. var ray = this.ray;
  76543. if (!ray) {
  76544. return;
  76545. }
  76546. var point = this._renderPoints[1];
  76547. var len = Math.min(ray.length, 1000000);
  76548. point.copyFrom(ray.direction);
  76549. point.scaleInPlace(len);
  76550. point.addInPlace(ray.origin);
  76551. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  76552. };
  76553. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  76554. this._attachedToMesh = mesh;
  76555. var ray = this.ray;
  76556. if (!ray) {
  76557. return;
  76558. }
  76559. if (!ray.direction) {
  76560. ray.direction = BABYLON.Vector3.Zero();
  76561. }
  76562. if (!ray.origin) {
  76563. ray.origin = BABYLON.Vector3.Zero();
  76564. }
  76565. if (length) {
  76566. ray.length = length;
  76567. }
  76568. if (!meshSpaceOrigin) {
  76569. meshSpaceOrigin = BABYLON.Vector3.Zero();
  76570. }
  76571. if (!meshSpaceDirection) {
  76572. // -1 so that this will work with Mesh.lookAt
  76573. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  76574. }
  76575. if (!this._meshSpaceDirection) {
  76576. this._meshSpaceDirection = meshSpaceDirection.clone();
  76577. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  76578. }
  76579. else {
  76580. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  76581. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  76582. }
  76583. if (!this._updateToMeshFunction) {
  76584. this._updateToMeshFunction = this._updateToMesh.bind(this);
  76585. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  76586. }
  76587. this._updateToMesh();
  76588. };
  76589. RayHelper.prototype.detachFromMesh = function () {
  76590. if (this._attachedToMesh) {
  76591. if (this._updateToMeshFunction) {
  76592. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  76593. }
  76594. this._attachedToMesh = null;
  76595. this._updateToMeshFunction = null;
  76596. }
  76597. };
  76598. RayHelper.prototype._updateToMesh = function () {
  76599. var ray = this.ray;
  76600. if (!this._attachedToMesh || !ray) {
  76601. return;
  76602. }
  76603. if (this._attachedToMesh._isDisposed) {
  76604. this.detachFromMesh();
  76605. return;
  76606. }
  76607. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  76608. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  76609. };
  76610. RayHelper.prototype.dispose = function () {
  76611. this.hide();
  76612. this.detachFromMesh();
  76613. this.ray = null;
  76614. };
  76615. return RayHelper;
  76616. }());
  76617. BABYLON.RayHelper = RayHelper;
  76618. })(BABYLON || (BABYLON = {}));
  76619. //# sourceMappingURL=babylon.rayHelper.js.map
  76620. var BABYLON;
  76621. (function (BABYLON) {
  76622. // load the inspector using require, if not present in the global namespace.
  76623. var DebugLayer = /** @class */ (function () {
  76624. function DebugLayer(scene) {
  76625. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  76626. this._scene = scene;
  76627. // load inspector using require, if it doesn't exist on the global namespace.
  76628. }
  76629. /** Creates the inspector window. */
  76630. DebugLayer.prototype._createInspector = function (config) {
  76631. if (config === void 0) { config = {}; }
  76632. var popup = config.popup || false;
  76633. var initialTab = config.initialTab || 0;
  76634. var parentElement = config.parentElement || null;
  76635. if (!this._inspector) {
  76636. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  76637. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  76638. } // else nothing to do,; instance is already existing
  76639. };
  76640. DebugLayer.prototype.isVisible = function () {
  76641. if (!this._inspector) {
  76642. return false;
  76643. }
  76644. return true;
  76645. };
  76646. DebugLayer.prototype.hide = function () {
  76647. if (this._inspector) {
  76648. try {
  76649. this._inspector.dispose();
  76650. }
  76651. catch (e) {
  76652. // If the inspector has been removed directly from the inspector tool
  76653. }
  76654. this._inspector = null;
  76655. }
  76656. };
  76657. DebugLayer.prototype.show = function (config) {
  76658. if (config === void 0) { config = {}; }
  76659. if (typeof this.BJSINSPECTOR == 'undefined') {
  76660. // Load inspector and add it to the DOM
  76661. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  76662. }
  76663. else {
  76664. // Otherwise creates the inspector
  76665. this._createInspector(config);
  76666. }
  76667. };
  76668. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  76669. return DebugLayer;
  76670. }());
  76671. BABYLON.DebugLayer = DebugLayer;
  76672. })(BABYLON || (BABYLON = {}));
  76673. //# sourceMappingURL=babylon.debugLayer.js.map
  76674. var BABYLON;
  76675. (function (BABYLON) {
  76676. var BoundingBoxRenderer = /** @class */ (function () {
  76677. function BoundingBoxRenderer(scene) {
  76678. this.frontColor = new BABYLON.Color3(1, 1, 1);
  76679. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  76680. this.showBackLines = true;
  76681. this.renderList = new BABYLON.SmartArray(32);
  76682. this._vertexBuffers = {};
  76683. this._scene = scene;
  76684. }
  76685. BoundingBoxRenderer.prototype._prepareRessources = function () {
  76686. if (this._colorShader) {
  76687. return;
  76688. }
  76689. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  76690. attributes: [BABYLON.VertexBuffer.PositionKind],
  76691. uniforms: ["world", "viewProjection", "color"]
  76692. });
  76693. var engine = this._scene.getEngine();
  76694. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  76695. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  76696. this._createIndexBuffer();
  76697. };
  76698. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  76699. var engine = this._scene.getEngine();
  76700. 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]);
  76701. };
  76702. BoundingBoxRenderer.prototype._rebuild = function () {
  76703. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  76704. if (vb) {
  76705. vb._rebuild();
  76706. }
  76707. this._createIndexBuffer();
  76708. };
  76709. BoundingBoxRenderer.prototype.reset = function () {
  76710. this.renderList.reset();
  76711. };
  76712. BoundingBoxRenderer.prototype.render = function () {
  76713. if (this.renderList.length === 0) {
  76714. return;
  76715. }
  76716. this._prepareRessources();
  76717. if (!this._colorShader.isReady()) {
  76718. return;
  76719. }
  76720. var engine = this._scene.getEngine();
  76721. engine.setDepthWrite(false);
  76722. this._colorShader._preBind();
  76723. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  76724. var boundingBox = this.renderList.data[boundingBoxIndex];
  76725. var min = boundingBox.minimum;
  76726. var max = boundingBox.maximum;
  76727. var diff = max.subtract(min);
  76728. var median = min.add(diff.scale(0.5));
  76729. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  76730. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  76731. .multiply(boundingBox.getWorldMatrix());
  76732. // VBOs
  76733. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  76734. if (this.showBackLines) {
  76735. // Back
  76736. engine.setDepthFunctionToGreaterOrEqual();
  76737. this._scene.resetCachedMaterial();
  76738. this._colorShader.setColor4("color", this.backColor.toColor4());
  76739. this._colorShader.bind(worldMatrix);
  76740. // Draw order
  76741. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  76742. }
  76743. // Front
  76744. engine.setDepthFunctionToLess();
  76745. this._scene.resetCachedMaterial();
  76746. this._colorShader.setColor4("color", this.frontColor.toColor4());
  76747. this._colorShader.bind(worldMatrix);
  76748. // Draw order
  76749. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  76750. }
  76751. this._colorShader.unbind();
  76752. engine.setDepthFunctionToLessOrEqual();
  76753. engine.setDepthWrite(true);
  76754. };
  76755. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  76756. this._prepareRessources();
  76757. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  76758. return;
  76759. }
  76760. var engine = this._scene.getEngine();
  76761. engine.setDepthWrite(false);
  76762. engine.setColorWrite(false);
  76763. this._colorShader._preBind();
  76764. var boundingBox = mesh._boundingInfo.boundingBox;
  76765. var min = boundingBox.minimum;
  76766. var max = boundingBox.maximum;
  76767. var diff = max.subtract(min);
  76768. var median = min.add(diff.scale(0.5));
  76769. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  76770. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  76771. .multiply(boundingBox.getWorldMatrix());
  76772. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  76773. engine.setDepthFunctionToLess();
  76774. this._scene.resetCachedMaterial();
  76775. this._colorShader.bind(worldMatrix);
  76776. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  76777. this._colorShader.unbind();
  76778. engine.setDepthFunctionToLessOrEqual();
  76779. engine.setDepthWrite(true);
  76780. engine.setColorWrite(true);
  76781. };
  76782. BoundingBoxRenderer.prototype.dispose = function () {
  76783. if (!this._colorShader) {
  76784. return;
  76785. }
  76786. this.renderList.dispose();
  76787. this._colorShader.dispose();
  76788. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  76789. if (buffer) {
  76790. buffer.dispose();
  76791. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  76792. }
  76793. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  76794. };
  76795. return BoundingBoxRenderer;
  76796. }());
  76797. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  76798. })(BABYLON || (BABYLON = {}));
  76799. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  76800. var BABYLON;
  76801. (function (BABYLON) {
  76802. var MorphTarget = /** @class */ (function () {
  76803. function MorphTarget(name, influence) {
  76804. if (influence === void 0) { influence = 0; }
  76805. this.name = name;
  76806. this.animations = new Array();
  76807. this._positions = null;
  76808. this._normals = null;
  76809. this._tangents = null;
  76810. this.onInfluenceChanged = new BABYLON.Observable();
  76811. this.influence = influence;
  76812. }
  76813. Object.defineProperty(MorphTarget.prototype, "influence", {
  76814. get: function () {
  76815. return this._influence;
  76816. },
  76817. set: function (influence) {
  76818. if (this._influence === influence) {
  76819. return;
  76820. }
  76821. var previous = this._influence;
  76822. this._influence = influence;
  76823. if (this.onInfluenceChanged.hasObservers) {
  76824. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  76825. }
  76826. },
  76827. enumerable: true,
  76828. configurable: true
  76829. });
  76830. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  76831. get: function () {
  76832. return !!this._positions;
  76833. },
  76834. enumerable: true,
  76835. configurable: true
  76836. });
  76837. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  76838. get: function () {
  76839. return !!this._normals;
  76840. },
  76841. enumerable: true,
  76842. configurable: true
  76843. });
  76844. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  76845. get: function () {
  76846. return !!this._tangents;
  76847. },
  76848. enumerable: true,
  76849. configurable: true
  76850. });
  76851. MorphTarget.prototype.setPositions = function (data) {
  76852. this._positions = data;
  76853. };
  76854. MorphTarget.prototype.getPositions = function () {
  76855. return this._positions;
  76856. };
  76857. MorphTarget.prototype.setNormals = function (data) {
  76858. this._normals = data;
  76859. };
  76860. MorphTarget.prototype.getNormals = function () {
  76861. return this._normals;
  76862. };
  76863. MorphTarget.prototype.setTangents = function (data) {
  76864. this._tangents = data;
  76865. };
  76866. MorphTarget.prototype.getTangents = function () {
  76867. return this._tangents;
  76868. };
  76869. /**
  76870. * Serializes the current target into a Serialization object.
  76871. * Returns the serialized object.
  76872. */
  76873. MorphTarget.prototype.serialize = function () {
  76874. var serializationObject = {};
  76875. serializationObject.name = this.name;
  76876. serializationObject.influence = this.influence;
  76877. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  76878. if (this.hasNormals) {
  76879. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  76880. }
  76881. if (this.hasTangents) {
  76882. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  76883. }
  76884. // Animations
  76885. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  76886. return serializationObject;
  76887. };
  76888. // Statics
  76889. MorphTarget.Parse = function (serializationObject) {
  76890. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  76891. result.setPositions(serializationObject.positions);
  76892. if (serializationObject.normals) {
  76893. result.setNormals(serializationObject.normals);
  76894. }
  76895. if (serializationObject.tangents) {
  76896. result.setTangents(serializationObject.tangents);
  76897. }
  76898. // Animations
  76899. if (serializationObject.animations) {
  76900. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  76901. var parsedAnimation = serializationObject.animations[animationIndex];
  76902. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  76903. }
  76904. }
  76905. return result;
  76906. };
  76907. MorphTarget.FromMesh = function (mesh, name, influence) {
  76908. if (!name) {
  76909. name = mesh.name;
  76910. }
  76911. var result = new MorphTarget(name, influence);
  76912. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  76913. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  76914. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  76915. }
  76916. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  76917. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  76918. }
  76919. return result;
  76920. };
  76921. return MorphTarget;
  76922. }());
  76923. BABYLON.MorphTarget = MorphTarget;
  76924. })(BABYLON || (BABYLON = {}));
  76925. //# sourceMappingURL=babylon.morphTarget.js.map
  76926. var BABYLON;
  76927. (function (BABYLON) {
  76928. var MorphTargetManager = /** @class */ (function () {
  76929. function MorphTargetManager(scene) {
  76930. if (scene === void 0) { scene = null; }
  76931. this._targets = new Array();
  76932. this._targetObservable = new Array();
  76933. this._activeTargets = new BABYLON.SmartArray(16);
  76934. this._supportsNormals = false;
  76935. this._supportsTangents = false;
  76936. this._vertexCount = 0;
  76937. this._uniqueId = 0;
  76938. this._tempInfluences = new Array();
  76939. if (!scene) {
  76940. scene = BABYLON.Engine.LastCreatedScene;
  76941. }
  76942. this._scene = scene;
  76943. if (this._scene) {
  76944. this._scene.morphTargetManagers.push(this);
  76945. this._uniqueId = this._scene.getUniqueId();
  76946. }
  76947. }
  76948. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  76949. get: function () {
  76950. return this._uniqueId;
  76951. },
  76952. enumerable: true,
  76953. configurable: true
  76954. });
  76955. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  76956. get: function () {
  76957. return this._vertexCount;
  76958. },
  76959. enumerable: true,
  76960. configurable: true
  76961. });
  76962. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  76963. get: function () {
  76964. return this._supportsNormals;
  76965. },
  76966. enumerable: true,
  76967. configurable: true
  76968. });
  76969. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  76970. get: function () {
  76971. return this._supportsTangents;
  76972. },
  76973. enumerable: true,
  76974. configurable: true
  76975. });
  76976. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  76977. get: function () {
  76978. return this._targets.length;
  76979. },
  76980. enumerable: true,
  76981. configurable: true
  76982. });
  76983. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  76984. get: function () {
  76985. return this._activeTargets.length;
  76986. },
  76987. enumerable: true,
  76988. configurable: true
  76989. });
  76990. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  76991. get: function () {
  76992. return this._influences;
  76993. },
  76994. enumerable: true,
  76995. configurable: true
  76996. });
  76997. MorphTargetManager.prototype.getActiveTarget = function (index) {
  76998. return this._activeTargets.data[index];
  76999. };
  77000. MorphTargetManager.prototype.getTarget = function (index) {
  77001. return this._targets[index];
  77002. };
  77003. MorphTargetManager.prototype.addTarget = function (target) {
  77004. var _this = this;
  77005. this._targets.push(target);
  77006. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  77007. _this._syncActiveTargets(needUpdate);
  77008. }));
  77009. this._syncActiveTargets(true);
  77010. };
  77011. MorphTargetManager.prototype.removeTarget = function (target) {
  77012. var index = this._targets.indexOf(target);
  77013. if (index >= 0) {
  77014. this._targets.splice(index, 1);
  77015. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  77016. this._syncActiveTargets(true);
  77017. }
  77018. };
  77019. /**
  77020. * Serializes the current manager into a Serialization object.
  77021. * Returns the serialized object.
  77022. */
  77023. MorphTargetManager.prototype.serialize = function () {
  77024. var serializationObject = {};
  77025. serializationObject.id = this.uniqueId;
  77026. serializationObject.targets = [];
  77027. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  77028. var target = _a[_i];
  77029. serializationObject.targets.push(target.serialize());
  77030. }
  77031. return serializationObject;
  77032. };
  77033. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  77034. var influenceCount = 0;
  77035. this._activeTargets.reset();
  77036. this._supportsNormals = true;
  77037. this._supportsTangents = true;
  77038. this._vertexCount = 0;
  77039. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  77040. var target = _a[_i];
  77041. this._activeTargets.push(target);
  77042. this._tempInfluences[influenceCount++] = target.influence;
  77043. var positions = target.getPositions();
  77044. if (positions) {
  77045. this._supportsNormals = this._supportsNormals && target.hasNormals;
  77046. this._supportsTangents = this._supportsTangents && target.hasTangents;
  77047. var vertexCount = positions.length / 3;
  77048. if (this._vertexCount === 0) {
  77049. this._vertexCount = vertexCount;
  77050. }
  77051. else if (this._vertexCount !== vertexCount) {
  77052. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  77053. return;
  77054. }
  77055. }
  77056. }
  77057. if (!this._influences || this._influences.length !== influenceCount) {
  77058. this._influences = new Float32Array(influenceCount);
  77059. }
  77060. for (var index = 0; index < influenceCount; index++) {
  77061. this._influences[index] = this._tempInfluences[index];
  77062. }
  77063. if (needUpdate && this._scene) {
  77064. // Flag meshes as dirty to resync with the active targets
  77065. for (var _b = 0, _c = this._scene.meshes; _b < _c.length; _b++) {
  77066. var mesh = _c[_b];
  77067. if (mesh.morphTargetManager === this) {
  77068. mesh._syncGeometryWithMorphTargetManager();
  77069. }
  77070. }
  77071. }
  77072. };
  77073. // Statics
  77074. MorphTargetManager.Parse = function (serializationObject, scene) {
  77075. var result = new MorphTargetManager(scene);
  77076. result._uniqueId = serializationObject.id;
  77077. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  77078. var targetData = _a[_i];
  77079. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  77080. }
  77081. return result;
  77082. };
  77083. return MorphTargetManager;
  77084. }());
  77085. BABYLON.MorphTargetManager = MorphTargetManager;
  77086. })(BABYLON || (BABYLON = {}));
  77087. //# sourceMappingURL=babylon.morphTargetManager.js.map
  77088. var BABYLON;
  77089. (function (BABYLON) {
  77090. var Octree = /** @class */ (function () {
  77091. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  77092. if (maxDepth === void 0) { maxDepth = 2; }
  77093. this.maxDepth = maxDepth;
  77094. this.dynamicContent = new Array();
  77095. this._maxBlockCapacity = maxBlockCapacity || 64;
  77096. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  77097. this._creationFunc = creationFunc;
  77098. }
  77099. // Methods
  77100. Octree.prototype.update = function (worldMin, worldMax, entries) {
  77101. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  77102. };
  77103. Octree.prototype.addMesh = function (entry) {
  77104. for (var index = 0; index < this.blocks.length; index++) {
  77105. var block = this.blocks[index];
  77106. block.addEntry(entry);
  77107. }
  77108. };
  77109. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  77110. this._selectionContent.reset();
  77111. for (var index = 0; index < this.blocks.length; index++) {
  77112. var block = this.blocks[index];
  77113. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  77114. }
  77115. if (allowDuplicate) {
  77116. this._selectionContent.concat(this.dynamicContent);
  77117. }
  77118. else {
  77119. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  77120. }
  77121. return this._selectionContent;
  77122. };
  77123. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  77124. this._selectionContent.reset();
  77125. for (var index = 0; index < this.blocks.length; index++) {
  77126. var block = this.blocks[index];
  77127. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  77128. }
  77129. if (allowDuplicate) {
  77130. this._selectionContent.concat(this.dynamicContent);
  77131. }
  77132. else {
  77133. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  77134. }
  77135. return this._selectionContent;
  77136. };
  77137. Octree.prototype.intersectsRay = function (ray) {
  77138. this._selectionContent.reset();
  77139. for (var index = 0; index < this.blocks.length; index++) {
  77140. var block = this.blocks[index];
  77141. block.intersectsRay(ray, this._selectionContent);
  77142. }
  77143. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  77144. return this._selectionContent;
  77145. };
  77146. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  77147. target.blocks = new Array();
  77148. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  77149. // Segmenting space
  77150. for (var x = 0; x < 2; x++) {
  77151. for (var y = 0; y < 2; y++) {
  77152. for (var z = 0; z < 2; z++) {
  77153. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  77154. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  77155. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  77156. block.addEntries(entries);
  77157. target.blocks.push(block);
  77158. }
  77159. }
  77160. }
  77161. };
  77162. Octree.CreationFuncForMeshes = function (entry, block) {
  77163. var boundingInfo = entry.getBoundingInfo();
  77164. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  77165. block.entries.push(entry);
  77166. }
  77167. };
  77168. Octree.CreationFuncForSubMeshes = function (entry, block) {
  77169. var boundingInfo = entry.getBoundingInfo();
  77170. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  77171. block.entries.push(entry);
  77172. }
  77173. };
  77174. return Octree;
  77175. }());
  77176. BABYLON.Octree = Octree;
  77177. })(BABYLON || (BABYLON = {}));
  77178. //# sourceMappingURL=babylon.octree.js.map
  77179. var BABYLON;
  77180. (function (BABYLON) {
  77181. var OctreeBlock = /** @class */ (function () {
  77182. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  77183. this.entries = new Array();
  77184. this._boundingVectors = new Array();
  77185. this._capacity = capacity;
  77186. this._depth = depth;
  77187. this._maxDepth = maxDepth;
  77188. this._creationFunc = creationFunc;
  77189. this._minPoint = minPoint;
  77190. this._maxPoint = maxPoint;
  77191. this._boundingVectors.push(minPoint.clone());
  77192. this._boundingVectors.push(maxPoint.clone());
  77193. this._boundingVectors.push(minPoint.clone());
  77194. this._boundingVectors[2].x = maxPoint.x;
  77195. this._boundingVectors.push(minPoint.clone());
  77196. this._boundingVectors[3].y = maxPoint.y;
  77197. this._boundingVectors.push(minPoint.clone());
  77198. this._boundingVectors[4].z = maxPoint.z;
  77199. this._boundingVectors.push(maxPoint.clone());
  77200. this._boundingVectors[5].z = minPoint.z;
  77201. this._boundingVectors.push(maxPoint.clone());
  77202. this._boundingVectors[6].x = minPoint.x;
  77203. this._boundingVectors.push(maxPoint.clone());
  77204. this._boundingVectors[7].y = minPoint.y;
  77205. }
  77206. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  77207. // Property
  77208. get: function () {
  77209. return this._capacity;
  77210. },
  77211. enumerable: true,
  77212. configurable: true
  77213. });
  77214. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  77215. get: function () {
  77216. return this._minPoint;
  77217. },
  77218. enumerable: true,
  77219. configurable: true
  77220. });
  77221. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  77222. get: function () {
  77223. return this._maxPoint;
  77224. },
  77225. enumerable: true,
  77226. configurable: true
  77227. });
  77228. // Methods
  77229. OctreeBlock.prototype.addEntry = function (entry) {
  77230. if (this.blocks) {
  77231. for (var index = 0; index < this.blocks.length; index++) {
  77232. var block = this.blocks[index];
  77233. block.addEntry(entry);
  77234. }
  77235. return;
  77236. }
  77237. this._creationFunc(entry, this);
  77238. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  77239. this.createInnerBlocks();
  77240. }
  77241. };
  77242. OctreeBlock.prototype.addEntries = function (entries) {
  77243. for (var index = 0; index < entries.length; index++) {
  77244. var mesh = entries[index];
  77245. this.addEntry(mesh);
  77246. }
  77247. };
  77248. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  77249. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  77250. if (this.blocks) {
  77251. for (var index = 0; index < this.blocks.length; index++) {
  77252. var block = this.blocks[index];
  77253. block.select(frustumPlanes, selection, allowDuplicate);
  77254. }
  77255. return;
  77256. }
  77257. if (allowDuplicate) {
  77258. selection.concat(this.entries);
  77259. }
  77260. else {
  77261. selection.concatWithNoDuplicate(this.entries);
  77262. }
  77263. }
  77264. };
  77265. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  77266. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  77267. if (this.blocks) {
  77268. for (var index = 0; index < this.blocks.length; index++) {
  77269. var block = this.blocks[index];
  77270. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  77271. }
  77272. return;
  77273. }
  77274. if (allowDuplicate) {
  77275. selection.concat(this.entries);
  77276. }
  77277. else {
  77278. selection.concatWithNoDuplicate(this.entries);
  77279. }
  77280. }
  77281. };
  77282. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  77283. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  77284. if (this.blocks) {
  77285. for (var index = 0; index < this.blocks.length; index++) {
  77286. var block = this.blocks[index];
  77287. block.intersectsRay(ray, selection);
  77288. }
  77289. return;
  77290. }
  77291. selection.concatWithNoDuplicate(this.entries);
  77292. }
  77293. };
  77294. OctreeBlock.prototype.createInnerBlocks = function () {
  77295. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  77296. };
  77297. return OctreeBlock;
  77298. }());
  77299. BABYLON.OctreeBlock = OctreeBlock;
  77300. })(BABYLON || (BABYLON = {}));
  77301. //# sourceMappingURL=babylon.octreeBlock.js.map
  77302. var BABYLON;
  77303. (function (BABYLON) {
  77304. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  77305. __extends(VRDistortionCorrectionPostProcess, _super);
  77306. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  77307. var _this = _super.call(this, name, "vrDistortionCorrection", [
  77308. 'LensCenter',
  77309. 'Scale',
  77310. 'ScaleIn',
  77311. 'HmdWarpParam'
  77312. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  77313. _this._isRightEye = isRightEye;
  77314. _this._distortionFactors = vrMetrics.distortionK;
  77315. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  77316. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  77317. _this.adaptScaleToCurrentViewport = true;
  77318. _this.onSizeChangedObservable.add(function () {
  77319. _this.aspectRatio = _this.width * .5 / _this.height;
  77320. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  77321. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  77322. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  77323. });
  77324. _this.onApplyObservable.add(function (effect) {
  77325. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  77326. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  77327. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  77328. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  77329. });
  77330. return _this;
  77331. }
  77332. return VRDistortionCorrectionPostProcess;
  77333. }(BABYLON.PostProcess));
  77334. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  77335. })(BABYLON || (BABYLON = {}));
  77336. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  77337. var BABYLON;
  77338. (function (BABYLON) {
  77339. var AnaglyphPostProcess = /** @class */ (function (_super) {
  77340. __extends(AnaglyphPostProcess, _super);
  77341. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  77342. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  77343. _this._passedProcess = rigCameras[0]._rigPostProcess;
  77344. _this.onApplyObservable.add(function (effect) {
  77345. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  77346. });
  77347. return _this;
  77348. }
  77349. return AnaglyphPostProcess;
  77350. }(BABYLON.PostProcess));
  77351. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  77352. })(BABYLON || (BABYLON = {}));
  77353. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  77354. var BABYLON;
  77355. (function (BABYLON) {
  77356. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  77357. __extends(StereoscopicInterlacePostProcess, _super);
  77358. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  77359. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  77360. _this._passedProcess = rigCameras[0]._rigPostProcess;
  77361. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  77362. _this.onSizeChangedObservable.add(function () {
  77363. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  77364. });
  77365. _this.onApplyObservable.add(function (effect) {
  77366. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  77367. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  77368. });
  77369. return _this;
  77370. }
  77371. return StereoscopicInterlacePostProcess;
  77372. }(BABYLON.PostProcess));
  77373. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  77374. })(BABYLON || (BABYLON = {}));
  77375. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  77376. var BABYLON;
  77377. (function (BABYLON) {
  77378. /**
  77379. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  77380. * Screen rotation is taken into account.
  77381. */
  77382. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  77383. function FreeCameraDeviceOrientationInput() {
  77384. var _this = this;
  77385. this._screenOrientationAngle = 0;
  77386. this._screenQuaternion = new BABYLON.Quaternion();
  77387. this._alpha = 0;
  77388. this._beta = 0;
  77389. this._gamma = 0;
  77390. this._orientationChanged = function () {
  77391. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  77392. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  77393. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  77394. };
  77395. this._deviceOrientation = function (evt) {
  77396. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  77397. _this._beta = evt.beta !== null ? evt.beta : 0;
  77398. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  77399. };
  77400. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  77401. this._orientationChanged();
  77402. }
  77403. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  77404. get: function () {
  77405. return this._camera;
  77406. },
  77407. set: function (camera) {
  77408. this._camera = camera;
  77409. if (this._camera != null && !this._camera.rotationQuaternion) {
  77410. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  77411. }
  77412. },
  77413. enumerable: true,
  77414. configurable: true
  77415. });
  77416. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  77417. window.addEventListener("orientationchange", this._orientationChanged);
  77418. window.addEventListener("deviceorientation", this._deviceOrientation);
  77419. //In certain cases, the attach control is called AFTER orientation was changed,
  77420. //So this is needed.
  77421. this._orientationChanged();
  77422. };
  77423. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  77424. window.removeEventListener("orientationchange", this._orientationChanged);
  77425. window.removeEventListener("deviceorientation", this._deviceOrientation);
  77426. };
  77427. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  77428. //if no device orientation provided, don't update the rotation.
  77429. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  77430. if (!this._alpha)
  77431. return;
  77432. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  77433. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  77434. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  77435. //Mirror on XY Plane
  77436. this._camera.rotationQuaternion.z *= -1;
  77437. this._camera.rotationQuaternion.w *= -1;
  77438. };
  77439. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  77440. return "FreeCameraDeviceOrientationInput";
  77441. };
  77442. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  77443. return "deviceOrientation";
  77444. };
  77445. return FreeCameraDeviceOrientationInput;
  77446. }());
  77447. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  77448. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  77449. })(BABYLON || (BABYLON = {}));
  77450. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  77451. var BABYLON;
  77452. (function (BABYLON) {
  77453. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  77454. function ArcRotateCameraVRDeviceOrientationInput() {
  77455. this.alphaCorrection = 1;
  77456. this.betaCorrection = 1;
  77457. this.gammaCorrection = 1;
  77458. this._alpha = 0;
  77459. this._gamma = 0;
  77460. this._dirty = false;
  77461. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  77462. }
  77463. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  77464. this.camera.attachControl(element, noPreventDefault);
  77465. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  77466. };
  77467. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  77468. if (evt.alpha !== null) {
  77469. this._alpha = +evt.alpha | 0;
  77470. }
  77471. if (evt.gamma !== null) {
  77472. this._gamma = +evt.gamma | 0;
  77473. }
  77474. this._dirty = true;
  77475. };
  77476. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  77477. if (this._dirty) {
  77478. this._dirty = false;
  77479. if (this._gamma < 0) {
  77480. this._gamma = 180 + this._gamma;
  77481. }
  77482. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  77483. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  77484. }
  77485. };
  77486. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  77487. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  77488. };
  77489. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  77490. return "ArcRotateCameraVRDeviceOrientationInput";
  77491. };
  77492. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  77493. return "VRDeviceOrientation";
  77494. };
  77495. return ArcRotateCameraVRDeviceOrientationInput;
  77496. }());
  77497. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  77498. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  77499. })(BABYLON || (BABYLON = {}));
  77500. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  77501. var BABYLON;
  77502. (function (BABYLON) {
  77503. var VRCameraMetrics = /** @class */ (function () {
  77504. function VRCameraMetrics() {
  77505. this.compensateDistortion = true;
  77506. }
  77507. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  77508. get: function () {
  77509. return this.hResolution / (2 * this.vResolution);
  77510. },
  77511. enumerable: true,
  77512. configurable: true
  77513. });
  77514. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  77515. get: function () {
  77516. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  77517. },
  77518. enumerable: true,
  77519. configurable: true
  77520. });
  77521. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  77522. get: function () {
  77523. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  77524. var h = (4 * meters) / this.hScreenSize;
  77525. return BABYLON.Matrix.Translation(h, 0, 0);
  77526. },
  77527. enumerable: true,
  77528. configurable: true
  77529. });
  77530. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  77531. get: function () {
  77532. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  77533. var h = (4 * meters) / this.hScreenSize;
  77534. return BABYLON.Matrix.Translation(-h, 0, 0);
  77535. },
  77536. enumerable: true,
  77537. configurable: true
  77538. });
  77539. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  77540. get: function () {
  77541. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  77542. },
  77543. enumerable: true,
  77544. configurable: true
  77545. });
  77546. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  77547. get: function () {
  77548. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  77549. },
  77550. enumerable: true,
  77551. configurable: true
  77552. });
  77553. VRCameraMetrics.GetDefault = function () {
  77554. var result = new VRCameraMetrics();
  77555. result.hResolution = 1280;
  77556. result.vResolution = 800;
  77557. result.hScreenSize = 0.149759993;
  77558. result.vScreenSize = 0.0935999975;
  77559. result.vScreenCenter = 0.0467999987;
  77560. result.eyeToScreenDistance = 0.0410000011;
  77561. result.lensSeparationDistance = 0.0635000020;
  77562. result.interpupillaryDistance = 0.0640000030;
  77563. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  77564. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  77565. result.postProcessScaleFactor = 1.714605507808412;
  77566. result.lensCenterOffset = 0.151976421;
  77567. return result;
  77568. };
  77569. return VRCameraMetrics;
  77570. }());
  77571. BABYLON.VRCameraMetrics = VRCameraMetrics;
  77572. })(BABYLON || (BABYLON = {}));
  77573. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  77574. var BABYLON;
  77575. (function (BABYLON) {
  77576. /**
  77577. * This represents a WebVR camera.
  77578. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  77579. * @example http://doc.babylonjs.com/how_to/webvr_camera
  77580. */
  77581. var WebVRFreeCamera = /** @class */ (function (_super) {
  77582. __extends(WebVRFreeCamera, _super);
  77583. /**
  77584. * Instantiates a WebVRFreeCamera.
  77585. * @param name The name of the WebVRFreeCamera
  77586. * @param position The starting anchor position for the camera
  77587. * @param scene The scene the camera belongs to
  77588. * @param webVROptions a set of customizable options for the webVRCamera
  77589. */
  77590. function WebVRFreeCamera(name, position, scene, webVROptions) {
  77591. if (webVROptions === void 0) { webVROptions = {}; }
  77592. var _this = _super.call(this, name, position, scene) || this;
  77593. _this.webVROptions = webVROptions;
  77594. /**
  77595. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  77596. */
  77597. _this._vrDevice = null;
  77598. /**
  77599. * The rawPose of the vrDevice.
  77600. */
  77601. _this.rawPose = null;
  77602. _this._specsVersion = "1.1";
  77603. _this._attached = false;
  77604. _this._descendants = [];
  77605. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  77606. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  77607. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  77608. _this._standingMatrix = null;
  77609. /**
  77610. * Represents device position in babylon space.
  77611. */
  77612. _this.devicePosition = BABYLON.Vector3.Zero();
  77613. /**
  77614. * Represents device rotation in babylon space.
  77615. */
  77616. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  77617. /**
  77618. * The scale of the device to be used when translating from device space to babylon space.
  77619. */
  77620. _this.deviceScaleFactor = 1;
  77621. _this._deviceToWorld = BABYLON.Matrix.Identity();
  77622. _this._worldToDevice = BABYLON.Matrix.Identity();
  77623. /**
  77624. * References to the webVR controllers for the vrDevice.
  77625. */
  77626. _this.controllers = [];
  77627. /**
  77628. * Emits an event when a controller is attached.
  77629. */
  77630. _this.onControllersAttachedObservable = new BABYLON.Observable();
  77631. /**
  77632. * Emits an event when a controller's mesh has been loaded;
  77633. */
  77634. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  77635. /**
  77636. * If the rig cameras be used as parent instead of this camera.
  77637. */
  77638. _this.rigParenting = true;
  77639. _this._defaultHeight = undefined;
  77640. _this._workingVector = BABYLON.Vector3.Zero();
  77641. _this._oneVector = BABYLON.Vector3.One();
  77642. _this._workingMatrix = BABYLON.Matrix.Identity();
  77643. _this._cache.position = BABYLON.Vector3.Zero();
  77644. if (webVROptions.defaultHeight) {
  77645. _this._defaultHeight = webVROptions.defaultHeight;
  77646. _this.position.y = _this._defaultHeight;
  77647. }
  77648. _this.minZ = 0.1;
  77649. //legacy support - the compensation boolean was removed.
  77650. if (arguments.length === 5) {
  77651. _this.webVROptions = arguments[4];
  77652. }
  77653. // default webVR options
  77654. if (_this.webVROptions.trackPosition == undefined) {
  77655. _this.webVROptions.trackPosition = true;
  77656. }
  77657. if (_this.webVROptions.controllerMeshes == undefined) {
  77658. _this.webVROptions.controllerMeshes = true;
  77659. }
  77660. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  77661. _this.webVROptions.defaultLightingOnControllers = true;
  77662. }
  77663. _this.rotationQuaternion = new BABYLON.Quaternion();
  77664. if (_this.webVROptions && _this.webVROptions.positionScale) {
  77665. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  77666. }
  77667. //enable VR
  77668. var engine = _this.getEngine();
  77669. _this._onVREnabled = function (success) { if (success) {
  77670. _this.initControllers();
  77671. } };
  77672. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  77673. engine.initWebVR().add(function (event) {
  77674. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  77675. return;
  77676. }
  77677. _this._vrDevice = event.vrDisplay;
  77678. //reset the rig parameters.
  77679. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  77680. if (_this._attached) {
  77681. _this.getEngine().enableVR();
  77682. }
  77683. });
  77684. if (typeof (VRFrameData) !== "undefined")
  77685. _this._frameData = new VRFrameData();
  77686. /**
  77687. * The idea behind the following lines:
  77688. * objects that have the camera as parent should actually have the rig cameras as a parent.
  77689. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  77690. * the second will not show it correctly.
  77691. *
  77692. * To solve this - each object that has the camera as parent will be added to a protected array.
  77693. * When the rig camera renders, it will take this array and set all of those to be its children.
  77694. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  77695. * Amazing!
  77696. */
  77697. scene.onBeforeCameraRenderObservable.add(function (camera) {
  77698. if (camera.parent === _this && _this.rigParenting) {
  77699. _this._descendants = _this.getDescendants(true, function (n) {
  77700. // don't take the cameras or the controllers!
  77701. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  77702. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  77703. return !isController && !isRigCamera;
  77704. });
  77705. _this._descendants.forEach(function (node) {
  77706. node.parent = camera;
  77707. });
  77708. }
  77709. });
  77710. scene.onAfterCameraRenderObservable.add(function (camera) {
  77711. if (camera.parent === _this && _this.rigParenting) {
  77712. _this._descendants.forEach(function (node) {
  77713. node.parent = _this;
  77714. });
  77715. }
  77716. });
  77717. return _this;
  77718. }
  77719. /**
  77720. * Gets the device distance from the ground.
  77721. * @returns the distance from the vrDevice to ground in device space. If standing matrix is not supported for the vrDevice 0 is returned.
  77722. */
  77723. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  77724. if (this._standingMatrix && this._defaultHeight === undefined) {
  77725. // Add standing matrix offset to get real offset from ground in room
  77726. this._standingMatrix.getTranslationToRef(this._workingVector);
  77727. return this._deviceRoomPosition.y + this._workingVector.y;
  77728. }
  77729. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  77730. return this._defaultHeight || 0;
  77731. };
  77732. /**
  77733. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  77734. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  77735. */
  77736. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  77737. var _this = this;
  77738. if (callback === void 0) { callback = function (bool) { }; }
  77739. // Use standing matrix if available
  77740. if (!navigator || !navigator.getVRDisplays) {
  77741. callback(false);
  77742. }
  77743. else {
  77744. navigator.getVRDisplays().then(function (displays) {
  77745. if (!displays || !displays[0] || !displays[0].stageParameters || !displays[0].stageParameters.sittingToStandingTransform) {
  77746. callback(false);
  77747. }
  77748. else {
  77749. _this._standingMatrix = new BABYLON.Matrix();
  77750. BABYLON.Matrix.FromFloat32ArrayToRefScaled(displays[0].stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  77751. if (!_this.getScene().useRightHandedSystem) {
  77752. [2, 6, 8, 9, 14].forEach(function (num) {
  77753. if (_this._standingMatrix) {
  77754. _this._standingMatrix.m[num] *= -1;
  77755. }
  77756. });
  77757. }
  77758. callback(true);
  77759. }
  77760. });
  77761. }
  77762. };
  77763. /**
  77764. * Disposes the camera
  77765. */
  77766. WebVRFreeCamera.prototype.dispose = function () {
  77767. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  77768. _super.prototype.dispose.call(this);
  77769. };
  77770. /**
  77771. * Gets a vrController by name.
  77772. * @param name The name of the controller to retreive
  77773. * @returns the controller matching the name specified or null if not found
  77774. */
  77775. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  77776. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  77777. var gp = _a[_i];
  77778. if (gp.hand === name) {
  77779. return gp;
  77780. }
  77781. }
  77782. return null;
  77783. };
  77784. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  77785. /**
  77786. * The controller corrisponding to the users left hand.
  77787. */
  77788. get: function () {
  77789. if (!this._leftController) {
  77790. this._leftController = this.getControllerByName("left");
  77791. }
  77792. return this._leftController;
  77793. },
  77794. enumerable: true,
  77795. configurable: true
  77796. });
  77797. ;
  77798. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  77799. /**
  77800. * The controller corrisponding to the users right hand.
  77801. */
  77802. get: function () {
  77803. if (!this._rightController) {
  77804. this._rightController = this.getControllerByName("right");
  77805. }
  77806. return this._rightController;
  77807. },
  77808. enumerable: true,
  77809. configurable: true
  77810. });
  77811. ;
  77812. /**
  77813. * Casts a ray forward from the vrCamera's gaze.
  77814. * @param length Length of the ray (default: 100)
  77815. * @returns the ray corrisponding to the gaze
  77816. */
  77817. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  77818. if (length === void 0) { length = 100; }
  77819. if (this.leftCamera) {
  77820. // Use left eye to avoid computation to compute center on every call
  77821. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  77822. }
  77823. else {
  77824. return _super.prototype.getForwardRay.call(this, length);
  77825. }
  77826. };
  77827. /**
  77828. * Updates the camera based on device's frame data
  77829. */
  77830. WebVRFreeCamera.prototype._checkInputs = function () {
  77831. if (this._vrDevice && this._vrDevice.isPresenting) {
  77832. this._vrDevice.getFrameData(this._frameData);
  77833. this.updateFromDevice(this._frameData.pose);
  77834. }
  77835. _super.prototype._checkInputs.call(this);
  77836. };
  77837. /**
  77838. * Updates the poseControlled values based on the input device pose.
  77839. * @param poseData Pose coming from the device
  77840. */
  77841. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  77842. if (poseData && poseData.orientation) {
  77843. this.rawPose = poseData;
  77844. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  77845. if (this.getScene().useRightHandedSystem) {
  77846. this._deviceRoomRotationQuaternion.z *= -1;
  77847. this._deviceRoomRotationQuaternion.w *= -1;
  77848. }
  77849. if (this.webVROptions.trackPosition && this.rawPose.position) {
  77850. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  77851. if (this.getScene().useRightHandedSystem) {
  77852. this._deviceRoomPosition.z *= -1;
  77853. }
  77854. }
  77855. }
  77856. };
  77857. /**
  77858. * WebVR's attach control will start broadcasting frames to the device.
  77859. * Note that in certain browsers (chrome for example) this function must be called
  77860. * within a user-interaction callback. Example:
  77861. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  77862. *
  77863. * @param element html element to attach the vrDevice to
  77864. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  77865. */
  77866. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  77867. _super.prototype.attachControl.call(this, element, noPreventDefault);
  77868. this._attached = true;
  77869. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  77870. if (this._vrDevice) {
  77871. this.getEngine().enableVR();
  77872. }
  77873. };
  77874. /**
  77875. * Detaches the camera from the html element and disables VR
  77876. *
  77877. * @param element html element to detach from
  77878. */
  77879. WebVRFreeCamera.prototype.detachControl = function (element) {
  77880. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  77881. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  77882. _super.prototype.detachControl.call(this, element);
  77883. this._attached = false;
  77884. this.getEngine().disableVR();
  77885. };
  77886. /**
  77887. * @returns the name of this class
  77888. */
  77889. WebVRFreeCamera.prototype.getClassName = function () {
  77890. return "WebVRFreeCamera";
  77891. };
  77892. /**
  77893. * Calls resetPose on the vrDisplay
  77894. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  77895. */
  77896. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  77897. //uses the vrDisplay's "resetPose()".
  77898. //pitch and roll won't be affected.
  77899. this._vrDevice.resetPose();
  77900. };
  77901. /**
  77902. * Updates the rig cameras (left and right eye)
  77903. */
  77904. WebVRFreeCamera.prototype._updateRigCameras = function () {
  77905. var camLeft = this._rigCameras[0];
  77906. var camRight = this._rigCameras[1];
  77907. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  77908. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  77909. camLeft.position.copyFrom(this._deviceRoomPosition);
  77910. camRight.position.copyFrom(this._deviceRoomPosition);
  77911. };
  77912. /**
  77913. * Updates the cached values of the camera
  77914. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  77915. */
  77916. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  77917. var _this = this;
  77918. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  77919. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  77920. if (!this.updateCacheCalled) {
  77921. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  77922. this.updateCacheCalled = true;
  77923. this.update();
  77924. }
  77925. // Set working vector to the device position in room space rotated by the new rotation
  77926. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  77927. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  77928. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  77929. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  77930. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  77931. // Add translation from anchor position
  77932. this._deviceToWorld.getTranslationToRef(this._workingVector);
  77933. this._workingVector.addInPlace(this.position);
  77934. this._workingVector.subtractInPlace(this._cache.position);
  77935. this._deviceToWorld.setTranslation(this._workingVector);
  77936. // Set an inverted matrix to be used when updating the camera
  77937. this._deviceToWorld.invertToRef(this._worldToDevice);
  77938. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  77939. this.controllers.forEach(function (controller) {
  77940. controller._deviceToWorld = _this._deviceToWorld;
  77941. controller.update();
  77942. });
  77943. }
  77944. if (!ignoreParentClass) {
  77945. _super.prototype._updateCache.call(this);
  77946. }
  77947. this.updateCacheCalled = false;
  77948. };
  77949. /**
  77950. * Updates the current device position and rotation in the babylon world
  77951. */
  77952. WebVRFreeCamera.prototype.update = function () {
  77953. // Get current device position in babylon world
  77954. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  77955. // Get current device rotation in babylon world
  77956. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  77957. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  77958. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  77959. _super.prototype.update.call(this);
  77960. };
  77961. /**
  77962. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  77963. * @returns an identity matrix
  77964. */
  77965. WebVRFreeCamera.prototype._getViewMatrix = function () {
  77966. return BABYLON.Matrix.Identity();
  77967. };
  77968. /**
  77969. * This function is called by the two RIG cameras.
  77970. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  77971. */
  77972. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  77973. var _this = this;
  77974. //WebVR 1.1
  77975. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  77976. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  77977. if (!this.getScene().useRightHandedSystem) {
  77978. [2, 6, 8, 9, 14].forEach(function (num) {
  77979. _this._webvrViewMatrix.m[num] *= -1;
  77980. });
  77981. }
  77982. // update the camera rotation matrix
  77983. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  77984. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  77985. // Computing target and final matrix
  77986. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  77987. var parentCamera = this._cameraRigParams["parentCamera"];
  77988. // should the view matrix be updated with scale and position offset?
  77989. if (parentCamera.deviceScaleFactor !== 1) {
  77990. this._webvrViewMatrix.invert();
  77991. // scale the position, if set
  77992. if (parentCamera.deviceScaleFactor) {
  77993. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  77994. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  77995. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  77996. }
  77997. this._webvrViewMatrix.invert();
  77998. }
  77999. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  78000. return this._webvrViewMatrix;
  78001. };
  78002. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  78003. var _this = this;
  78004. var parentCamera = this.parent;
  78005. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  78006. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  78007. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  78008. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  78009. //babylon compatible matrix
  78010. if (!this.getScene().useRightHandedSystem) {
  78011. [8, 9, 10, 11].forEach(function (num) {
  78012. _this._projectionMatrix.m[num] *= -1;
  78013. });
  78014. }
  78015. return this._projectionMatrix;
  78016. };
  78017. /**
  78018. * Initializes the controllers and their meshes
  78019. */
  78020. WebVRFreeCamera.prototype.initControllers = function () {
  78021. var _this = this;
  78022. this.controllers = [];
  78023. var manager = this.getScene().gamepadManager;
  78024. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  78025. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  78026. var webVrController = gamepad;
  78027. if (webVrController.defaultModel) {
  78028. webVrController.defaultModel.setEnabled(false);
  78029. }
  78030. if (webVrController.hand === "right") {
  78031. _this._rightController = null;
  78032. }
  78033. if (webVrController.hand === "left") {
  78034. _this._rightController = null;
  78035. }
  78036. var controllerIndex = _this.controllers.indexOf(webVrController);
  78037. if (controllerIndex !== -1) {
  78038. _this.controllers.splice(controllerIndex, 1);
  78039. }
  78040. }
  78041. });
  78042. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  78043. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  78044. var webVrController_1 = gamepad;
  78045. webVrController_1._deviceToWorld = _this._deviceToWorld;
  78046. if (_this.webVROptions.controllerMeshes) {
  78047. if (webVrController_1.defaultModel) {
  78048. webVrController_1.defaultModel.setEnabled(true);
  78049. }
  78050. else {
  78051. // Load the meshes
  78052. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  78053. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  78054. if (_this.webVROptions.defaultLightingOnControllers) {
  78055. if (!_this._lightOnControllers) {
  78056. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  78057. }
  78058. var activateLightOnSubMeshes_1 = function (mesh, light) {
  78059. var children = mesh.getChildren();
  78060. if (children.length !== 0) {
  78061. children.forEach(function (mesh) {
  78062. light.includedOnlyMeshes.push(mesh);
  78063. activateLightOnSubMeshes_1(mesh, light);
  78064. });
  78065. }
  78066. };
  78067. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  78068. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  78069. }
  78070. });
  78071. }
  78072. }
  78073. webVrController_1.attachToPoseControlledCamera(_this);
  78074. // since this is async - sanity check. Is the controller already stored?
  78075. if (_this.controllers.indexOf(webVrController_1) === -1) {
  78076. //add to the controllers array
  78077. _this.controllers.push(webVrController_1);
  78078. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  78079. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  78080. // So we're overriding setting left & right manually to be sure
  78081. var firstViveWandDetected = false;
  78082. for (var i = 0; i < _this.controllers.length; i++) {
  78083. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  78084. if (!firstViveWandDetected) {
  78085. firstViveWandDetected = true;
  78086. _this.controllers[i].hand = "left";
  78087. }
  78088. else {
  78089. _this.controllers[i].hand = "right";
  78090. }
  78091. }
  78092. }
  78093. //did we find enough controllers? Great! let the developer know.
  78094. if (_this.controllers.length >= 2) {
  78095. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  78096. }
  78097. }
  78098. }
  78099. });
  78100. };
  78101. return WebVRFreeCamera;
  78102. }(BABYLON.FreeCamera));
  78103. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  78104. })(BABYLON || (BABYLON = {}));
  78105. //# sourceMappingURL=babylon.webVRCamera.js.map
  78106. var BABYLON;
  78107. (function (BABYLON) {
  78108. // We're mainly based on the logic defined into the FreeCamera code
  78109. /**
  78110. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  78111. * being tilted forward or back and left or right.
  78112. */
  78113. var DeviceOrientationCamera = /** @class */ (function (_super) {
  78114. __extends(DeviceOrientationCamera, _super);
  78115. /**
  78116. * Creates a new device orientation camera. @see DeviceOrientationCamera
  78117. * @param name The name of the camera
  78118. * @param position The start position camera
  78119. * @param scene The scene the camera belongs to
  78120. */
  78121. function DeviceOrientationCamera(name, position, scene) {
  78122. var _this = _super.call(this, name, position, scene) || this;
  78123. _this._quaternionCache = new BABYLON.Quaternion();
  78124. _this.inputs.addDeviceOrientation();
  78125. return _this;
  78126. }
  78127. /**
  78128. * Gets the current instance class name ("DeviceOrientationCamera").
  78129. * This helps avoiding instanceof at run time.
  78130. * @returns the class name
  78131. */
  78132. DeviceOrientationCamera.prototype.getClassName = function () {
  78133. return "DeviceOrientationCamera";
  78134. };
  78135. /**
  78136. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  78137. */
  78138. DeviceOrientationCamera.prototype._checkInputs = function () {
  78139. _super.prototype._checkInputs.call(this);
  78140. this._quaternionCache.copyFrom(this.rotationQuaternion);
  78141. if (this._initialQuaternion) {
  78142. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  78143. }
  78144. };
  78145. /**
  78146. * Reset the camera to its default orientation on the specified axis only.
  78147. * @param axis The axis to reset
  78148. */
  78149. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  78150. var _this = this;
  78151. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  78152. //can only work if this camera has a rotation quaternion already.
  78153. if (!this.rotationQuaternion)
  78154. return;
  78155. if (!this._initialQuaternion) {
  78156. this._initialQuaternion = new BABYLON.Quaternion();
  78157. }
  78158. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  78159. ['x', 'y', 'z'].forEach(function (axisName) {
  78160. if (!axis[axisName]) {
  78161. _this._initialQuaternion[axisName] = 0;
  78162. }
  78163. else {
  78164. _this._initialQuaternion[axisName] *= -1;
  78165. }
  78166. });
  78167. this._initialQuaternion.normalize();
  78168. //force rotation update
  78169. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  78170. };
  78171. return DeviceOrientationCamera;
  78172. }(BABYLON.FreeCamera));
  78173. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  78174. })(BABYLON || (BABYLON = {}));
  78175. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  78176. var BABYLON;
  78177. (function (BABYLON) {
  78178. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  78179. __extends(VRDeviceOrientationFreeCamera, _super);
  78180. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  78181. if (compensateDistortion === void 0) { compensateDistortion = true; }
  78182. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  78183. var _this = _super.call(this, name, position, scene) || this;
  78184. vrCameraMetrics.compensateDistortion = compensateDistortion;
  78185. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  78186. return _this;
  78187. }
  78188. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  78189. return "VRDeviceOrientationFreeCamera";
  78190. };
  78191. return VRDeviceOrientationFreeCamera;
  78192. }(BABYLON.DeviceOrientationCamera));
  78193. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  78194. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  78195. __extends(VRDeviceOrientationGamepadCamera, _super);
  78196. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  78197. if (compensateDistortion === void 0) { compensateDistortion = true; }
  78198. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  78199. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  78200. _this.inputs.addGamepad();
  78201. return _this;
  78202. }
  78203. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  78204. return "VRDeviceOrientationGamepadCamera";
  78205. };
  78206. return VRDeviceOrientationGamepadCamera;
  78207. }(VRDeviceOrientationFreeCamera));
  78208. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  78209. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  78210. __extends(VRDeviceOrientationArcRotateCamera, _super);
  78211. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  78212. if (compensateDistortion === void 0) { compensateDistortion = true; }
  78213. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  78214. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  78215. vrCameraMetrics.compensateDistortion = compensateDistortion;
  78216. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  78217. _this.inputs.addVRDeviceOrientation();
  78218. return _this;
  78219. }
  78220. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  78221. return "VRDeviceOrientationArcRotateCamera";
  78222. };
  78223. return VRDeviceOrientationArcRotateCamera;
  78224. }(BABYLON.ArcRotateCamera));
  78225. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  78226. })(BABYLON || (BABYLON = {}));
  78227. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  78228. var BABYLON;
  78229. (function (BABYLON) {
  78230. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  78231. __extends(AnaglyphFreeCamera, _super);
  78232. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  78233. var _this = _super.call(this, name, position, scene) || this;
  78234. _this.interaxialDistance = interaxialDistance;
  78235. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  78236. return _this;
  78237. }
  78238. AnaglyphFreeCamera.prototype.getClassName = function () {
  78239. return "AnaglyphFreeCamera";
  78240. };
  78241. return AnaglyphFreeCamera;
  78242. }(BABYLON.FreeCamera));
  78243. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  78244. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  78245. __extends(AnaglyphArcRotateCamera, _super);
  78246. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  78247. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  78248. _this.interaxialDistance = interaxialDistance;
  78249. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  78250. return _this;
  78251. }
  78252. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  78253. return "AnaglyphArcRotateCamera";
  78254. };
  78255. return AnaglyphArcRotateCamera;
  78256. }(BABYLON.ArcRotateCamera));
  78257. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  78258. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  78259. __extends(AnaglyphGamepadCamera, _super);
  78260. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  78261. var _this = _super.call(this, name, position, scene) || this;
  78262. _this.interaxialDistance = interaxialDistance;
  78263. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  78264. return _this;
  78265. }
  78266. AnaglyphGamepadCamera.prototype.getClassName = function () {
  78267. return "AnaglyphGamepadCamera";
  78268. };
  78269. return AnaglyphGamepadCamera;
  78270. }(BABYLON.GamepadCamera));
  78271. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  78272. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  78273. __extends(AnaglyphUniversalCamera, _super);
  78274. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  78275. var _this = _super.call(this, name, position, scene) || this;
  78276. _this.interaxialDistance = interaxialDistance;
  78277. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  78278. return _this;
  78279. }
  78280. AnaglyphUniversalCamera.prototype.getClassName = function () {
  78281. return "AnaglyphUniversalCamera";
  78282. };
  78283. return AnaglyphUniversalCamera;
  78284. }(BABYLON.UniversalCamera));
  78285. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  78286. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  78287. __extends(StereoscopicFreeCamera, _super);
  78288. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  78289. var _this = _super.call(this, name, position, scene) || this;
  78290. _this.interaxialDistance = interaxialDistance;
  78291. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  78292. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  78293. return _this;
  78294. }
  78295. StereoscopicFreeCamera.prototype.getClassName = function () {
  78296. return "StereoscopicFreeCamera";
  78297. };
  78298. return StereoscopicFreeCamera;
  78299. }(BABYLON.FreeCamera));
  78300. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  78301. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  78302. __extends(StereoscopicArcRotateCamera, _super);
  78303. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  78304. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  78305. _this.interaxialDistance = interaxialDistance;
  78306. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  78307. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  78308. return _this;
  78309. }
  78310. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  78311. return "StereoscopicArcRotateCamera";
  78312. };
  78313. return StereoscopicArcRotateCamera;
  78314. }(BABYLON.ArcRotateCamera));
  78315. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  78316. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  78317. __extends(StereoscopicGamepadCamera, _super);
  78318. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  78319. var _this = _super.call(this, name, position, scene) || this;
  78320. _this.interaxialDistance = interaxialDistance;
  78321. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  78322. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  78323. return _this;
  78324. }
  78325. StereoscopicGamepadCamera.prototype.getClassName = function () {
  78326. return "StereoscopicGamepadCamera";
  78327. };
  78328. return StereoscopicGamepadCamera;
  78329. }(BABYLON.GamepadCamera));
  78330. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  78331. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  78332. __extends(StereoscopicUniversalCamera, _super);
  78333. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  78334. var _this = _super.call(this, name, position, scene) || this;
  78335. _this.interaxialDistance = interaxialDistance;
  78336. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  78337. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  78338. return _this;
  78339. }
  78340. StereoscopicUniversalCamera.prototype.getClassName = function () {
  78341. return "StereoscopicUniversalCamera";
  78342. };
  78343. return StereoscopicUniversalCamera;
  78344. }(BABYLON.UniversalCamera));
  78345. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  78346. })(BABYLON || (BABYLON = {}));
  78347. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  78348. var BABYLON;
  78349. (function (BABYLON) {
  78350. /**
  78351. * Helps to quickly add VR support to an existing scene.
  78352. * See http://doc.babylonjs.com/how_to/webvr_helper
  78353. */
  78354. var VRExperienceHelper = /** @class */ (function () {
  78355. /**
  78356. * Instantiates a VRExperienceHelper.
  78357. * Helps to quickly add VR support to an existing scene.
  78358. * @param scene The scene the VRExperienceHelper belongs to.
  78359. * @param webVROptions Options to modify the vr experience helper's behavior.
  78360. */
  78361. function VRExperienceHelper(scene, /** Options to modify the vr experience helper's behavior. */ webVROptions) {
  78362. if (webVROptions === void 0) { webVROptions = {}; }
  78363. var _this = this;
  78364. this.webVROptions = webVROptions;
  78365. // Can the system support WebVR, even if a headset isn't plugged in?
  78366. this._webVRsupported = false;
  78367. // If WebVR is supported, is a headset plugged in and are we ready to present?
  78368. this._webVRready = false;
  78369. // Are we waiting for the requestPresent callback to complete?
  78370. this._webVRrequesting = false;
  78371. // Are we presenting to the headset right now?
  78372. this._webVRpresenting = false;
  78373. // Are we presenting in the fullscreen fallback?
  78374. this._fullscreenVRpresenting = false;
  78375. /**
  78376. * Observable raised when entering VR.
  78377. */
  78378. this.onEnteringVRObservable = new BABYLON.Observable();
  78379. /**
  78380. * Observable raised when exiting VR.
  78381. */
  78382. this.onExitingVRObservable = new BABYLON.Observable();
  78383. /**
  78384. * Observable raised when controller mesh is loaded.
  78385. */
  78386. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  78387. this._useCustomVRButton = false;
  78388. this._teleportationRequested = false;
  78389. this._teleportationEnabledOnLeftController = false;
  78390. this._teleportationEnabledOnRightController = false;
  78391. this._interactionsEnabledOnLeftController = false;
  78392. this._interactionsEnabledOnRightController = false;
  78393. this._leftControllerReady = false;
  78394. this._rightControllerReady = false;
  78395. this._floorMeshesCollection = [];
  78396. this._teleportationAllowed = false;
  78397. this._rotationAllowed = true;
  78398. this._teleportationRequestInitiated = false;
  78399. this._teleportationBackRequestInitiated = false;
  78400. this.teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  78401. this._rotationRightAsked = false;
  78402. this._rotationLeftAsked = false;
  78403. this._isDefaultTeleportationTarget = true;
  78404. this._teleportationFillColor = "#444444";
  78405. this._teleportationBorderColor = "#FFFFFF";
  78406. this._rotationAngle = 0;
  78407. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  78408. this._padSensibilityUp = 0.65;
  78409. this._padSensibilityDown = 0.35;
  78410. /**
  78411. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  78412. */
  78413. this.onNewMeshSelected = new BABYLON.Observable();
  78414. /**
  78415. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  78416. */
  78417. this.onNewMeshPicked = new BABYLON.Observable();
  78418. /**
  78419. * Observable raised before camera teleportation
  78420. */
  78421. this.onBeforeCameraTeleport = new BABYLON.Observable();
  78422. /**
  78423. * Observable raised after camera teleportation
  78424. */
  78425. this.onAfterCameraTeleport = new BABYLON.Observable();
  78426. /**
  78427. * Observable raised when current selected mesh gets unselected
  78428. */
  78429. this.onSelectedMeshUnselected = new BABYLON.Observable();
  78430. /**
  78431. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  78432. */
  78433. this.teleportationEnabled = true;
  78434. this._pointerDownOnMeshAsked = false;
  78435. this._isActionableMesh = false;
  78436. this._teleportationInitialized = false;
  78437. this._interactionsEnabled = false;
  78438. this._interactionsRequested = false;
  78439. this._displayGaze = true;
  78440. this._displayLaserPointer = true;
  78441. this._dpadPressed = true;
  78442. this._onResize = function () {
  78443. _this.moveButtonToBottomRight();
  78444. if (_this._fullscreenVRpresenting && _this._webVRready) {
  78445. _this.exitVR();
  78446. }
  78447. };
  78448. this._onFullscreenChange = function () {
  78449. if (document.fullscreen !== undefined) {
  78450. _this._fullscreenVRpresenting = document.fullscreen;
  78451. }
  78452. else if (document.mozFullScreen !== undefined) {
  78453. _this._fullscreenVRpresenting = document.mozFullScreen;
  78454. }
  78455. else if (document.webkitIsFullScreen !== undefined) {
  78456. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  78457. }
  78458. else if (document.msIsFullScreen !== undefined) {
  78459. _this._fullscreenVRpresenting = document.msIsFullScreen;
  78460. }
  78461. if (!_this._fullscreenVRpresenting && _this._canvas) {
  78462. _this.exitVR();
  78463. if (!_this._useCustomVRButton) {
  78464. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  78465. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  78466. }
  78467. }
  78468. };
  78469. this.beforeRender = function () {
  78470. _this._castRayAndSelectObject();
  78471. };
  78472. this._onNewGamepadConnected = function (gamepad) {
  78473. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  78474. if (gamepad.leftStick) {
  78475. gamepad.onleftstickchanged(function (stickValues) {
  78476. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  78477. // Listening to classic/xbox gamepad only if no VR controller is active
  78478. if ((!_this._leftLaserPointer && !_this._rightLaserPointer) ||
  78479. ((_this._leftLaserPointer && !_this._leftLaserPointer.isVisible) &&
  78480. (_this._rightLaserPointer && !_this._rightLaserPointer.isVisible))) {
  78481. _this._checkTeleportWithRay(stickValues);
  78482. _this._checkTeleportBackwards(stickValues);
  78483. }
  78484. }
  78485. });
  78486. }
  78487. if (gamepad.rightStick) {
  78488. gamepad.onrightstickchanged(function (stickValues) {
  78489. if (_this._teleportationInitialized) {
  78490. _this._checkRotate(stickValues);
  78491. }
  78492. });
  78493. }
  78494. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  78495. gamepad.onbuttondown(function (buttonPressed) {
  78496. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  78497. _this._selectionPointerDown();
  78498. }
  78499. });
  78500. gamepad.onbuttonup(function (buttonPressed) {
  78501. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  78502. _this._selectionPointerUp();
  78503. }
  78504. });
  78505. }
  78506. }
  78507. else {
  78508. var webVRController = gamepad;
  78509. _this._tryEnableInteractionOnController(webVRController);
  78510. }
  78511. };
  78512. // 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
  78513. this._tryEnableInteractionOnController = function (webVRController) {
  78514. if (webVRController.hand === "left") {
  78515. _this._leftControllerReady = true;
  78516. if (_this._interactionsRequested && !_this._interactionsEnabledOnLeftController) {
  78517. _this._enableInteractionOnController(webVRController);
  78518. }
  78519. if (_this._teleportationRequested && !_this._teleportationEnabledOnLeftController) {
  78520. _this._enableTeleportationOnController(webVRController);
  78521. }
  78522. }
  78523. if (webVRController.hand === "right") {
  78524. _this._rightControllerReady = true;
  78525. if (_this._interactionsRequested && !_this._interactionsEnabledOnRightController) {
  78526. _this._enableInteractionOnController(webVRController);
  78527. }
  78528. if (_this._teleportationRequested && !_this._teleportationEnabledOnRightController) {
  78529. _this._enableTeleportationOnController(webVRController);
  78530. }
  78531. }
  78532. };
  78533. this._onNewGamepadDisconnected = function (gamepad) {
  78534. if (gamepad instanceof BABYLON.WebVRController) {
  78535. if (gamepad.hand === "left") {
  78536. _this._interactionsEnabledOnLeftController = false;
  78537. _this._teleportationEnabledOnLeftController = false;
  78538. _this._leftControllerReady = false;
  78539. if (_this._leftLaserPointer) {
  78540. _this._leftLaserPointer.dispose();
  78541. }
  78542. }
  78543. if (gamepad.hand === "right") {
  78544. _this._interactionsEnabledOnRightController = false;
  78545. _this._teleportationEnabledOnRightController = false;
  78546. _this._rightControllerReady = false;
  78547. if (_this._rightLaserPointer) {
  78548. _this._rightLaserPointer.dispose();
  78549. }
  78550. }
  78551. }
  78552. };
  78553. this._workingVector = BABYLON.Vector3.Zero();
  78554. this._workingQuaternion = BABYLON.Quaternion.Identity();
  78555. this._workingMatrix = BABYLON.Matrix.Identity();
  78556. this._scene = scene;
  78557. this._canvas = scene.getEngine().getRenderingCanvas();
  78558. // Parse options
  78559. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  78560. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  78561. }
  78562. if (webVROptions.createDeviceOrientationCamera === undefined) {
  78563. webVROptions.createDeviceOrientationCamera = true;
  78564. }
  78565. if (webVROptions.defaultHeight === undefined) {
  78566. webVROptions.defaultHeight = 1.7;
  78567. }
  78568. if (webVROptions.useCustomVRButton) {
  78569. this._useCustomVRButton = true;
  78570. if (webVROptions.customVRButton) {
  78571. this._btnVR = webVROptions.customVRButton;
  78572. }
  78573. }
  78574. if (webVROptions.rayLength) {
  78575. this._rayLength = webVROptions.rayLength;
  78576. }
  78577. this._defaultHeight = webVROptions.defaultHeight;
  78578. // Set position
  78579. if (this._scene.activeCamera) {
  78580. this._position = this._scene.activeCamera.position.clone();
  78581. }
  78582. else {
  78583. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  78584. }
  78585. // Set non-vr camera
  78586. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  78587. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  78588. // Copy data from existing camera
  78589. if (this._scene.activeCamera) {
  78590. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  78591. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  78592. // Set rotation from previous camera
  78593. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  78594. var targetCamera = this._scene.activeCamera;
  78595. if (targetCamera.rotationQuaternion) {
  78596. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  78597. }
  78598. else {
  78599. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  78600. }
  78601. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  78602. }
  78603. }
  78604. this._scene.activeCamera = this._deviceOrientationCamera;
  78605. if (this._canvas) {
  78606. this._scene.activeCamera.attachControl(this._canvas);
  78607. }
  78608. }
  78609. else {
  78610. this._existingCamera = this._scene.activeCamera;
  78611. }
  78612. // Create VR cameras
  78613. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  78614. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  78615. }
  78616. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  78617. this._webVRCamera.useStandingMatrix();
  78618. // Create default button
  78619. if (!this._useCustomVRButton) {
  78620. this._btnVR = document.createElement("BUTTON");
  78621. this._btnVR.className = "babylonVRicon";
  78622. this._btnVR.id = "babylonVRiconbtn";
  78623. this._btnVR.title = "Click to switch to VR";
  78624. 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) }";
  78625. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  78626. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  78627. // css += ".babylonVRicon.vrdisplaysupported { }";
  78628. // css += ".babylonVRicon.vrdisplayready { }";
  78629. // css += ".babylonVRicon.vrdisplayrequesting { }";
  78630. var style = document.createElement('style');
  78631. style.appendChild(document.createTextNode(css));
  78632. document.getElementsByTagName('head')[0].appendChild(style);
  78633. this.moveButtonToBottomRight();
  78634. }
  78635. // VR button click event
  78636. if (this._btnVR) {
  78637. this._btnVR.addEventListener("click", function () {
  78638. if (!_this.isInVRMode) {
  78639. _this.enterVR();
  78640. }
  78641. else {
  78642. _this.exitVR();
  78643. }
  78644. });
  78645. }
  78646. // Window events
  78647. window.addEventListener("resize", this._onResize);
  78648. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  78649. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  78650. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  78651. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  78652. // Display vr button when headset is connected
  78653. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  78654. this.displayVRButton();
  78655. }
  78656. else {
  78657. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  78658. if (e.vrDisplay) {
  78659. _this.displayVRButton();
  78660. }
  78661. });
  78662. }
  78663. // Exiting VR mode using 'ESC' key on desktop
  78664. this._onKeyDown = function (event) {
  78665. if (event.keyCode === 27 && _this.isInVRMode) {
  78666. _this.exitVR();
  78667. }
  78668. };
  78669. document.addEventListener("keydown", this._onKeyDown);
  78670. // Exiting VR mode double tapping the touch screen
  78671. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  78672. if (_this.isInVRMode) {
  78673. _this.exitVR();
  78674. if (_this._fullscreenVRpresenting) {
  78675. _this._scene.getEngine().switchFullscreen(true);
  78676. }
  78677. }
  78678. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  78679. // Listen for WebVR display changes
  78680. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  78681. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  78682. this._onVRRequestPresentStart = function () {
  78683. _this._webVRrequesting = true;
  78684. _this.updateButtonVisibility();
  78685. };
  78686. this._onVRRequestPresentComplete = function (success) {
  78687. _this._webVRrequesting = false;
  78688. _this.updateButtonVisibility();
  78689. };
  78690. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  78691. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  78692. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  78693. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  78694. scene.onDisposeObservable.add(function () {
  78695. _this.dispose();
  78696. });
  78697. // Gamepad connection events
  78698. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  78699. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  78700. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  78701. this.updateButtonVisibility();
  78702. //create easing functions
  78703. this._circleEase = new BABYLON.CircleEase();
  78704. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  78705. }
  78706. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  78707. /** Return this.onEnteringVRObservable
  78708. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  78709. */
  78710. get: function () {
  78711. return this.onEnteringVRObservable;
  78712. },
  78713. enumerable: true,
  78714. configurable: true
  78715. });
  78716. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  78717. /** Return this.onExitingVRObservable
  78718. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  78719. */
  78720. get: function () {
  78721. return this.onExitingVRObservable;
  78722. },
  78723. enumerable: true,
  78724. configurable: true
  78725. });
  78726. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  78727. /** Return this.onControllerMeshLoadedObservable
  78728. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  78729. */
  78730. get: function () {
  78731. return this.onControllerMeshLoadedObservable;
  78732. },
  78733. enumerable: true,
  78734. configurable: true
  78735. });
  78736. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  78737. /**
  78738. * The mesh used to display where the user is going to teleport.
  78739. */
  78740. get: function () {
  78741. return this._teleportationTarget;
  78742. },
  78743. /**
  78744. * Sets the mesh to be used to display where the user is going to teleport.
  78745. */
  78746. set: function (value) {
  78747. if (value) {
  78748. value.name = "teleportationTarget";
  78749. this._isDefaultTeleportationTarget = false;
  78750. this._teleportationTarget = value;
  78751. }
  78752. },
  78753. enumerable: true,
  78754. configurable: true
  78755. });
  78756. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  78757. /**
  78758. * The mesh used to display where the user is selecting.
  78759. */
  78760. get: function () {
  78761. return this._gazeTracker;
  78762. },
  78763. /**
  78764. * Sets the mesh to be used to display where the user is selecting.
  78765. */
  78766. set: function (value) {
  78767. if (value) {
  78768. this._gazeTracker = value;
  78769. this._gazeTracker.bakeCurrentTransformIntoVertices();
  78770. this._gazeTracker.isPickable = false;
  78771. this._gazeTracker.isVisible = false;
  78772. }
  78773. },
  78774. enumerable: true,
  78775. configurable: true
  78776. });
  78777. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  78778. /**
  78779. * If the ray of the gaze should be displayed.
  78780. */
  78781. get: function () {
  78782. return this._displayGaze;
  78783. },
  78784. /**
  78785. * Sets if the ray of the gaze should be displayed.
  78786. */
  78787. set: function (value) {
  78788. this._displayGaze = value;
  78789. if (!value) {
  78790. this._gazeTracker.isVisible = false;
  78791. }
  78792. },
  78793. enumerable: true,
  78794. configurable: true
  78795. });
  78796. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  78797. /**
  78798. * If the ray of the LaserPointer should be displayed.
  78799. */
  78800. get: function () {
  78801. return this._displayLaserPointer;
  78802. },
  78803. /**
  78804. * Sets if the ray of the LaserPointer should be displayed.
  78805. */
  78806. set: function (value) {
  78807. this._displayLaserPointer = value;
  78808. if (!value) {
  78809. if (this._rightLaserPointer) {
  78810. this._rightLaserPointer.isVisible = false;
  78811. }
  78812. if (this._leftLaserPointer) {
  78813. this._leftLaserPointer.isVisible = false;
  78814. }
  78815. }
  78816. else {
  78817. if (this._rightLaserPointer) {
  78818. this._rightLaserPointer.isVisible = true;
  78819. }
  78820. else if (this._leftLaserPointer) {
  78821. this._leftLaserPointer.isVisible = true;
  78822. }
  78823. }
  78824. },
  78825. enumerable: true,
  78826. configurable: true
  78827. });
  78828. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  78829. /**
  78830. * The deviceOrientationCamera used as the camera when not in VR.
  78831. */
  78832. get: function () {
  78833. return this._deviceOrientationCamera;
  78834. },
  78835. enumerable: true,
  78836. configurable: true
  78837. });
  78838. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  78839. /**
  78840. * Based on the current WebVR support, returns the current VR camera used.
  78841. */
  78842. get: function () {
  78843. if (this._webVRready) {
  78844. return this._webVRCamera;
  78845. }
  78846. else {
  78847. return this._scene.activeCamera;
  78848. }
  78849. },
  78850. enumerable: true,
  78851. configurable: true
  78852. });
  78853. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  78854. /**
  78855. * The webVRCamera which is used when in VR.
  78856. */
  78857. get: function () {
  78858. return this._webVRCamera;
  78859. },
  78860. enumerable: true,
  78861. configurable: true
  78862. });
  78863. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  78864. /**
  78865. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  78866. */
  78867. get: function () {
  78868. return this._vrDeviceOrientationCamera;
  78869. },
  78870. enumerable: true,
  78871. configurable: true
  78872. });
  78873. // Raised when one of the controller has loaded successfully its associated default mesh
  78874. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  78875. this._tryEnableInteractionOnController(webVRController);
  78876. try {
  78877. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  78878. }
  78879. catch (err) {
  78880. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  78881. }
  78882. };
  78883. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  78884. /**
  78885. * Gets a value indicating if we are currently in VR mode.
  78886. */
  78887. get: function () {
  78888. return this._webVRpresenting || this._fullscreenVRpresenting;
  78889. },
  78890. enumerable: true,
  78891. configurable: true
  78892. });
  78893. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  78894. var vrDisplay = this._scene.getEngine().getVRDevice();
  78895. if (vrDisplay) {
  78896. var wasPresenting = this._webVRpresenting;
  78897. // A VR display is connected
  78898. this._webVRpresenting = vrDisplay.isPresenting;
  78899. if (wasPresenting && !this._webVRpresenting)
  78900. this.exitVR();
  78901. }
  78902. else {
  78903. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  78904. }
  78905. this.updateButtonVisibility();
  78906. };
  78907. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  78908. this._webVRsupported = eventArgs.vrSupported;
  78909. this._webVRready = !!eventArgs.vrDisplay;
  78910. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  78911. this.updateButtonVisibility();
  78912. };
  78913. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  78914. if (this._canvas && !this._useCustomVRButton) {
  78915. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  78916. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  78917. }
  78918. };
  78919. VRExperienceHelper.prototype.displayVRButton = function () {
  78920. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  78921. document.body.appendChild(this._btnVR);
  78922. this._btnVRDisplayed = true;
  78923. }
  78924. };
  78925. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  78926. if (!this._btnVR || this._useCustomVRButton) {
  78927. return;
  78928. }
  78929. this._btnVR.className = "babylonVRicon";
  78930. if (this.isInVRMode) {
  78931. this._btnVR.className += " vrdisplaypresenting";
  78932. }
  78933. else {
  78934. if (this._webVRready)
  78935. this._btnVR.className += " vrdisplayready";
  78936. if (this._webVRsupported)
  78937. this._btnVR.className += " vrdisplaysupported";
  78938. if (this._webVRrequesting)
  78939. this._btnVR.className += " vrdisplayrequesting";
  78940. }
  78941. };
  78942. /**
  78943. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  78944. * Otherwise, will use the fullscreen API.
  78945. */
  78946. VRExperienceHelper.prototype.enterVR = function () {
  78947. if (this.onEnteringVRObservable) {
  78948. try {
  78949. this.onEnteringVRObservable.notifyObservers(this);
  78950. }
  78951. catch (err) {
  78952. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  78953. }
  78954. }
  78955. if (this._scene.activeCamera) {
  78956. this._position = this._scene.activeCamera.position.clone();
  78957. // make sure that we return to the last active camera
  78958. this._existingCamera = this._scene.activeCamera;
  78959. }
  78960. if (this._webVRrequesting)
  78961. return;
  78962. // If WebVR is supported and a headset is connected
  78963. if (this._webVRready) {
  78964. if (!this._webVRpresenting) {
  78965. this._webVRCamera.position = this._position;
  78966. this._scene.activeCamera = this._webVRCamera;
  78967. }
  78968. }
  78969. else if (this._vrDeviceOrientationCamera) {
  78970. this._vrDeviceOrientationCamera.position = this._position;
  78971. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  78972. this._scene.getEngine().switchFullscreen(true);
  78973. this.updateButtonVisibility();
  78974. }
  78975. if (this._scene.activeCamera && this._canvas) {
  78976. this._scene.activeCamera.attachControl(this._canvas);
  78977. }
  78978. if (this._interactionsEnabled) {
  78979. this._scene.registerBeforeRender(this.beforeRender);
  78980. }
  78981. };
  78982. /**
  78983. * Attempt to exit VR, or fullscreen.
  78984. */
  78985. VRExperienceHelper.prototype.exitVR = function () {
  78986. if (this.onExitingVRObservable) {
  78987. try {
  78988. this.onExitingVRObservable.notifyObservers(this);
  78989. }
  78990. catch (err) {
  78991. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  78992. }
  78993. }
  78994. if (this._webVRpresenting) {
  78995. this._scene.getEngine().disableVR();
  78996. }
  78997. if (this._scene.activeCamera) {
  78998. this._position = this._scene.activeCamera.position.clone();
  78999. }
  79000. if (this._deviceOrientationCamera) {
  79001. this._deviceOrientationCamera.position = this._position;
  79002. this._scene.activeCamera = this._deviceOrientationCamera;
  79003. if (this._canvas) {
  79004. this._scene.activeCamera.attachControl(this._canvas);
  79005. }
  79006. }
  79007. else if (this._existingCamera) {
  79008. this._existingCamera.position = this._position;
  79009. this._scene.activeCamera = this._existingCamera;
  79010. }
  79011. this.updateButtonVisibility();
  79012. if (this._interactionsEnabled) {
  79013. this._scene.unregisterBeforeRender(this.beforeRender);
  79014. }
  79015. };
  79016. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  79017. /**
  79018. * The position of the vr experience helper.
  79019. */
  79020. get: function () {
  79021. return this._position;
  79022. },
  79023. /**
  79024. * Sets the position of the vr experience helper.
  79025. */
  79026. set: function (value) {
  79027. this._position = value;
  79028. if (this._scene.activeCamera) {
  79029. this._scene.activeCamera.position = value;
  79030. }
  79031. },
  79032. enumerable: true,
  79033. configurable: true
  79034. });
  79035. /**
  79036. * Enables controllers and user interactions suck as selecting and object or clicking on an object.
  79037. */
  79038. VRExperienceHelper.prototype.enableInteractions = function () {
  79039. var _this = this;
  79040. if (!this._interactionsEnabled) {
  79041. this._interactionsRequested = true;
  79042. if (this._leftControllerReady && this._webVRCamera.leftController) {
  79043. this._enableInteractionOnController(this._webVRCamera.leftController);
  79044. }
  79045. if (this._rightControllerReady && this._webVRCamera.rightController) {
  79046. this._enableInteractionOnController(this._webVRCamera.rightController);
  79047. }
  79048. if (!this._gazeTracker) {
  79049. this._createGazeTracker();
  79050. }
  79051. this.raySelectionPredicate = function (mesh) {
  79052. return mesh.isVisible;
  79053. };
  79054. this.meshSelectionPredicate = function (mesh) {
  79055. return true;
  79056. };
  79057. this._raySelectionPredicate = function (mesh) {
  79058. if (_this._isTeleportationFloor(mesh) || (mesh != _this._gazeTracker
  79059. && mesh.name.indexOf("teleportationTarget") === -1
  79060. && mesh.name.indexOf("torusTeleportation") === -1
  79061. && mesh.name.indexOf("laserPointer") === -1)) {
  79062. return _this.raySelectionPredicate(mesh);
  79063. }
  79064. return false;
  79065. };
  79066. this._interactionsEnabled = true;
  79067. }
  79068. };
  79069. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  79070. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  79071. if (this._floorMeshesCollection[i].id === mesh.id) {
  79072. return true;
  79073. }
  79074. }
  79075. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  79076. return true;
  79077. }
  79078. return false;
  79079. };
  79080. /**
  79081. * Adds a floor mesh to be used for teleportation.
  79082. * @param floorMesh the mesh to be used for teleportation.
  79083. */
  79084. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  79085. if (!this._floorMeshesCollection) {
  79086. return;
  79087. }
  79088. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  79089. return;
  79090. }
  79091. this._floorMeshesCollection.push(floorMesh);
  79092. };
  79093. /**
  79094. * Removes a floor mesh from being used for teleportation.
  79095. * @param floorMesh the mesh to be removed.
  79096. */
  79097. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  79098. if (!this._floorMeshesCollection) {
  79099. return;
  79100. }
  79101. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  79102. if (meshIndex !== -1) {
  79103. this._floorMeshesCollection.splice(meshIndex, 1);
  79104. }
  79105. };
  79106. /**
  79107. * Enables interactions and teleportation using the VR controllers and gaze.
  79108. * @param vrTeleportationOptions options to modify teleportation behavior.
  79109. */
  79110. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  79111. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  79112. if (!this._teleportationInitialized) {
  79113. this._teleportationRequested = true;
  79114. this.enableInteractions();
  79115. if (vrTeleportationOptions.floorMeshName) {
  79116. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  79117. }
  79118. if (vrTeleportationOptions.floorMeshes) {
  79119. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  79120. }
  79121. if (this._leftControllerReady && this._webVRCamera.leftController) {
  79122. this._enableTeleportationOnController(this._webVRCamera.leftController);
  79123. }
  79124. if (this._rightControllerReady && this._webVRCamera.rightController) {
  79125. this._enableTeleportationOnController(this._webVRCamera.rightController);
  79126. }
  79127. // Creates an image processing post process for the vignette not relying
  79128. // on the main scene configuration for image processing to reduce setup and spaces
  79129. // (gamma/linear) conflicts.
  79130. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  79131. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  79132. imageProcessingConfiguration.vignetteEnabled = true;
  79133. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  79134. this._webVRCamera.detachPostProcess(this._postProcessMove);
  79135. this._passProcessMove = new BABYLON.PassPostProcess("pass", 1.0, this._webVRCamera);
  79136. this._teleportationInitialized = true;
  79137. if (this._isDefaultTeleportationTarget) {
  79138. this._createTeleportationCircles();
  79139. }
  79140. }
  79141. };
  79142. VRExperienceHelper.prototype._enableInteractionOnController = function (webVRController) {
  79143. var _this = this;
  79144. var controllerMesh = webVRController.mesh;
  79145. if (controllerMesh) {
  79146. var makeNotPick = function (root) {
  79147. root.name += " laserPointer";
  79148. root.getChildMeshes().forEach(function (c) {
  79149. makeNotPick(c);
  79150. });
  79151. };
  79152. makeNotPick(controllerMesh);
  79153. var childMeshes = controllerMesh.getChildMeshes();
  79154. for (var i = 0; i < childMeshes.length; i++) {
  79155. if (childMeshes[i].name && childMeshes[i].name.indexOf("POINTING_POSE") >= 0) {
  79156. controllerMesh = childMeshes[i];
  79157. break;
  79158. }
  79159. }
  79160. var laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, this._scene, false);
  79161. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", this._scene);
  79162. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  79163. laserPointerMaterial.alpha = 0.6;
  79164. laserPointer.material = laserPointerMaterial;
  79165. laserPointer.rotation.x = Math.PI / 2;
  79166. laserPointer.parent = controllerMesh;
  79167. laserPointer.position.z = -0.5;
  79168. laserPointer.isVisible = false;
  79169. if (webVRController.hand === "left") {
  79170. this._leftLaserPointer = laserPointer;
  79171. this._interactionsEnabledOnLeftController = true;
  79172. if (!this._rightLaserPointer) {
  79173. this._leftLaserPointer.isVisible = true;
  79174. }
  79175. }
  79176. else {
  79177. this._rightLaserPointer = laserPointer;
  79178. this._interactionsEnabledOnRightController = true;
  79179. if (!this._leftLaserPointer) {
  79180. this._rightLaserPointer.isVisible = true;
  79181. }
  79182. }
  79183. webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  79184. // Enabling / disabling laserPointer
  79185. if (_this._displayLaserPointer && stateObject.value === 1) {
  79186. laserPointer.isVisible = !laserPointer.isVisible;
  79187. // Laser pointer can only be active on left or right, not both at the same time
  79188. if (webVRController.hand === "left" && _this._rightLaserPointer) {
  79189. _this._rightLaserPointer.isVisible = false;
  79190. }
  79191. else if (_this._leftLaserPointer) {
  79192. _this._leftLaserPointer.isVisible = false;
  79193. }
  79194. }
  79195. });
  79196. webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  79197. if (!_this._pointerDownOnMeshAsked) {
  79198. if (stateObject.value > _this._padSensibilityUp) {
  79199. _this._selectionPointerDown();
  79200. }
  79201. }
  79202. else if (stateObject.value < _this._padSensibilityDown) {
  79203. _this._selectionPointerUp();
  79204. }
  79205. });
  79206. }
  79207. };
  79208. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, webVRController) {
  79209. if (webVRController === void 0) { webVRController = null; }
  79210. if (!this._teleportationRequestInitiated) {
  79211. if (stateObject.y < -this._padSensibilityUp && this._dpadPressed) {
  79212. if (webVRController) {
  79213. // If laser pointer wasn't enabled yet
  79214. if (this._displayLaserPointer && webVRController.hand === "left" && this._leftLaserPointer) {
  79215. this._leftLaserPointer.isVisible = true;
  79216. if (this._rightLaserPointer) {
  79217. this._rightLaserPointer.isVisible = false;
  79218. }
  79219. }
  79220. else if (this._displayLaserPointer && this._rightLaserPointer) {
  79221. this._rightLaserPointer.isVisible = true;
  79222. if (this._leftLaserPointer) {
  79223. this._leftLaserPointer.isVisible = false;
  79224. }
  79225. }
  79226. }
  79227. this._teleportationRequestInitiated = true;
  79228. }
  79229. }
  79230. else {
  79231. // Listening to the proper controller values changes to confirm teleportation
  79232. if (webVRController == null
  79233. || (webVRController.hand === "left" && this._leftLaserPointer && this._leftLaserPointer.isVisible)
  79234. || (webVRController.hand === "right" && this._rightLaserPointer && this._rightLaserPointer.isVisible)) {
  79235. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  79236. if (this._teleportationAllowed) {
  79237. this._teleportationAllowed = false;
  79238. this._teleportCamera();
  79239. }
  79240. this._teleportationRequestInitiated = false;
  79241. }
  79242. }
  79243. }
  79244. };
  79245. VRExperienceHelper.prototype._selectionPointerDown = function () {
  79246. this._pointerDownOnMeshAsked = true;
  79247. if (this._currentMeshSelected && this._currentHit) {
  79248. this._scene.simulatePointerDown(this._currentHit);
  79249. }
  79250. };
  79251. VRExperienceHelper.prototype._selectionPointerUp = function () {
  79252. if (this._currentMeshSelected && this._currentHit) {
  79253. this._scene.simulatePointerUp(this._currentHit);
  79254. }
  79255. this._pointerDownOnMeshAsked = false;
  79256. };
  79257. VRExperienceHelper.prototype._checkRotate = function (stateObject) {
  79258. // Only rotate when user is not currently selecting a teleportation location
  79259. if (this._teleportationRequestInitiated) {
  79260. return;
  79261. }
  79262. if (!this._rotationLeftAsked) {
  79263. if (stateObject.x < -this._padSensibilityUp && this._dpadPressed) {
  79264. this._rotationLeftAsked = true;
  79265. if (this._rotationAllowed) {
  79266. this._rotateCamera(false);
  79267. }
  79268. }
  79269. }
  79270. else {
  79271. if (stateObject.x > -this._padSensibilityDown) {
  79272. this._rotationLeftAsked = false;
  79273. }
  79274. }
  79275. if (!this._rotationRightAsked) {
  79276. if (stateObject.x > this._padSensibilityUp && this._dpadPressed) {
  79277. this._rotationRightAsked = true;
  79278. if (this._rotationAllowed) {
  79279. this._rotateCamera(true);
  79280. }
  79281. }
  79282. }
  79283. else {
  79284. if (stateObject.x < this._padSensibilityDown) {
  79285. this._rotationRightAsked = false;
  79286. }
  79287. }
  79288. };
  79289. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject) {
  79290. // Only teleport backwards when user is not currently selecting a teleportation location
  79291. if (this._teleportationRequestInitiated) {
  79292. return;
  79293. }
  79294. // Teleport backwards
  79295. if (stateObject.y > this._padSensibilityUp && this._dpadPressed) {
  79296. if (!this._teleportationBackRequestInitiated) {
  79297. if (!this.currentVRCamera) {
  79298. return;
  79299. }
  79300. // Get rotation and position of the current camera
  79301. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  79302. var position = this.currentVRCamera.position;
  79303. // If the camera has device position, use that instead
  79304. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  79305. rotation = this.currentVRCamera.deviceRotationQuaternion;
  79306. position = this.currentVRCamera.devicePosition;
  79307. }
  79308. // Get matrix with only the y rotation of the device rotation
  79309. rotation.toEulerAnglesToRef(this._workingVector);
  79310. this._workingVector.z = 0;
  79311. this._workingVector.x = 0;
  79312. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  79313. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  79314. // Rotate backwards ray by device rotation to cast at the ground behind the user
  79315. BABYLON.Vector3.TransformCoordinatesToRef(this.teleportBackwardsVector, this._workingMatrix, this._workingVector);
  79316. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  79317. var ray = new BABYLON.Ray(position, this._workingVector);
  79318. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  79319. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  79320. this._teleportCamera(hit.pickedPoint);
  79321. }
  79322. this._teleportationBackRequestInitiated = true;
  79323. }
  79324. }
  79325. else {
  79326. this._teleportationBackRequestInitiated = false;
  79327. }
  79328. };
  79329. VRExperienceHelper.prototype._enableTeleportationOnController = function (webVRController) {
  79330. var _this = this;
  79331. var controllerMesh = webVRController.mesh;
  79332. if (controllerMesh) {
  79333. if (webVRController.hand === "left") {
  79334. if (!this._interactionsEnabledOnLeftController) {
  79335. this._enableInteractionOnController(webVRController);
  79336. }
  79337. this._teleportationEnabledOnLeftController = true;
  79338. }
  79339. else {
  79340. if (!this._interactionsEnabledOnRightController) {
  79341. this._enableInteractionOnController(webVRController);
  79342. }
  79343. this._teleportationEnabledOnRightController = true;
  79344. }
  79345. if (webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  79346. this._dpadPressed = false;
  79347. webVRController.onPadStateChangedObservable.add(function (stateObject) {
  79348. _this._dpadPressed = stateObject.pressed;
  79349. if (!_this._dpadPressed) {
  79350. _this._rotationLeftAsked = false;
  79351. _this._rotationRightAsked = false;
  79352. _this._teleportationBackRequestInitiated = false;
  79353. }
  79354. });
  79355. }
  79356. webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  79357. if (_this.teleportationEnabled) {
  79358. _this._checkTeleportBackwards(stateObject);
  79359. _this._checkTeleportWithRay(stateObject, webVRController);
  79360. }
  79361. _this._checkRotate(stateObject);
  79362. });
  79363. }
  79364. };
  79365. // Gaze support used to point to teleport or to interact with an object
  79366. VRExperienceHelper.prototype._createGazeTracker = function () {
  79367. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, this._scene, false);
  79368. this._gazeTracker.bakeCurrentTransformIntoVertices();
  79369. this._gazeTracker.isPickable = false;
  79370. this._gazeTracker.isVisible = false;
  79371. var targetMat = new BABYLON.StandardMaterial("targetMat", this._scene);
  79372. targetMat.specularColor = BABYLON.Color3.Black();
  79373. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  79374. targetMat.backFaceCulling = false;
  79375. this._gazeTracker.material = targetMat;
  79376. };
  79377. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  79378. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  79379. this._teleportationTarget.isPickable = false;
  79380. var length = 512;
  79381. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  79382. dynamicTexture.hasAlpha = true;
  79383. var context = dynamicTexture.getContext();
  79384. var centerX = length / 2;
  79385. var centerY = length / 2;
  79386. var radius = 200;
  79387. context.beginPath();
  79388. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  79389. context.fillStyle = this._teleportationFillColor;
  79390. context.fill();
  79391. context.lineWidth = 10;
  79392. context.strokeStyle = this._teleportationBorderColor;
  79393. context.stroke();
  79394. context.closePath();
  79395. dynamicTexture.update();
  79396. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  79397. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  79398. this._teleportationTarget.material = teleportationCircleMaterial;
  79399. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  79400. torus.isPickable = false;
  79401. torus.parent = this._teleportationTarget;
  79402. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  79403. var keys = [];
  79404. keys.push({
  79405. frame: 0,
  79406. value: 0
  79407. });
  79408. keys.push({
  79409. frame: 30,
  79410. value: 0.4
  79411. });
  79412. keys.push({
  79413. frame: 60,
  79414. value: 0
  79415. });
  79416. animationInnerCircle.setKeys(keys);
  79417. var easingFunction = new BABYLON.SineEase();
  79418. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  79419. animationInnerCircle.setEasingFunction(easingFunction);
  79420. torus.animations = [];
  79421. torus.animations.push(animationInnerCircle);
  79422. this._scene.beginAnimation(torus, 0, 60, true);
  79423. this._hideTeleportationTarget();
  79424. };
  79425. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  79426. if (this._teleportationInitialized) {
  79427. this._teleportationTarget.isVisible = true;
  79428. if (this._isDefaultTeleportationTarget) {
  79429. this._teleportationTarget.getChildren()[0].isVisible = true;
  79430. }
  79431. }
  79432. };
  79433. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  79434. if (this._teleportationInitialized) {
  79435. this._teleportationTarget.isVisible = false;
  79436. if (this._isDefaultTeleportationTarget) {
  79437. this._teleportationTarget.getChildren()[0].isVisible = false;
  79438. }
  79439. }
  79440. };
  79441. VRExperienceHelper.prototype._rotateCamera = function (right) {
  79442. var _this = this;
  79443. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  79444. return;
  79445. }
  79446. if (right) {
  79447. this._rotationAngle++;
  79448. }
  79449. else {
  79450. this._rotationAngle--;
  79451. }
  79452. this.currentVRCamera.animations = [];
  79453. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  79454. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  79455. var animationRotationKeys = [];
  79456. animationRotationKeys.push({
  79457. frame: 0,
  79458. value: this.currentVRCamera.rotationQuaternion
  79459. });
  79460. animationRotationKeys.push({
  79461. frame: 6,
  79462. value: target
  79463. });
  79464. animationRotation.setKeys(animationRotationKeys);
  79465. animationRotation.setEasingFunction(this._circleEase);
  79466. this.currentVRCamera.animations.push(animationRotation);
  79467. this._postProcessMove.animations = [];
  79468. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  79469. var vignetteWeightKeys = [];
  79470. vignetteWeightKeys.push({
  79471. frame: 0,
  79472. value: 0
  79473. });
  79474. vignetteWeightKeys.push({
  79475. frame: 3,
  79476. value: 4
  79477. });
  79478. vignetteWeightKeys.push({
  79479. frame: 6,
  79480. value: 0
  79481. });
  79482. animationPP.setKeys(vignetteWeightKeys);
  79483. animationPP.setEasingFunction(this._circleEase);
  79484. this._postProcessMove.animations.push(animationPP);
  79485. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  79486. var vignetteStretchKeys = [];
  79487. vignetteStretchKeys.push({
  79488. frame: 0,
  79489. value: 0
  79490. });
  79491. vignetteStretchKeys.push({
  79492. frame: 3,
  79493. value: 10
  79494. });
  79495. vignetteStretchKeys.push({
  79496. frame: 6,
  79497. value: 0
  79498. });
  79499. animationPP2.setKeys(vignetteStretchKeys);
  79500. animationPP2.setEasingFunction(this._circleEase);
  79501. this._postProcessMove.animations.push(animationPP2);
  79502. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  79503. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  79504. this._webVRCamera.attachPostProcess(this._postProcessMove);
  79505. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  79506. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  79507. });
  79508. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  79509. };
  79510. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit) {
  79511. if (hit.pickedPoint) {
  79512. this._teleportationAllowed = true;
  79513. if (this._teleportationRequestInitiated) {
  79514. this._displayTeleportationTarget();
  79515. }
  79516. else {
  79517. this._hideTeleportationTarget();
  79518. }
  79519. this._haloCenter.copyFrom(hit.pickedPoint);
  79520. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  79521. var pickNormal = hit.getNormal(true, false);
  79522. if (pickNormal) {
  79523. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  79524. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  79525. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  79526. }
  79527. this._teleportationTarget.position.y += 0.1;
  79528. }
  79529. };
  79530. VRExperienceHelper.prototype._teleportCamera = function (location) {
  79531. var _this = this;
  79532. if (location === void 0) { location = null; }
  79533. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  79534. return;
  79535. }
  79536. if (!location) {
  79537. location = this._haloCenter;
  79538. }
  79539. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  79540. // offset of the headset from the anchor.
  79541. if (this.webVRCamera.leftCamera) {
  79542. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  79543. this._workingVector.subtractInPlace(this.webVRCamera.position);
  79544. location.subtractToRef(this._workingVector, this._workingVector);
  79545. }
  79546. else {
  79547. this._workingVector.copyFrom(location);
  79548. }
  79549. // Add height to account for user's height offset
  79550. if (this.isInVRMode) {
  79551. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround();
  79552. }
  79553. else {
  79554. this._workingVector.y += this._defaultHeight;
  79555. }
  79556. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  79557. // Create animation from the camera's position to the new location
  79558. this.currentVRCamera.animations = [];
  79559. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  79560. var animationCameraTeleportationKeys = [{
  79561. frame: 0,
  79562. value: this.currentVRCamera.position
  79563. },
  79564. {
  79565. frame: 11,
  79566. value: this._workingVector
  79567. }
  79568. ];
  79569. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  79570. animationCameraTeleportation.setEasingFunction(this._circleEase);
  79571. this.currentVRCamera.animations.push(animationCameraTeleportation);
  79572. this._postProcessMove.animations = [];
  79573. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  79574. var vignetteWeightKeys = [];
  79575. vignetteWeightKeys.push({
  79576. frame: 0,
  79577. value: 0
  79578. });
  79579. vignetteWeightKeys.push({
  79580. frame: 5,
  79581. value: 8
  79582. });
  79583. vignetteWeightKeys.push({
  79584. frame: 11,
  79585. value: 0
  79586. });
  79587. animationPP.setKeys(vignetteWeightKeys);
  79588. this._postProcessMove.animations.push(animationPP);
  79589. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  79590. var vignetteStretchKeys = [];
  79591. vignetteStretchKeys.push({
  79592. frame: 0,
  79593. value: 0
  79594. });
  79595. vignetteStretchKeys.push({
  79596. frame: 5,
  79597. value: 10
  79598. });
  79599. vignetteStretchKeys.push({
  79600. frame: 11,
  79601. value: 0
  79602. });
  79603. animationPP2.setKeys(vignetteStretchKeys);
  79604. this._postProcessMove.animations.push(animationPP2);
  79605. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  79606. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  79607. this._webVRCamera.attachPostProcess(this._postProcessMove);
  79608. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  79609. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  79610. });
  79611. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  79612. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  79613. });
  79614. };
  79615. VRExperienceHelper.prototype._castRayAndSelectObject = function () {
  79616. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  79617. return;
  79618. }
  79619. var ray;
  79620. if (this._leftLaserPointer && this._leftLaserPointer.isVisible && this.currentVRCamera.leftController) {
  79621. ray = this.currentVRCamera.leftController.getForwardRay(this._rayLength);
  79622. }
  79623. else if (this._rightLaserPointer && this._rightLaserPointer.isVisible && this.currentVRCamera.rightController) {
  79624. ray = this.currentVRCamera.rightController.getForwardRay(this._rayLength);
  79625. }
  79626. else {
  79627. ray = this.currentVRCamera.getForwardRay(this._rayLength);
  79628. }
  79629. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  79630. // Moving the gazeTracker on the mesh face targetted
  79631. if (hit && hit.pickedPoint) {
  79632. if (this._displayGaze) {
  79633. var multiplier = 1;
  79634. this._gazeTracker.isVisible = true;
  79635. if (this._isActionableMesh) {
  79636. multiplier = 3;
  79637. }
  79638. this._gazeTracker.scaling.x = hit.distance * multiplier;
  79639. this._gazeTracker.scaling.y = hit.distance * multiplier;
  79640. this._gazeTracker.scaling.z = hit.distance * multiplier;
  79641. var pickNormal = hit.getNormal();
  79642. // To avoid z-fighting
  79643. var deltaFighting = 0.002;
  79644. if (pickNormal) {
  79645. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  79646. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  79647. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._gazeTracker.rotation);
  79648. }
  79649. this._gazeTracker.position.copyFrom(hit.pickedPoint);
  79650. if (this._gazeTracker.position.x < 0) {
  79651. this._gazeTracker.position.x += deltaFighting;
  79652. }
  79653. else {
  79654. this._gazeTracker.position.x -= deltaFighting;
  79655. }
  79656. if (this._gazeTracker.position.y < 0) {
  79657. this._gazeTracker.position.y += deltaFighting;
  79658. }
  79659. else {
  79660. this._gazeTracker.position.y -= deltaFighting;
  79661. }
  79662. if (this._gazeTracker.position.z < 0) {
  79663. this._gazeTracker.position.z += deltaFighting;
  79664. }
  79665. else {
  79666. this._gazeTracker.position.z -= deltaFighting;
  79667. }
  79668. }
  79669. // Changing the size of the laser pointer based on the distance from the targetted point
  79670. if (this._rightLaserPointer && this._rightLaserPointer.isVisible) {
  79671. this._rightLaserPointer.scaling.y = hit.distance;
  79672. this._rightLaserPointer.position.z = -hit.distance / 2;
  79673. }
  79674. if (this._leftLaserPointer && this._leftLaserPointer.isVisible) {
  79675. this._leftLaserPointer.scaling.y = hit.distance;
  79676. this._leftLaserPointer.position.z = -hit.distance / 2;
  79677. }
  79678. }
  79679. else {
  79680. this._gazeTracker.isVisible = false;
  79681. }
  79682. if (hit && hit.pickedMesh) {
  79683. this._currentHit = hit;
  79684. if (this._pointerDownOnMeshAsked) {
  79685. this._scene.simulatePointerMove(this._currentHit);
  79686. }
  79687. // The object selected is the floor, we're in a teleportation scenario
  79688. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  79689. // Moving the teleportation area to this targetted point
  79690. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  79691. if (this._currentMeshSelected && !this._isTeleportationFloor(this._currentMeshSelected)) {
  79692. this._notifySelectedMeshUnselected();
  79693. }
  79694. this._currentMeshSelected = null;
  79695. this._moveTeleportationSelectorTo(hit);
  79696. return;
  79697. }
  79698. // If not, we're in a selection scenario
  79699. this._hideTeleportationTarget();
  79700. this._teleportationAllowed = false;
  79701. if (hit.pickedMesh !== this._currentMeshSelected) {
  79702. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  79703. this.onNewMeshPicked.notifyObservers(hit);
  79704. this._currentMeshSelected = hit.pickedMesh;
  79705. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  79706. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  79707. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  79708. this._isActionableMesh = true;
  79709. }
  79710. else {
  79711. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  79712. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  79713. this._isActionableMesh = false;
  79714. }
  79715. try {
  79716. this.onNewMeshSelected.notifyObservers(this._currentMeshSelected);
  79717. }
  79718. catch (err) {
  79719. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  79720. }
  79721. }
  79722. else {
  79723. this._notifySelectedMeshUnselected();
  79724. this._currentMeshSelected = null;
  79725. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  79726. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  79727. }
  79728. }
  79729. }
  79730. else {
  79731. this._currentHit = null;
  79732. this._notifySelectedMeshUnselected();
  79733. this._currentMeshSelected = null;
  79734. this._teleportationAllowed = false;
  79735. this._hideTeleportationTarget();
  79736. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  79737. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  79738. }
  79739. };
  79740. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function () {
  79741. if (this._currentMeshSelected) {
  79742. this.onSelectedMeshUnselected.notifyObservers(this._currentMeshSelected);
  79743. }
  79744. };
  79745. /**
  79746. * Sets the color of the laser ray from the vr controllers.
  79747. * @param color new color for the ray.
  79748. */
  79749. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  79750. if (this._leftLaserPointer && this._leftLaserPointer.material) {
  79751. this._leftLaserPointer.material.emissiveColor = color;
  79752. }
  79753. if (this._rightLaserPointer && this._rightLaserPointer.material) {
  79754. this._rightLaserPointer.material.emissiveColor = color;
  79755. }
  79756. };
  79757. /**
  79758. * Sets the color of the ray from the vr headsets gaze.
  79759. * @param color new color for the ray.
  79760. */
  79761. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  79762. if (this._gazeTracker.material) {
  79763. this._gazeTracker.material.emissiveColor = color;
  79764. }
  79765. };
  79766. /**
  79767. * Exits VR and disposes of the vr experience helper
  79768. */
  79769. VRExperienceHelper.prototype.dispose = function () {
  79770. if (this.isInVRMode) {
  79771. this.exitVR();
  79772. }
  79773. if (this._passProcessMove) {
  79774. this._passProcessMove.dispose();
  79775. }
  79776. if (this._postProcessMove) {
  79777. this._postProcessMove.dispose();
  79778. }
  79779. if (this._webVRCamera) {
  79780. this._webVRCamera.dispose();
  79781. }
  79782. if (this._vrDeviceOrientationCamera) {
  79783. this._vrDeviceOrientationCamera.dispose();
  79784. }
  79785. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  79786. document.body.removeChild(this._btnVR);
  79787. }
  79788. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  79789. this._deviceOrientationCamera.dispose();
  79790. }
  79791. if (this._gazeTracker) {
  79792. this._gazeTracker.dispose();
  79793. }
  79794. if (this._teleportationTarget) {
  79795. this._teleportationTarget.dispose();
  79796. }
  79797. this._floorMeshesCollection = [];
  79798. document.removeEventListener("keydown", this._onKeyDown);
  79799. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  79800. window.removeEventListener("resize", this._onResize);
  79801. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  79802. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  79803. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  79804. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  79805. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  79806. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  79807. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  79808. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  79809. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  79810. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  79811. this._scene.unregisterBeforeRender(this.beforeRender);
  79812. };
  79813. /**
  79814. * Gets the name of the VRExperienceHelper class
  79815. * @returns "VRExperienceHelper"
  79816. */
  79817. VRExperienceHelper.prototype.getClassName = function () {
  79818. return "VRExperienceHelper";
  79819. };
  79820. return VRExperienceHelper;
  79821. }());
  79822. BABYLON.VRExperienceHelper = VRExperienceHelper;
  79823. })(BABYLON || (BABYLON = {}));
  79824. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  79825. // Mainly based on these 2 articles :
  79826. // 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
  79827. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  79828. var BABYLON;
  79829. (function (BABYLON) {
  79830. var JoystickAxis;
  79831. (function (JoystickAxis) {
  79832. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  79833. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  79834. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  79835. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  79836. var VirtualJoystick = /** @class */ (function () {
  79837. function VirtualJoystick(leftJoystick) {
  79838. var _this = this;
  79839. if (leftJoystick) {
  79840. this._leftJoystick = true;
  79841. }
  79842. else {
  79843. this._leftJoystick = false;
  79844. }
  79845. VirtualJoystick._globalJoystickIndex++;
  79846. // By default left & right arrow keys are moving the X
  79847. // and up & down keys are moving the Y
  79848. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  79849. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  79850. this.reverseLeftRight = false;
  79851. this.reverseUpDown = false;
  79852. // collections of pointers
  79853. this._touches = new BABYLON.StringDictionary();
  79854. this.deltaPosition = BABYLON.Vector3.Zero();
  79855. this._joystickSensibility = 25;
  79856. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  79857. this._onResize = function (evt) {
  79858. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  79859. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  79860. if (VirtualJoystick.vjCanvas) {
  79861. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  79862. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  79863. }
  79864. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  79865. };
  79866. // injecting a canvas element on top of the canvas 3D game
  79867. if (!VirtualJoystick.vjCanvas) {
  79868. window.addEventListener("resize", this._onResize, false);
  79869. VirtualJoystick.vjCanvas = document.createElement("canvas");
  79870. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  79871. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  79872. VirtualJoystick.vjCanvas.width = window.innerWidth;
  79873. VirtualJoystick.vjCanvas.height = window.innerHeight;
  79874. VirtualJoystick.vjCanvas.style.width = "100%";
  79875. VirtualJoystick.vjCanvas.style.height = "100%";
  79876. VirtualJoystick.vjCanvas.style.position = "absolute";
  79877. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  79878. VirtualJoystick.vjCanvas.style.top = "0px";
  79879. VirtualJoystick.vjCanvas.style.left = "0px";
  79880. VirtualJoystick.vjCanvas.style.zIndex = "5";
  79881. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  79882. // Support for jQuery PEP polyfill
  79883. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  79884. var context = VirtualJoystick.vjCanvas.getContext('2d');
  79885. if (!context) {
  79886. throw new Error("Unable to create canvas for virtual joystick");
  79887. }
  79888. VirtualJoystick.vjCanvasContext = context;
  79889. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  79890. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  79891. document.body.appendChild(VirtualJoystick.vjCanvas);
  79892. }
  79893. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  79894. this.pressed = false;
  79895. // default joystick color
  79896. this._joystickColor = "cyan";
  79897. this._joystickPointerID = -1;
  79898. // current joystick position
  79899. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  79900. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  79901. // origin joystick position
  79902. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  79903. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  79904. this._onPointerDownHandlerRef = function (evt) {
  79905. _this._onPointerDown(evt);
  79906. };
  79907. this._onPointerMoveHandlerRef = function (evt) {
  79908. _this._onPointerMove(evt);
  79909. };
  79910. this._onPointerUpHandlerRef = function (evt) {
  79911. _this._onPointerUp(evt);
  79912. };
  79913. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  79914. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  79915. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  79916. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  79917. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  79918. evt.preventDefault(); // Disables system menu
  79919. }, false);
  79920. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  79921. }
  79922. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  79923. this._joystickSensibility = newJoystickSensibility;
  79924. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  79925. };
  79926. VirtualJoystick.prototype._onPointerDown = function (e) {
  79927. var positionOnScreenCondition;
  79928. e.preventDefault();
  79929. if (this._leftJoystick === true) {
  79930. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  79931. }
  79932. else {
  79933. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  79934. }
  79935. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  79936. // First contact will be dedicated to the virtual joystick
  79937. this._joystickPointerID = e.pointerId;
  79938. this._joystickPointerStartPos.x = e.clientX;
  79939. this._joystickPointerStartPos.y = e.clientY;
  79940. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  79941. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  79942. this._deltaJoystickVector.x = 0;
  79943. this._deltaJoystickVector.y = 0;
  79944. this.pressed = true;
  79945. this._touches.add(e.pointerId.toString(), e);
  79946. }
  79947. else {
  79948. // You can only trigger the action buttons with a joystick declared
  79949. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  79950. this._action();
  79951. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  79952. }
  79953. }
  79954. };
  79955. VirtualJoystick.prototype._onPointerMove = function (e) {
  79956. // If the current pointer is the one associated to the joystick (first touch contact)
  79957. if (this._joystickPointerID == e.pointerId) {
  79958. this._joystickPointerPos.x = e.clientX;
  79959. this._joystickPointerPos.y = e.clientY;
  79960. this._deltaJoystickVector = this._joystickPointerPos.clone();
  79961. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  79962. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  79963. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  79964. switch (this._axisTargetedByLeftAndRight) {
  79965. case JoystickAxis.X:
  79966. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  79967. break;
  79968. case JoystickAxis.Y:
  79969. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  79970. break;
  79971. case JoystickAxis.Z:
  79972. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  79973. break;
  79974. }
  79975. var directionUpDown = this.reverseUpDown ? 1 : -1;
  79976. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  79977. switch (this._axisTargetedByUpAndDown) {
  79978. case JoystickAxis.X:
  79979. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  79980. break;
  79981. case JoystickAxis.Y:
  79982. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  79983. break;
  79984. case JoystickAxis.Z:
  79985. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  79986. break;
  79987. }
  79988. }
  79989. else {
  79990. var data = this._touches.get(e.pointerId.toString());
  79991. if (data) {
  79992. data.x = e.clientX;
  79993. data.y = e.clientY;
  79994. }
  79995. }
  79996. };
  79997. VirtualJoystick.prototype._onPointerUp = function (e) {
  79998. if (this._joystickPointerID == e.pointerId) {
  79999. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  80000. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  80001. this._joystickPointerID = -1;
  80002. this.pressed = false;
  80003. }
  80004. else {
  80005. var touch = this._touches.get(e.pointerId.toString());
  80006. if (touch) {
  80007. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  80008. }
  80009. }
  80010. this._deltaJoystickVector.x = 0;
  80011. this._deltaJoystickVector.y = 0;
  80012. this._touches.remove(e.pointerId.toString());
  80013. };
  80014. /**
  80015. * Change the color of the virtual joystick
  80016. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  80017. */
  80018. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  80019. this._joystickColor = newColor;
  80020. };
  80021. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  80022. this._action = action;
  80023. };
  80024. // Define which axis you'd like to control for left & right
  80025. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  80026. switch (axis) {
  80027. case JoystickAxis.X:
  80028. case JoystickAxis.Y:
  80029. case JoystickAxis.Z:
  80030. this._axisTargetedByLeftAndRight = axis;
  80031. break;
  80032. default:
  80033. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  80034. break;
  80035. }
  80036. };
  80037. // Define which axis you'd like to control for up & down
  80038. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  80039. switch (axis) {
  80040. case JoystickAxis.X:
  80041. case JoystickAxis.Y:
  80042. case JoystickAxis.Z:
  80043. this._axisTargetedByUpAndDown = axis;
  80044. break;
  80045. default:
  80046. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  80047. break;
  80048. }
  80049. };
  80050. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  80051. var _this = this;
  80052. if (this.pressed) {
  80053. this._touches.forEach(function (key, touch) {
  80054. if (touch.pointerId === _this._joystickPointerID) {
  80055. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  80056. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  80057. VirtualJoystick.vjCanvasContext.beginPath();
  80058. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  80059. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  80060. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  80061. VirtualJoystick.vjCanvasContext.stroke();
  80062. VirtualJoystick.vjCanvasContext.closePath();
  80063. VirtualJoystick.vjCanvasContext.beginPath();
  80064. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  80065. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  80066. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  80067. VirtualJoystick.vjCanvasContext.stroke();
  80068. VirtualJoystick.vjCanvasContext.closePath();
  80069. VirtualJoystick.vjCanvasContext.beginPath();
  80070. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  80071. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  80072. VirtualJoystick.vjCanvasContext.stroke();
  80073. VirtualJoystick.vjCanvasContext.closePath();
  80074. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  80075. }
  80076. else {
  80077. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  80078. VirtualJoystick.vjCanvasContext.beginPath();
  80079. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  80080. VirtualJoystick.vjCanvasContext.beginPath();
  80081. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  80082. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  80083. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  80084. VirtualJoystick.vjCanvasContext.stroke();
  80085. VirtualJoystick.vjCanvasContext.closePath();
  80086. touch.prevX = touch.x;
  80087. touch.prevY = touch.y;
  80088. }
  80089. ;
  80090. });
  80091. }
  80092. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  80093. };
  80094. VirtualJoystick.prototype.releaseCanvas = function () {
  80095. if (VirtualJoystick.vjCanvas) {
  80096. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  80097. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  80098. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  80099. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  80100. window.removeEventListener("resize", this._onResize);
  80101. document.body.removeChild(VirtualJoystick.vjCanvas);
  80102. VirtualJoystick.vjCanvas = null;
  80103. }
  80104. };
  80105. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  80106. VirtualJoystick._globalJoystickIndex = 0;
  80107. return VirtualJoystick;
  80108. }());
  80109. BABYLON.VirtualJoystick = VirtualJoystick;
  80110. })(BABYLON || (BABYLON = {}));
  80111. //# sourceMappingURL=babylon.virtualJoystick.js.map
  80112. var BABYLON;
  80113. (function (BABYLON) {
  80114. // We're mainly based on the logic defined into the FreeCamera code
  80115. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  80116. __extends(VirtualJoysticksCamera, _super);
  80117. function VirtualJoysticksCamera(name, position, scene) {
  80118. var _this = _super.call(this, name, position, scene) || this;
  80119. _this.inputs.addVirtualJoystick();
  80120. return _this;
  80121. }
  80122. VirtualJoysticksCamera.prototype.getClassName = function () {
  80123. return "VirtualJoysticksCamera";
  80124. };
  80125. return VirtualJoysticksCamera;
  80126. }(BABYLON.FreeCamera));
  80127. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  80128. })(BABYLON || (BABYLON = {}));
  80129. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  80130. var BABYLON;
  80131. (function (BABYLON) {
  80132. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  80133. function FreeCameraVirtualJoystickInput() {
  80134. }
  80135. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  80136. return this._leftjoystick;
  80137. };
  80138. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  80139. return this._rightjoystick;
  80140. };
  80141. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  80142. if (this._leftjoystick) {
  80143. var camera = this.camera;
  80144. var speed = camera._computeLocalCameraSpeed() * 50;
  80145. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  80146. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  80147. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  80148. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  80149. if (!this._leftjoystick.pressed) {
  80150. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  80151. }
  80152. if (!this._rightjoystick.pressed) {
  80153. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  80154. }
  80155. }
  80156. };
  80157. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  80158. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  80159. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  80160. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  80161. this._leftjoystick.setJoystickSensibility(0.15);
  80162. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  80163. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  80164. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  80165. this._rightjoystick.reverseUpDown = true;
  80166. this._rightjoystick.setJoystickSensibility(0.05);
  80167. this._rightjoystick.setJoystickColor("yellow");
  80168. };
  80169. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  80170. this._leftjoystick.releaseCanvas();
  80171. this._rightjoystick.releaseCanvas();
  80172. };
  80173. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  80174. return "FreeCameraVirtualJoystickInput";
  80175. };
  80176. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  80177. return "virtualJoystick";
  80178. };
  80179. return FreeCameraVirtualJoystickInput;
  80180. }());
  80181. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  80182. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  80183. })(BABYLON || (BABYLON = {}));
  80184. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  80185. var BABYLON;
  80186. (function (BABYLON) {
  80187. var SimplificationSettings = /** @class */ (function () {
  80188. function SimplificationSettings(quality, distance, optimizeMesh) {
  80189. this.quality = quality;
  80190. this.distance = distance;
  80191. this.optimizeMesh = optimizeMesh;
  80192. }
  80193. return SimplificationSettings;
  80194. }());
  80195. BABYLON.SimplificationSettings = SimplificationSettings;
  80196. var SimplificationQueue = /** @class */ (function () {
  80197. function SimplificationQueue() {
  80198. this.running = false;
  80199. this._simplificationArray = [];
  80200. }
  80201. SimplificationQueue.prototype.addTask = function (task) {
  80202. this._simplificationArray.push(task);
  80203. };
  80204. SimplificationQueue.prototype.executeNext = function () {
  80205. var task = this._simplificationArray.pop();
  80206. if (task) {
  80207. this.running = true;
  80208. this.runSimplification(task);
  80209. }
  80210. else {
  80211. this.running = false;
  80212. }
  80213. };
  80214. SimplificationQueue.prototype.runSimplification = function (task) {
  80215. var _this = this;
  80216. if (task.parallelProcessing) {
  80217. //parallel simplifier
  80218. task.settings.forEach(function (setting) {
  80219. var simplifier = _this.getSimplifier(task);
  80220. simplifier.simplify(setting, function (newMesh) {
  80221. task.mesh.addLODLevel(setting.distance, newMesh);
  80222. newMesh.isVisible = true;
  80223. //check if it is the last
  80224. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  80225. //all done, run the success callback.
  80226. task.successCallback();
  80227. }
  80228. _this.executeNext();
  80229. });
  80230. });
  80231. }
  80232. else {
  80233. //single simplifier.
  80234. var simplifier = this.getSimplifier(task);
  80235. var runDecimation = function (setting, callback) {
  80236. simplifier.simplify(setting, function (newMesh) {
  80237. task.mesh.addLODLevel(setting.distance, newMesh);
  80238. newMesh.isVisible = true;
  80239. //run the next quality level
  80240. callback();
  80241. });
  80242. };
  80243. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  80244. runDecimation(task.settings[loop.index], function () {
  80245. loop.executeNext();
  80246. });
  80247. }, function () {
  80248. //execution ended, run the success callback.
  80249. if (task.successCallback) {
  80250. task.successCallback();
  80251. }
  80252. _this.executeNext();
  80253. });
  80254. }
  80255. };
  80256. SimplificationQueue.prototype.getSimplifier = function (task) {
  80257. switch (task.simplificationType) {
  80258. case SimplificationType.QUADRATIC:
  80259. default:
  80260. return new QuadraticErrorSimplification(task.mesh);
  80261. }
  80262. };
  80263. return SimplificationQueue;
  80264. }());
  80265. BABYLON.SimplificationQueue = SimplificationQueue;
  80266. /**
  80267. * The implemented types of simplification.
  80268. * At the moment only Quadratic Error Decimation is implemented.
  80269. */
  80270. var SimplificationType;
  80271. (function (SimplificationType) {
  80272. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  80273. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  80274. var DecimationTriangle = /** @class */ (function () {
  80275. function DecimationTriangle(vertices) {
  80276. this.vertices = vertices;
  80277. this.error = new Array(4);
  80278. this.deleted = false;
  80279. this.isDirty = false;
  80280. this.deletePending = false;
  80281. this.borderFactor = 0;
  80282. }
  80283. return DecimationTriangle;
  80284. }());
  80285. BABYLON.DecimationTriangle = DecimationTriangle;
  80286. var DecimationVertex = /** @class */ (function () {
  80287. function DecimationVertex(position, id) {
  80288. this.position = position;
  80289. this.id = id;
  80290. this.isBorder = true;
  80291. this.q = new QuadraticMatrix();
  80292. this.triangleCount = 0;
  80293. this.triangleStart = 0;
  80294. this.originalOffsets = [];
  80295. }
  80296. DecimationVertex.prototype.updatePosition = function (newPosition) {
  80297. this.position.copyFrom(newPosition);
  80298. };
  80299. return DecimationVertex;
  80300. }());
  80301. BABYLON.DecimationVertex = DecimationVertex;
  80302. var QuadraticMatrix = /** @class */ (function () {
  80303. function QuadraticMatrix(data) {
  80304. this.data = new Array(10);
  80305. for (var i = 0; i < 10; ++i) {
  80306. if (data && data[i]) {
  80307. this.data[i] = data[i];
  80308. }
  80309. else {
  80310. this.data[i] = 0;
  80311. }
  80312. }
  80313. }
  80314. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  80315. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  80316. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  80317. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  80318. return det;
  80319. };
  80320. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  80321. for (var i = 0; i < 10; ++i) {
  80322. this.data[i] += matrix.data[i];
  80323. }
  80324. };
  80325. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  80326. for (var i = 0; i < 10; ++i) {
  80327. this.data[i] += data[i];
  80328. }
  80329. };
  80330. QuadraticMatrix.prototype.add = function (matrix) {
  80331. var m = new QuadraticMatrix();
  80332. for (var i = 0; i < 10; ++i) {
  80333. m.data[i] = this.data[i] + matrix.data[i];
  80334. }
  80335. return m;
  80336. };
  80337. QuadraticMatrix.FromData = function (a, b, c, d) {
  80338. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  80339. };
  80340. //returning an array to avoid garbage collection
  80341. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  80342. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  80343. };
  80344. return QuadraticMatrix;
  80345. }());
  80346. BABYLON.QuadraticMatrix = QuadraticMatrix;
  80347. var Reference = /** @class */ (function () {
  80348. function Reference(vertexId, triangleId) {
  80349. this.vertexId = vertexId;
  80350. this.triangleId = triangleId;
  80351. }
  80352. return Reference;
  80353. }());
  80354. BABYLON.Reference = Reference;
  80355. /**
  80356. * An implementation of the Quadratic Error simplification algorithm.
  80357. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  80358. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  80359. * @author RaananW
  80360. */
  80361. var QuadraticErrorSimplification = /** @class */ (function () {
  80362. function QuadraticErrorSimplification(_mesh) {
  80363. this._mesh = _mesh;
  80364. this.syncIterations = 5000;
  80365. this.aggressiveness = 7;
  80366. this.decimationIterations = 100;
  80367. this.boundingBoxEpsilon = BABYLON.Epsilon;
  80368. }
  80369. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  80370. var _this = this;
  80371. this.initDecimatedMesh();
  80372. //iterating through the submeshes array, one after the other.
  80373. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  80374. _this.initWithMesh(loop.index, function () {
  80375. _this.runDecimation(settings, loop.index, function () {
  80376. loop.executeNext();
  80377. });
  80378. }, settings.optimizeMesh);
  80379. }, function () {
  80380. setTimeout(function () {
  80381. successCallback(_this._reconstructedMesh);
  80382. }, 0);
  80383. });
  80384. };
  80385. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  80386. var _this = this;
  80387. var targetCount = ~~(this.triangles.length * settings.quality);
  80388. var deletedTriangles = 0;
  80389. var triangleCount = this.triangles.length;
  80390. var iterationFunction = function (iteration, callback) {
  80391. setTimeout(function () {
  80392. if (iteration % 5 === 0) {
  80393. _this.updateMesh(iteration === 0);
  80394. }
  80395. for (var i = 0; i < _this.triangles.length; ++i) {
  80396. _this.triangles[i].isDirty = false;
  80397. }
  80398. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  80399. var trianglesIterator = function (i) {
  80400. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  80401. var t = _this.triangles[tIdx];
  80402. if (!t)
  80403. return;
  80404. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  80405. return;
  80406. }
  80407. for (var j = 0; j < 3; ++j) {
  80408. if (t.error[j] < threshold) {
  80409. var deleted0 = [];
  80410. var deleted1 = [];
  80411. var v0 = t.vertices[j];
  80412. var v1 = t.vertices[(j + 1) % 3];
  80413. if (v0.isBorder || v1.isBorder)
  80414. continue;
  80415. var p = BABYLON.Vector3.Zero();
  80416. var n = BABYLON.Vector3.Zero();
  80417. var uv = BABYLON.Vector2.Zero();
  80418. var color = new BABYLON.Color4(0, 0, 0, 1);
  80419. _this.calculateError(v0, v1, p, n, uv, color);
  80420. var delTr = new Array();
  80421. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  80422. continue;
  80423. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  80424. continue;
  80425. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  80426. continue;
  80427. var uniqueArray = new Array();
  80428. delTr.forEach(function (deletedT) {
  80429. if (uniqueArray.indexOf(deletedT) === -1) {
  80430. deletedT.deletePending = true;
  80431. uniqueArray.push(deletedT);
  80432. }
  80433. });
  80434. if (uniqueArray.length % 2 !== 0) {
  80435. continue;
  80436. }
  80437. v0.q = v1.q.add(v0.q);
  80438. v0.updatePosition(p);
  80439. var tStart = _this.references.length;
  80440. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  80441. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  80442. var tCount = _this.references.length - tStart;
  80443. if (tCount <= v0.triangleCount) {
  80444. if (tCount) {
  80445. for (var c = 0; c < tCount; c++) {
  80446. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  80447. }
  80448. }
  80449. }
  80450. else {
  80451. v0.triangleStart = tStart;
  80452. }
  80453. v0.triangleCount = tCount;
  80454. break;
  80455. }
  80456. }
  80457. };
  80458. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  80459. }, 0);
  80460. };
  80461. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  80462. if (triangleCount - deletedTriangles <= targetCount)
  80463. loop.breakLoop();
  80464. else {
  80465. iterationFunction(loop.index, function () {
  80466. loop.executeNext();
  80467. });
  80468. }
  80469. }, function () {
  80470. setTimeout(function () {
  80471. //reconstruct this part of the mesh
  80472. _this.reconstructMesh(submeshIndex);
  80473. successCallback();
  80474. }, 0);
  80475. });
  80476. };
  80477. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  80478. var _this = this;
  80479. this.vertices = [];
  80480. this.triangles = [];
  80481. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  80482. var indices = this._mesh.getIndices();
  80483. var submesh = this._mesh.subMeshes[submeshIndex];
  80484. var findInVertices = function (positionToSearch) {
  80485. if (optimizeMesh) {
  80486. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  80487. if (_this.vertices[ii].position.equals(positionToSearch)) {
  80488. return _this.vertices[ii];
  80489. }
  80490. }
  80491. }
  80492. return null;
  80493. };
  80494. var vertexReferences = [];
  80495. var vertexInit = function (i) {
  80496. if (!positionData) {
  80497. return;
  80498. }
  80499. var offset = i + submesh.verticesStart;
  80500. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  80501. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  80502. vertex.originalOffsets.push(offset);
  80503. if (vertex.id === _this.vertices.length) {
  80504. _this.vertices.push(vertex);
  80505. }
  80506. vertexReferences.push(vertex.id);
  80507. };
  80508. //var totalVertices = mesh.getTotalVertices();
  80509. var totalVertices = submesh.verticesCount;
  80510. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  80511. var indicesInit = function (i) {
  80512. if (!indices) {
  80513. return;
  80514. }
  80515. var offset = (submesh.indexStart / 3) + i;
  80516. var pos = (offset * 3);
  80517. var i0 = indices[pos + 0];
  80518. var i1 = indices[pos + 1];
  80519. var i2 = indices[pos + 2];
  80520. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  80521. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  80522. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  80523. var triangle = new DecimationTriangle([v0, v1, v2]);
  80524. triangle.originalOffset = pos;
  80525. _this.triangles.push(triangle);
  80526. };
  80527. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  80528. _this.init(callback);
  80529. });
  80530. });
  80531. };
  80532. QuadraticErrorSimplification.prototype.init = function (callback) {
  80533. var _this = this;
  80534. var triangleInit1 = function (i) {
  80535. var t = _this.triangles[i];
  80536. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  80537. for (var j = 0; j < 3; j++) {
  80538. 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))));
  80539. }
  80540. };
  80541. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  80542. var triangleInit2 = function (i) {
  80543. var t = _this.triangles[i];
  80544. for (var j = 0; j < 3; ++j) {
  80545. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  80546. }
  80547. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  80548. };
  80549. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  80550. callback();
  80551. });
  80552. });
  80553. };
  80554. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  80555. var newTriangles = [];
  80556. var i;
  80557. for (i = 0; i < this.vertices.length; ++i) {
  80558. this.vertices[i].triangleCount = 0;
  80559. }
  80560. var t;
  80561. var j;
  80562. for (i = 0; i < this.triangles.length; ++i) {
  80563. if (!this.triangles[i].deleted) {
  80564. t = this.triangles[i];
  80565. for (j = 0; j < 3; ++j) {
  80566. t.vertices[j].triangleCount = 1;
  80567. }
  80568. newTriangles.push(t);
  80569. }
  80570. }
  80571. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  80572. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  80573. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  80574. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  80575. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  80576. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  80577. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  80578. var vertexCount = 0;
  80579. for (i = 0; i < this.vertices.length; ++i) {
  80580. var vertex = this.vertices[i];
  80581. vertex.id = vertexCount;
  80582. if (vertex.triangleCount) {
  80583. vertex.originalOffsets.forEach(function (originalOffset) {
  80584. if (!normalData) {
  80585. return;
  80586. }
  80587. newPositionData.push(vertex.position.x);
  80588. newPositionData.push(vertex.position.y);
  80589. newPositionData.push(vertex.position.z);
  80590. newNormalData.push(normalData[originalOffset * 3]);
  80591. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  80592. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  80593. if (uvs && uvs.length) {
  80594. newUVsData.push(uvs[(originalOffset * 2)]);
  80595. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  80596. }
  80597. else if (colorsData && colorsData.length) {
  80598. newColorsData.push(colorsData[(originalOffset * 4)]);
  80599. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  80600. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  80601. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  80602. }
  80603. ++vertexCount;
  80604. });
  80605. }
  80606. }
  80607. var startingIndex = this._reconstructedMesh.getTotalIndices();
  80608. var startingVertex = this._reconstructedMesh.getTotalVertices();
  80609. var submeshesArray = this._reconstructedMesh.subMeshes;
  80610. this._reconstructedMesh.subMeshes = [];
  80611. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  80612. var originalIndices = this._mesh.getIndices();
  80613. for (i = 0; i < newTriangles.length; ++i) {
  80614. t = newTriangles[i]; //now get the new referencing point for each vertex
  80615. [0, 1, 2].forEach(function (idx) {
  80616. var id = originalIndices[t.originalOffset + idx];
  80617. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  80618. if (offset < 0)
  80619. offset = 0;
  80620. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  80621. });
  80622. }
  80623. //overwriting the old vertex buffers and indices.
  80624. this._reconstructedMesh.setIndices(newIndicesArray);
  80625. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  80626. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  80627. if (newUVsData.length > 0)
  80628. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  80629. if (newColorsData.length > 0)
  80630. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  80631. //create submesh
  80632. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  80633. if (submeshIndex > 0) {
  80634. this._reconstructedMesh.subMeshes = [];
  80635. submeshesArray.forEach(function (submesh) {
  80636. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  80637. });
  80638. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  80639. }
  80640. };
  80641. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  80642. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  80643. this._reconstructedMesh.material = this._mesh.material;
  80644. this._reconstructedMesh.parent = this._mesh.parent;
  80645. this._reconstructedMesh.isVisible = false;
  80646. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  80647. };
  80648. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  80649. for (var i = 0; i < vertex1.triangleCount; ++i) {
  80650. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  80651. if (t.deleted)
  80652. continue;
  80653. var s = this.references[vertex1.triangleStart + i].vertexId;
  80654. var v1 = t.vertices[(s + 1) % 3];
  80655. var v2 = t.vertices[(s + 2) % 3];
  80656. if ((v1 === vertex2 || v2 === vertex2)) {
  80657. deletedArray[i] = true;
  80658. delTr.push(t);
  80659. continue;
  80660. }
  80661. var d1 = v1.position.subtract(point);
  80662. d1 = d1.normalize();
  80663. var d2 = v2.position.subtract(point);
  80664. d2 = d2.normalize();
  80665. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  80666. return true;
  80667. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  80668. deletedArray[i] = false;
  80669. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  80670. return true;
  80671. }
  80672. return false;
  80673. };
  80674. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  80675. var newDeleted = deletedTriangles;
  80676. for (var i = 0; i < vertex.triangleCount; ++i) {
  80677. var ref = this.references[vertex.triangleStart + i];
  80678. var t = this.triangles[ref.triangleId];
  80679. if (t.deleted)
  80680. continue;
  80681. if (deletedArray[i] && t.deletePending) {
  80682. t.deleted = true;
  80683. newDeleted++;
  80684. continue;
  80685. }
  80686. t.vertices[ref.vertexId] = origVertex;
  80687. t.isDirty = true;
  80688. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  80689. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  80690. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  80691. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  80692. this.references.push(ref);
  80693. }
  80694. return newDeleted;
  80695. };
  80696. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  80697. for (var i = 0; i < this.vertices.length; ++i) {
  80698. var vCount = [];
  80699. var vId = [];
  80700. var v = this.vertices[i];
  80701. var j;
  80702. for (j = 0; j < v.triangleCount; ++j) {
  80703. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  80704. for (var ii = 0; ii < 3; ii++) {
  80705. var ofs = 0;
  80706. var vv = triangle.vertices[ii];
  80707. while (ofs < vCount.length) {
  80708. if (vId[ofs] === vv.id)
  80709. break;
  80710. ++ofs;
  80711. }
  80712. if (ofs === vCount.length) {
  80713. vCount.push(1);
  80714. vId.push(vv.id);
  80715. }
  80716. else {
  80717. vCount[ofs]++;
  80718. }
  80719. }
  80720. }
  80721. for (j = 0; j < vCount.length; ++j) {
  80722. if (vCount[j] === 1) {
  80723. this.vertices[vId[j]].isBorder = true;
  80724. }
  80725. else {
  80726. this.vertices[vId[j]].isBorder = false;
  80727. }
  80728. }
  80729. }
  80730. };
  80731. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  80732. if (identifyBorders === void 0) { identifyBorders = false; }
  80733. var i;
  80734. if (!identifyBorders) {
  80735. var newTrianglesVector = [];
  80736. for (i = 0; i < this.triangles.length; ++i) {
  80737. if (!this.triangles[i].deleted) {
  80738. newTrianglesVector.push(this.triangles[i]);
  80739. }
  80740. }
  80741. this.triangles = newTrianglesVector;
  80742. }
  80743. for (i = 0; i < this.vertices.length; ++i) {
  80744. this.vertices[i].triangleCount = 0;
  80745. this.vertices[i].triangleStart = 0;
  80746. }
  80747. var t;
  80748. var j;
  80749. var v;
  80750. for (i = 0; i < this.triangles.length; ++i) {
  80751. t = this.triangles[i];
  80752. for (j = 0; j < 3; ++j) {
  80753. v = t.vertices[j];
  80754. v.triangleCount++;
  80755. }
  80756. }
  80757. var tStart = 0;
  80758. for (i = 0; i < this.vertices.length; ++i) {
  80759. this.vertices[i].triangleStart = tStart;
  80760. tStart += this.vertices[i].triangleCount;
  80761. this.vertices[i].triangleCount = 0;
  80762. }
  80763. var newReferences = new Array(this.triangles.length * 3);
  80764. for (i = 0; i < this.triangles.length; ++i) {
  80765. t = this.triangles[i];
  80766. for (j = 0; j < 3; ++j) {
  80767. v = t.vertices[j];
  80768. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  80769. v.triangleCount++;
  80770. }
  80771. }
  80772. this.references = newReferences;
  80773. if (identifyBorders) {
  80774. this.identifyBorder();
  80775. }
  80776. };
  80777. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  80778. var x = point.x;
  80779. var y = point.y;
  80780. var z = point.z;
  80781. 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
  80782. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  80783. };
  80784. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  80785. var q = vertex1.q.add(vertex2.q);
  80786. var border = vertex1.isBorder && vertex2.isBorder;
  80787. var error = 0;
  80788. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  80789. if (qDet !== 0 && !border) {
  80790. if (!pointResult) {
  80791. pointResult = BABYLON.Vector3.Zero();
  80792. }
  80793. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  80794. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  80795. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  80796. error = this.vertexError(q, pointResult);
  80797. }
  80798. else {
  80799. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  80800. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  80801. var error1 = this.vertexError(q, vertex1.position);
  80802. var error2 = this.vertexError(q, vertex2.position);
  80803. var error3 = this.vertexError(q, p3);
  80804. error = Math.min(error1, error2, error3);
  80805. if (error === error1) {
  80806. if (pointResult) {
  80807. pointResult.copyFrom(vertex1.position);
  80808. }
  80809. }
  80810. else if (error === error2) {
  80811. if (pointResult) {
  80812. pointResult.copyFrom(vertex2.position);
  80813. }
  80814. }
  80815. else {
  80816. if (pointResult) {
  80817. pointResult.copyFrom(p3);
  80818. }
  80819. }
  80820. }
  80821. return error;
  80822. };
  80823. return QuadraticErrorSimplification;
  80824. }());
  80825. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  80826. })(BABYLON || (BABYLON = {}));
  80827. //# sourceMappingURL=babylon.meshSimplification.js.map
  80828. var BABYLON;
  80829. (function (BABYLON) {
  80830. var MeshLODLevel = /** @class */ (function () {
  80831. function MeshLODLevel(distance, mesh) {
  80832. this.distance = distance;
  80833. this.mesh = mesh;
  80834. }
  80835. return MeshLODLevel;
  80836. }());
  80837. BABYLON.MeshLODLevel = MeshLODLevel;
  80838. })(BABYLON || (BABYLON = {}));
  80839. //# sourceMappingURL=babylon.meshLODLevel.js.map
  80840. var BABYLON;
  80841. (function (BABYLON) {
  80842. /**
  80843. * Defines the root class used to create scene optimization to use with SceneOptimizer
  80844. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  80845. */
  80846. var SceneOptimization = /** @class */ (function () {
  80847. /**
  80848. * Creates the SceneOptimization object
  80849. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  80850. * @param desc defines the description associated with the optimization
  80851. */
  80852. function SceneOptimization(
  80853. /**
  80854. * Defines the priority of this optimization (0 by default which means first in the list)
  80855. */
  80856. priority) {
  80857. if (priority === void 0) { priority = 0; }
  80858. this.priority = priority;
  80859. }
  80860. /**
  80861. * Gets a string describing the action executed by the current optimization
  80862. * @returns description string
  80863. */
  80864. SceneOptimization.prototype.getDescription = function () {
  80865. return "";
  80866. };
  80867. /**
  80868. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  80869. * @param scene defines the current scene where to apply this optimization
  80870. * @param optimizer defines the current optimizer
  80871. * @returns true if everything that can be done was applied
  80872. */
  80873. SceneOptimization.prototype.apply = function (scene, optimizer) {
  80874. return true;
  80875. };
  80876. ;
  80877. return SceneOptimization;
  80878. }());
  80879. BABYLON.SceneOptimization = SceneOptimization;
  80880. /**
  80881. * Defines an optimization used to reduce the size of render target textures
  80882. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  80883. */
  80884. var TextureOptimization = /** @class */ (function (_super) {
  80885. __extends(TextureOptimization, _super);
  80886. /**
  80887. * Creates the TextureOptimization object
  80888. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  80889. * @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
  80890. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  80891. */
  80892. function TextureOptimization(
  80893. /**
  80894. * Defines the priority of this optimization (0 by default which means first in the list)
  80895. */
  80896. priority,
  80897. /**
  80898. * 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
  80899. */
  80900. maximumSize,
  80901. /**
  80902. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  80903. */
  80904. step) {
  80905. if (priority === void 0) { priority = 0; }
  80906. if (maximumSize === void 0) { maximumSize = 1024; }
  80907. if (step === void 0) { step = 0.5; }
  80908. var _this = _super.call(this, priority) || this;
  80909. _this.priority = priority;
  80910. _this.maximumSize = maximumSize;
  80911. _this.step = step;
  80912. return _this;
  80913. }
  80914. /**
  80915. * Gets a string describing the action executed by the current optimization
  80916. * @returns description string
  80917. */
  80918. TextureOptimization.prototype.getDescription = function () {
  80919. return "Reducing render target texture size to " + this.maximumSize;
  80920. };
  80921. /**
  80922. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  80923. * @param scene defines the current scene where to apply this optimization
  80924. * @param optimizer defines the current optimizer
  80925. * @returns true if everything that can be done was applied
  80926. */
  80927. TextureOptimization.prototype.apply = function (scene, optimizer) {
  80928. var allDone = true;
  80929. for (var index = 0; index < scene.textures.length; index++) {
  80930. var texture = scene.textures[index];
  80931. if (!texture.canRescale || texture.getContext) {
  80932. continue;
  80933. }
  80934. var currentSize = texture.getSize();
  80935. var maxDimension = Math.max(currentSize.width, currentSize.height);
  80936. if (maxDimension > this.maximumSize) {
  80937. texture.scale(this.step);
  80938. allDone = false;
  80939. }
  80940. }
  80941. return allDone;
  80942. };
  80943. return TextureOptimization;
  80944. }(SceneOptimization));
  80945. BABYLON.TextureOptimization = TextureOptimization;
  80946. /**
  80947. * Defines an optimization used to increase or decrease the rendering resolution
  80948. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  80949. */
  80950. var HardwareScalingOptimization = /** @class */ (function (_super) {
  80951. __extends(HardwareScalingOptimization, _super);
  80952. /**
  80953. * Creates the HardwareScalingOptimization object
  80954. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  80955. * @param maximumScale defines the maximum scale to use (2 by default)
  80956. * @param step defines the step to use between two passes (0.5 by default)
  80957. */
  80958. function HardwareScalingOptimization(
  80959. /**
  80960. * Defines the priority of this optimization (0 by default which means first in the list)
  80961. */
  80962. priority,
  80963. /**
  80964. * Defines the maximum scale to use (2 by default)
  80965. */
  80966. maximumScale,
  80967. /**
  80968. * Defines the step to use between two passes (0.5 by default)
  80969. */
  80970. step) {
  80971. if (priority === void 0) { priority = 0; }
  80972. if (maximumScale === void 0) { maximumScale = 2; }
  80973. if (step === void 0) { step = 0.25; }
  80974. var _this = _super.call(this, priority) || this;
  80975. _this.priority = priority;
  80976. _this.maximumScale = maximumScale;
  80977. _this.step = step;
  80978. _this._currentScale = -1;
  80979. _this._directionOffset = 1;
  80980. return _this;
  80981. }
  80982. /**
  80983. * Gets a string describing the action executed by the current optimization
  80984. * @return description string
  80985. */
  80986. HardwareScalingOptimization.prototype.getDescription = function () {
  80987. return "Setting hardware scaling level to " + this._currentScale;
  80988. };
  80989. /**
  80990. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  80991. * @param scene defines the current scene where to apply this optimization
  80992. * @param optimizer defines the current optimizer
  80993. * @returns true if everything that can be done was applied
  80994. */
  80995. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  80996. if (this._currentScale === -1) {
  80997. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  80998. if (this._currentScale > this.maximumScale) {
  80999. this._directionOffset = -1;
  81000. }
  81001. }
  81002. this._currentScale += this._directionOffset * this.step;
  81003. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  81004. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  81005. };
  81006. ;
  81007. return HardwareScalingOptimization;
  81008. }(SceneOptimization));
  81009. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  81010. /**
  81011. * Defines an optimization used to remove shadows
  81012. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  81013. */
  81014. var ShadowsOptimization = /** @class */ (function (_super) {
  81015. __extends(ShadowsOptimization, _super);
  81016. function ShadowsOptimization() {
  81017. return _super !== null && _super.apply(this, arguments) || this;
  81018. }
  81019. /**
  81020. * Gets a string describing the action executed by the current optimization
  81021. * @return description string
  81022. */
  81023. ShadowsOptimization.prototype.getDescription = function () {
  81024. return "Turning shadows on/off";
  81025. };
  81026. /**
  81027. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  81028. * @param scene defines the current scene where to apply this optimization
  81029. * @param optimizer defines the current optimizer
  81030. * @returns true if everything that can be done was applied
  81031. */
  81032. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  81033. scene.shadowsEnabled = optimizer.isInImprovementMode;
  81034. return true;
  81035. };
  81036. ;
  81037. return ShadowsOptimization;
  81038. }(SceneOptimization));
  81039. BABYLON.ShadowsOptimization = ShadowsOptimization;
  81040. /**
  81041. * Defines an optimization used to turn post-processes off
  81042. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  81043. */
  81044. var PostProcessesOptimization = /** @class */ (function (_super) {
  81045. __extends(PostProcessesOptimization, _super);
  81046. function PostProcessesOptimization() {
  81047. return _super !== null && _super.apply(this, arguments) || this;
  81048. }
  81049. /**
  81050. * Gets a string describing the action executed by the current optimization
  81051. * @return description string
  81052. */
  81053. PostProcessesOptimization.prototype.getDescription = function () {
  81054. return "Turning post-processes on/off";
  81055. };
  81056. /**
  81057. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  81058. * @param scene defines the current scene where to apply this optimization
  81059. * @param optimizer defines the current optimizer
  81060. * @returns true if everything that can be done was applied
  81061. */
  81062. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  81063. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  81064. return true;
  81065. };
  81066. ;
  81067. return PostProcessesOptimization;
  81068. }(SceneOptimization));
  81069. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  81070. /**
  81071. * Defines an optimization used to turn lens flares off
  81072. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  81073. */
  81074. var LensFlaresOptimization = /** @class */ (function (_super) {
  81075. __extends(LensFlaresOptimization, _super);
  81076. function LensFlaresOptimization() {
  81077. return _super !== null && _super.apply(this, arguments) || this;
  81078. }
  81079. /**
  81080. * Gets a string describing the action executed by the current optimization
  81081. * @return description string
  81082. */
  81083. LensFlaresOptimization.prototype.getDescription = function () {
  81084. return "Turning lens flares on/off";
  81085. };
  81086. /**
  81087. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  81088. * @param scene defines the current scene where to apply this optimization
  81089. * @param optimizer defines the current optimizer
  81090. * @returns true if everything that can be done was applied
  81091. */
  81092. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  81093. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  81094. return true;
  81095. };
  81096. ;
  81097. return LensFlaresOptimization;
  81098. }(SceneOptimization));
  81099. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  81100. /**
  81101. * Defines an optimization based on user defined callback.
  81102. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  81103. */
  81104. var CustomOptimization = /** @class */ (function (_super) {
  81105. __extends(CustomOptimization, _super);
  81106. function CustomOptimization() {
  81107. return _super !== null && _super.apply(this, arguments) || this;
  81108. }
  81109. /**
  81110. * Gets a string describing the action executed by the current optimization
  81111. * @returns description string
  81112. */
  81113. CustomOptimization.prototype.getDescription = function () {
  81114. if (this.onGetDescription) {
  81115. return this.onGetDescription();
  81116. }
  81117. return "Running user defined callback";
  81118. };
  81119. /**
  81120. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  81121. * @param scene defines the current scene where to apply this optimization
  81122. * @param optimizer defines the current optimizer
  81123. * @returns true if everything that can be done was applied
  81124. */
  81125. CustomOptimization.prototype.apply = function (scene, optimizer) {
  81126. if (this.onApply) {
  81127. return this.onApply(scene, optimizer);
  81128. }
  81129. return true;
  81130. };
  81131. ;
  81132. return CustomOptimization;
  81133. }(SceneOptimization));
  81134. BABYLON.CustomOptimization = CustomOptimization;
  81135. /**
  81136. * Defines an optimization used to turn particles off
  81137. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  81138. */
  81139. var ParticlesOptimization = /** @class */ (function (_super) {
  81140. __extends(ParticlesOptimization, _super);
  81141. function ParticlesOptimization() {
  81142. return _super !== null && _super.apply(this, arguments) || this;
  81143. }
  81144. /**
  81145. * Gets a string describing the action executed by the current optimization
  81146. * @return description string
  81147. */
  81148. ParticlesOptimization.prototype.getDescription = function () {
  81149. return "Turning particles on/off";
  81150. };
  81151. /**
  81152. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  81153. * @param scene defines the current scene where to apply this optimization
  81154. * @param optimizer defines the current optimizer
  81155. * @returns true if everything that can be done was applied
  81156. */
  81157. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  81158. scene.particlesEnabled = optimizer.isInImprovementMode;
  81159. return true;
  81160. };
  81161. ;
  81162. return ParticlesOptimization;
  81163. }(SceneOptimization));
  81164. BABYLON.ParticlesOptimization = ParticlesOptimization;
  81165. /**
  81166. * Defines an optimization used to turn render targets off
  81167. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  81168. */
  81169. var RenderTargetsOptimization = /** @class */ (function (_super) {
  81170. __extends(RenderTargetsOptimization, _super);
  81171. function RenderTargetsOptimization() {
  81172. return _super !== null && _super.apply(this, arguments) || this;
  81173. }
  81174. /**
  81175. * Gets a string describing the action executed by the current optimization
  81176. * @return description string
  81177. */
  81178. RenderTargetsOptimization.prototype.getDescription = function () {
  81179. return "Turning render targets off";
  81180. };
  81181. /**
  81182. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  81183. * @param scene defines the current scene where to apply this optimization
  81184. * @param optimizer defines the current optimizer
  81185. * @returns true if everything that can be done was applied
  81186. */
  81187. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  81188. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  81189. return true;
  81190. };
  81191. ;
  81192. return RenderTargetsOptimization;
  81193. }(SceneOptimization));
  81194. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  81195. /**
  81196. * Defines an optimization used to merge meshes with compatible materials
  81197. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  81198. */
  81199. var MergeMeshesOptimization = /** @class */ (function (_super) {
  81200. __extends(MergeMeshesOptimization, _super);
  81201. function MergeMeshesOptimization() {
  81202. var _this = _super !== null && _super.apply(this, arguments) || this;
  81203. _this._canBeMerged = function (abstractMesh) {
  81204. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  81205. return false;
  81206. }
  81207. var mesh = abstractMesh;
  81208. if (!mesh.isVisible || !mesh.isEnabled()) {
  81209. return false;
  81210. }
  81211. if (mesh.instances.length > 0) {
  81212. return false;
  81213. }
  81214. if (mesh.skeleton || mesh.hasLODLevels) {
  81215. return false;
  81216. }
  81217. if (mesh.parent) {
  81218. return false;
  81219. }
  81220. return true;
  81221. };
  81222. return _this;
  81223. }
  81224. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  81225. /**
  81226. * Gets or sets a boolean which defines if optimization octree has to be updated
  81227. */
  81228. get: function () {
  81229. return MergeMeshesOptimization._UpdateSelectionTree;
  81230. },
  81231. /**
  81232. * Gets or sets a boolean which defines if optimization octree has to be updated
  81233. */
  81234. set: function (value) {
  81235. MergeMeshesOptimization._UpdateSelectionTree = value;
  81236. },
  81237. enumerable: true,
  81238. configurable: true
  81239. });
  81240. /**
  81241. * Gets a string describing the action executed by the current optimization
  81242. * @return description string
  81243. */
  81244. MergeMeshesOptimization.prototype.getDescription = function () {
  81245. return "Merging similar meshes together";
  81246. };
  81247. /**
  81248. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  81249. * @param scene defines the current scene where to apply this optimization
  81250. * @param optimizer defines the current optimizer
  81251. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  81252. * @returns true if everything that can be done was applied
  81253. */
  81254. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  81255. var globalPool = scene.meshes.slice(0);
  81256. var globalLength = globalPool.length;
  81257. for (var index = 0; index < globalLength; index++) {
  81258. var currentPool = new Array();
  81259. var current = globalPool[index];
  81260. // Checks
  81261. if (!this._canBeMerged(current)) {
  81262. continue;
  81263. }
  81264. currentPool.push(current);
  81265. // Find compatible meshes
  81266. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  81267. var otherMesh = globalPool[subIndex];
  81268. if (!this._canBeMerged(otherMesh)) {
  81269. continue;
  81270. }
  81271. if (otherMesh.material !== current.material) {
  81272. continue;
  81273. }
  81274. if (otherMesh.checkCollisions !== current.checkCollisions) {
  81275. continue;
  81276. }
  81277. currentPool.push(otherMesh);
  81278. globalLength--;
  81279. globalPool.splice(subIndex, 1);
  81280. subIndex--;
  81281. }
  81282. if (currentPool.length < 2) {
  81283. continue;
  81284. }
  81285. // Merge meshes
  81286. BABYLON.Mesh.MergeMeshes(currentPool);
  81287. }
  81288. if (updateSelectionTree != undefined) {
  81289. if (updateSelectionTree) {
  81290. scene.createOrUpdateSelectionOctree();
  81291. }
  81292. }
  81293. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  81294. scene.createOrUpdateSelectionOctree();
  81295. }
  81296. return true;
  81297. };
  81298. ;
  81299. MergeMeshesOptimization._UpdateSelectionTree = false;
  81300. return MergeMeshesOptimization;
  81301. }(SceneOptimization));
  81302. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  81303. /**
  81304. * Defines a list of options used by SceneOptimizer
  81305. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  81306. */
  81307. var SceneOptimizerOptions = /** @class */ (function () {
  81308. /**
  81309. * Creates a new list of options used by SceneOptimizer
  81310. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  81311. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  81312. */
  81313. function SceneOptimizerOptions(
  81314. /**
  81315. * Defines the target frame rate to reach (60 by default)
  81316. */
  81317. targetFrameRate,
  81318. /**
  81319. * Defines the interval between two checkes (2000ms by default)
  81320. */
  81321. trackerDuration) {
  81322. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  81323. if (trackerDuration === void 0) { trackerDuration = 2000; }
  81324. this.targetFrameRate = targetFrameRate;
  81325. this.trackerDuration = trackerDuration;
  81326. /**
  81327. * Gets the list of optimizations to apply
  81328. */
  81329. this.optimizations = new Array();
  81330. }
  81331. /**
  81332. * Add a new optimization
  81333. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  81334. * @returns the current SceneOptimizerOptions
  81335. */
  81336. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  81337. this.optimizations.push(optimization);
  81338. return this;
  81339. };
  81340. /**
  81341. * Add a new custom optimization
  81342. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  81343. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  81344. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  81345. * @returns the current SceneOptimizerOptions
  81346. */
  81347. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  81348. if (priority === void 0) { priority = 0; }
  81349. var optimization = new CustomOptimization(priority);
  81350. optimization.onApply = onApply;
  81351. optimization.onGetDescription = onGetDescription;
  81352. this.optimizations.push(optimization);
  81353. return this;
  81354. };
  81355. /**
  81356. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  81357. * @param targetFrameRate defines the target frame rate (60 by default)
  81358. * @returns a SceneOptimizerOptions object
  81359. */
  81360. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  81361. var result = new SceneOptimizerOptions(targetFrameRate);
  81362. var priority = 0;
  81363. result.addOptimization(new MergeMeshesOptimization(priority));
  81364. result.addOptimization(new ShadowsOptimization(priority));
  81365. result.addOptimization(new LensFlaresOptimization(priority));
  81366. // Next priority
  81367. priority++;
  81368. result.addOptimization(new PostProcessesOptimization(priority));
  81369. result.addOptimization(new ParticlesOptimization(priority));
  81370. // Next priority
  81371. priority++;
  81372. result.addOptimization(new TextureOptimization(priority, 1024));
  81373. return result;
  81374. };
  81375. /**
  81376. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  81377. * @param targetFrameRate defines the target frame rate (60 by default)
  81378. * @returns a SceneOptimizerOptions object
  81379. */
  81380. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  81381. var result = new SceneOptimizerOptions(targetFrameRate);
  81382. var priority = 0;
  81383. result.addOptimization(new MergeMeshesOptimization(priority));
  81384. result.addOptimization(new ShadowsOptimization(priority));
  81385. result.addOptimization(new LensFlaresOptimization(priority));
  81386. // Next priority
  81387. priority++;
  81388. result.addOptimization(new PostProcessesOptimization(priority));
  81389. result.addOptimization(new ParticlesOptimization(priority));
  81390. // Next priority
  81391. priority++;
  81392. result.addOptimization(new TextureOptimization(priority, 512));
  81393. // Next priority
  81394. priority++;
  81395. result.addOptimization(new RenderTargetsOptimization(priority));
  81396. // Next priority
  81397. priority++;
  81398. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  81399. return result;
  81400. };
  81401. /**
  81402. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  81403. * @param targetFrameRate defines the target frame rate (60 by default)
  81404. * @returns a SceneOptimizerOptions object
  81405. */
  81406. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  81407. var result = new SceneOptimizerOptions(targetFrameRate);
  81408. var priority = 0;
  81409. result.addOptimization(new MergeMeshesOptimization(priority));
  81410. result.addOptimization(new ShadowsOptimization(priority));
  81411. result.addOptimization(new LensFlaresOptimization(priority));
  81412. // Next priority
  81413. priority++;
  81414. result.addOptimization(new PostProcessesOptimization(priority));
  81415. result.addOptimization(new ParticlesOptimization(priority));
  81416. // Next priority
  81417. priority++;
  81418. result.addOptimization(new TextureOptimization(priority, 256));
  81419. // Next priority
  81420. priority++;
  81421. result.addOptimization(new RenderTargetsOptimization(priority));
  81422. // Next priority
  81423. priority++;
  81424. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  81425. return result;
  81426. };
  81427. return SceneOptimizerOptions;
  81428. }());
  81429. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  81430. /**
  81431. * Class used to run optimizations in order to reach a target frame rate
  81432. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  81433. */
  81434. var SceneOptimizer = /** @class */ (function () {
  81435. /**
  81436. * Creates a new SceneOptimizer
  81437. * @param scene defines the scene to work on
  81438. * @param options defines the options to use with the SceneOptimizer
  81439. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  81440. * @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)
  81441. */
  81442. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  81443. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  81444. if (improvementMode === void 0) { improvementMode = false; }
  81445. var _this = this;
  81446. this._isRunning = false;
  81447. this._currentPriorityLevel = 0;
  81448. this._targetFrameRate = 60;
  81449. this._trackerDuration = 2000;
  81450. this._currentFrameRate = 0;
  81451. this._improvementMode = false;
  81452. /**
  81453. * Defines an observable called when the optimizer reaches the target frame rate
  81454. */
  81455. this.onSuccessObservable = new BABYLON.Observable();
  81456. /**
  81457. * Defines an observable called when the optimizer enables an optimization
  81458. */
  81459. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  81460. /**
  81461. * Defines an observable called when the optimizer is not able to reach the target frame rate
  81462. */
  81463. this.onFailureObservable = new BABYLON.Observable();
  81464. if (!options) {
  81465. this._options = new SceneOptimizerOptions();
  81466. }
  81467. else {
  81468. this._options = options;
  81469. }
  81470. if (this._options.targetFrameRate) {
  81471. this._targetFrameRate = this._options.targetFrameRate;
  81472. }
  81473. if (this._options.trackerDuration) {
  81474. this._trackerDuration = this._options.trackerDuration;
  81475. }
  81476. if (autoGeneratePriorities) {
  81477. var priority = 0;
  81478. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  81479. var optim = _a[_i];
  81480. optim.priority = priority++;
  81481. }
  81482. }
  81483. this._improvementMode = improvementMode;
  81484. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  81485. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  81486. _this._sceneDisposeObserver = null;
  81487. _this.dispose();
  81488. });
  81489. }
  81490. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  81491. /**
  81492. * Gets a boolean indicating if the optimizer is in improvement mode
  81493. */
  81494. get: function () {
  81495. return this._improvementMode;
  81496. },
  81497. enumerable: true,
  81498. configurable: true
  81499. });
  81500. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  81501. /**
  81502. * Gets the current priority level (0 at start)
  81503. */
  81504. get: function () {
  81505. return this._currentPriorityLevel;
  81506. },
  81507. enumerable: true,
  81508. configurable: true
  81509. });
  81510. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  81511. /**
  81512. * Gets the current frame rate checked by the SceneOptimizer
  81513. */
  81514. get: function () {
  81515. return this._currentFrameRate;
  81516. },
  81517. enumerable: true,
  81518. configurable: true
  81519. });
  81520. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  81521. /**
  81522. * Gets or sets the current target frame rate (60 by default)
  81523. */
  81524. get: function () {
  81525. return this._targetFrameRate;
  81526. },
  81527. /**
  81528. * Gets or sets the current target frame rate (60 by default)
  81529. */
  81530. set: function (value) {
  81531. this._targetFrameRate = value;
  81532. },
  81533. enumerable: true,
  81534. configurable: true
  81535. });
  81536. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  81537. /**
  81538. * Gets or sets the current interval between two checks (every 2000ms by default)
  81539. */
  81540. get: function () {
  81541. return this._trackerDuration;
  81542. },
  81543. /**
  81544. * Gets or sets the current interval between two checks (every 2000ms by default)
  81545. */
  81546. set: function (value) {
  81547. this._trackerDuration = value;
  81548. },
  81549. enumerable: true,
  81550. configurable: true
  81551. });
  81552. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  81553. /**
  81554. * Gets the list of active optimizations
  81555. */
  81556. get: function () {
  81557. return this._options.optimizations;
  81558. },
  81559. enumerable: true,
  81560. configurable: true
  81561. });
  81562. /**
  81563. * Stops the current optimizer
  81564. */
  81565. SceneOptimizer.prototype.stop = function () {
  81566. this._isRunning = false;
  81567. };
  81568. /**
  81569. * Reset the optimizer to initial step (current priority level = 0)
  81570. */
  81571. SceneOptimizer.prototype.reset = function () {
  81572. this._currentPriorityLevel = 0;
  81573. };
  81574. /**
  81575. * Start the optimizer. By default it will try to reach a specific framerate
  81576. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  81577. */
  81578. SceneOptimizer.prototype.start = function () {
  81579. var _this = this;
  81580. if (this._isRunning) {
  81581. return;
  81582. }
  81583. this._isRunning = true;
  81584. // Let's wait for the scene to be ready before running our check
  81585. this._scene.executeWhenReady(function () {
  81586. setTimeout(function () {
  81587. _this._checkCurrentState();
  81588. }, _this._trackerDuration);
  81589. });
  81590. };
  81591. SceneOptimizer.prototype._checkCurrentState = function () {
  81592. var _this = this;
  81593. if (!this._isRunning) {
  81594. return;
  81595. }
  81596. var scene = this._scene;
  81597. var options = this._options;
  81598. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  81599. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  81600. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  81601. this._isRunning = false;
  81602. this.onSuccessObservable.notifyObservers(this);
  81603. return;
  81604. }
  81605. // Apply current level of optimizations
  81606. var allDone = true;
  81607. var noOptimizationApplied = true;
  81608. for (var index = 0; index < options.optimizations.length; index++) {
  81609. var optimization = options.optimizations[index];
  81610. if (optimization.priority === this._currentPriorityLevel) {
  81611. noOptimizationApplied = false;
  81612. allDone = allDone && optimization.apply(scene, this);
  81613. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  81614. }
  81615. }
  81616. // If no optimization was applied, this is a failure :(
  81617. if (noOptimizationApplied) {
  81618. this._isRunning = false;
  81619. this.onFailureObservable.notifyObservers(this);
  81620. return;
  81621. }
  81622. // If all optimizations were done, move to next level
  81623. if (allDone) {
  81624. this._currentPriorityLevel++;
  81625. }
  81626. // Let's the system running for a specific amount of time before checking FPS
  81627. scene.executeWhenReady(function () {
  81628. setTimeout(function () {
  81629. _this._checkCurrentState();
  81630. }, _this._trackerDuration);
  81631. });
  81632. };
  81633. /**
  81634. * Release all resources
  81635. */
  81636. SceneOptimizer.prototype.dispose = function () {
  81637. this.stop();
  81638. this.onSuccessObservable.clear();
  81639. this.onFailureObservable.clear();
  81640. this.onNewOptimizationAppliedObservable.clear();
  81641. if (this._sceneDisposeObserver) {
  81642. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  81643. }
  81644. };
  81645. /**
  81646. * Helper function to create a SceneOptimizer with one single line of code
  81647. * @param scene defines the scene to work on
  81648. * @param options defines the options to use with the SceneOptimizer
  81649. * @param onSuccess defines a callback to call on success
  81650. * @param onFailure defines a callback to call on failure
  81651. * @returns the new SceneOptimizer object
  81652. */
  81653. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  81654. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  81655. if (onSuccess) {
  81656. optimizer.onSuccessObservable.add(function () {
  81657. onSuccess();
  81658. });
  81659. }
  81660. if (onFailure) {
  81661. optimizer.onFailureObservable.add(function () {
  81662. onFailure();
  81663. });
  81664. }
  81665. optimizer.start();
  81666. return optimizer;
  81667. };
  81668. return SceneOptimizer;
  81669. }());
  81670. BABYLON.SceneOptimizer = SceneOptimizer;
  81671. })(BABYLON || (BABYLON = {}));
  81672. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  81673. var BABYLON;
  81674. (function (BABYLON) {
  81675. var OutlineRenderer = /** @class */ (function () {
  81676. function OutlineRenderer(scene) {
  81677. this.zOffset = 1;
  81678. this._scene = scene;
  81679. }
  81680. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  81681. var _this = this;
  81682. if (useOverlay === void 0) { useOverlay = false; }
  81683. var scene = this._scene;
  81684. var engine = this._scene.getEngine();
  81685. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  81686. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  81687. return;
  81688. }
  81689. var mesh = subMesh.getRenderingMesh();
  81690. var material = subMesh.getMaterial();
  81691. if (!material || !scene.activeCamera) {
  81692. return;
  81693. }
  81694. engine.enableEffect(this._effect);
  81695. // Logarithmic depth
  81696. if (material.useLogarithmicDepth) {
  81697. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  81698. }
  81699. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  81700. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  81701. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  81702. // Bones
  81703. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  81704. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  81705. }
  81706. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  81707. // Alpha test
  81708. if (material && material.needAlphaTesting()) {
  81709. var alphaTexture = material.getAlphaTestTexture();
  81710. if (alphaTexture) {
  81711. this._effect.setTexture("diffuseSampler", alphaTexture);
  81712. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  81713. }
  81714. }
  81715. engine.setZOffset(-this.zOffset);
  81716. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  81717. engine.setZOffset(0);
  81718. };
  81719. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  81720. var defines = [];
  81721. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  81722. var mesh = subMesh.getMesh();
  81723. var material = subMesh.getMaterial();
  81724. if (material) {
  81725. // Alpha test
  81726. if (material.needAlphaTesting()) {
  81727. defines.push("#define ALPHATEST");
  81728. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  81729. attribs.push(BABYLON.VertexBuffer.UVKind);
  81730. defines.push("#define UV1");
  81731. }
  81732. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  81733. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  81734. defines.push("#define UV2");
  81735. }
  81736. }
  81737. //Logarithmic depth
  81738. if (material.useLogarithmicDepth) {
  81739. defines.push("#define LOGARITHMICDEPTH");
  81740. }
  81741. }
  81742. // Bones
  81743. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  81744. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  81745. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  81746. if (mesh.numBoneInfluencers > 4) {
  81747. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  81748. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  81749. }
  81750. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  81751. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  81752. }
  81753. else {
  81754. defines.push("#define NUM_BONE_INFLUENCERS 0");
  81755. }
  81756. // Instances
  81757. if (useInstances) {
  81758. defines.push("#define INSTANCES");
  81759. attribs.push("world0");
  81760. attribs.push("world1");
  81761. attribs.push("world2");
  81762. attribs.push("world3");
  81763. }
  81764. // Get correct effect
  81765. var join = defines.join("\n");
  81766. if (this._cachedDefines !== join) {
  81767. this._cachedDefines = join;
  81768. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  81769. }
  81770. return this._effect.isReady();
  81771. };
  81772. return OutlineRenderer;
  81773. }());
  81774. BABYLON.OutlineRenderer = OutlineRenderer;
  81775. })(BABYLON || (BABYLON = {}));
  81776. //# sourceMappingURL=babylon.outlineRenderer.js.map
  81777. var BABYLON;
  81778. (function (BABYLON) {
  81779. var FaceAdjacencies = /** @class */ (function () {
  81780. function FaceAdjacencies() {
  81781. this.edges = new Array();
  81782. this.edgesConnectedCount = 0;
  81783. }
  81784. return FaceAdjacencies;
  81785. }());
  81786. var EdgesRenderer = /** @class */ (function () {
  81787. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  81788. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  81789. if (epsilon === void 0) { epsilon = 0.95; }
  81790. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  81791. this.edgesWidthScalerForOrthographic = 1000.0;
  81792. this.edgesWidthScalerForPerspective = 50.0;
  81793. this._linesPositions = new Array();
  81794. this._linesNormals = new Array();
  81795. this._linesIndices = new Array();
  81796. this._buffers = {};
  81797. this._checkVerticesInsteadOfIndices = false;
  81798. this._source = source;
  81799. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  81800. this._epsilon = epsilon;
  81801. this._prepareRessources();
  81802. this._generateEdgesLines();
  81803. }
  81804. EdgesRenderer.prototype._prepareRessources = function () {
  81805. if (this._lineShader) {
  81806. return;
  81807. }
  81808. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  81809. attributes: ["position", "normal"],
  81810. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  81811. });
  81812. this._lineShader.disableDepthWrite = true;
  81813. this._lineShader.backFaceCulling = false;
  81814. };
  81815. EdgesRenderer.prototype._rebuild = function () {
  81816. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  81817. if (buffer) {
  81818. buffer._rebuild();
  81819. }
  81820. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  81821. if (buffer) {
  81822. buffer._rebuild();
  81823. }
  81824. var scene = this._source.getScene();
  81825. var engine = scene.getEngine();
  81826. this._ib = engine.createIndexBuffer(this._linesIndices);
  81827. };
  81828. EdgesRenderer.prototype.dispose = function () {
  81829. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  81830. if (buffer) {
  81831. buffer.dispose();
  81832. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  81833. }
  81834. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  81835. if (buffer) {
  81836. buffer.dispose();
  81837. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  81838. }
  81839. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  81840. this._lineShader.dispose();
  81841. };
  81842. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  81843. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  81844. return 0;
  81845. }
  81846. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  81847. return 1;
  81848. }
  81849. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  81850. return 2;
  81851. }
  81852. return -1;
  81853. };
  81854. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  81855. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  81856. return 0;
  81857. }
  81858. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  81859. return 1;
  81860. }
  81861. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  81862. return 2;
  81863. }
  81864. return -1;
  81865. };
  81866. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  81867. var needToCreateLine;
  81868. if (edge === undefined) {
  81869. needToCreateLine = true;
  81870. }
  81871. else {
  81872. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  81873. needToCreateLine = dotProduct < this._epsilon;
  81874. }
  81875. if (needToCreateLine) {
  81876. var offset = this._linesPositions.length / 3;
  81877. var normal = p0.subtract(p1);
  81878. normal.normalize();
  81879. // Positions
  81880. this._linesPositions.push(p0.x);
  81881. this._linesPositions.push(p0.y);
  81882. this._linesPositions.push(p0.z);
  81883. this._linesPositions.push(p0.x);
  81884. this._linesPositions.push(p0.y);
  81885. this._linesPositions.push(p0.z);
  81886. this._linesPositions.push(p1.x);
  81887. this._linesPositions.push(p1.y);
  81888. this._linesPositions.push(p1.z);
  81889. this._linesPositions.push(p1.x);
  81890. this._linesPositions.push(p1.y);
  81891. this._linesPositions.push(p1.z);
  81892. // Normals
  81893. this._linesNormals.push(p1.x);
  81894. this._linesNormals.push(p1.y);
  81895. this._linesNormals.push(p1.z);
  81896. this._linesNormals.push(-1);
  81897. this._linesNormals.push(p1.x);
  81898. this._linesNormals.push(p1.y);
  81899. this._linesNormals.push(p1.z);
  81900. this._linesNormals.push(1);
  81901. this._linesNormals.push(p0.x);
  81902. this._linesNormals.push(p0.y);
  81903. this._linesNormals.push(p0.z);
  81904. this._linesNormals.push(-1);
  81905. this._linesNormals.push(p0.x);
  81906. this._linesNormals.push(p0.y);
  81907. this._linesNormals.push(p0.z);
  81908. this._linesNormals.push(1);
  81909. // Indices
  81910. this._linesIndices.push(offset);
  81911. this._linesIndices.push(offset + 1);
  81912. this._linesIndices.push(offset + 2);
  81913. this._linesIndices.push(offset);
  81914. this._linesIndices.push(offset + 2);
  81915. this._linesIndices.push(offset + 3);
  81916. }
  81917. };
  81918. EdgesRenderer.prototype._generateEdgesLines = function () {
  81919. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  81920. var indices = this._source.getIndices();
  81921. if (!indices || !positions) {
  81922. return;
  81923. }
  81924. // First let's find adjacencies
  81925. var adjacencies = new Array();
  81926. var faceNormals = new Array();
  81927. var index;
  81928. var faceAdjacencies;
  81929. // Prepare faces
  81930. for (index = 0; index < indices.length; index += 3) {
  81931. faceAdjacencies = new FaceAdjacencies();
  81932. var p0Index = indices[index];
  81933. var p1Index = indices[index + 1];
  81934. var p2Index = indices[index + 2];
  81935. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  81936. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  81937. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  81938. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  81939. faceNormal.normalize();
  81940. faceNormals.push(faceNormal);
  81941. adjacencies.push(faceAdjacencies);
  81942. }
  81943. // Scan
  81944. for (index = 0; index < adjacencies.length; index++) {
  81945. faceAdjacencies = adjacencies[index];
  81946. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  81947. var otherFaceAdjacencies = adjacencies[otherIndex];
  81948. if (faceAdjacencies.edgesConnectedCount === 3) {
  81949. break;
  81950. }
  81951. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  81952. continue;
  81953. }
  81954. var otherP0 = indices[otherIndex * 3];
  81955. var otherP1 = indices[otherIndex * 3 + 1];
  81956. var otherP2 = indices[otherIndex * 3 + 2];
  81957. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  81958. var otherEdgeIndex = 0;
  81959. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  81960. continue;
  81961. }
  81962. switch (edgeIndex) {
  81963. case 0:
  81964. if (this._checkVerticesInsteadOfIndices) {
  81965. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  81966. }
  81967. else {
  81968. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  81969. }
  81970. break;
  81971. case 1:
  81972. if (this._checkVerticesInsteadOfIndices) {
  81973. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  81974. }
  81975. else {
  81976. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  81977. }
  81978. break;
  81979. case 2:
  81980. if (this._checkVerticesInsteadOfIndices) {
  81981. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  81982. }
  81983. else {
  81984. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  81985. }
  81986. break;
  81987. }
  81988. if (otherEdgeIndex === -1) {
  81989. continue;
  81990. }
  81991. faceAdjacencies.edges[edgeIndex] = otherIndex;
  81992. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  81993. faceAdjacencies.edgesConnectedCount++;
  81994. otherFaceAdjacencies.edgesConnectedCount++;
  81995. if (faceAdjacencies.edgesConnectedCount === 3) {
  81996. break;
  81997. }
  81998. }
  81999. }
  82000. }
  82001. // Create lines
  82002. for (index = 0; index < adjacencies.length; index++) {
  82003. // 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
  82004. var current = adjacencies[index];
  82005. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  82006. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  82007. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  82008. }
  82009. // Merge into a single mesh
  82010. var engine = this._source.getScene().getEngine();
  82011. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  82012. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  82013. this._ib = engine.createIndexBuffer(this._linesIndices);
  82014. this._indicesCount = this._linesIndices.length;
  82015. };
  82016. EdgesRenderer.prototype.render = function () {
  82017. var scene = this._source.getScene();
  82018. if (!this._lineShader.isReady() || !scene.activeCamera) {
  82019. return;
  82020. }
  82021. var engine = scene.getEngine();
  82022. this._lineShader._preBind();
  82023. // VBOs
  82024. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  82025. scene.resetCachedMaterial();
  82026. this._lineShader.setColor4("color", this._source.edgesColor);
  82027. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  82028. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  82029. }
  82030. else {
  82031. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  82032. }
  82033. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  82034. this._lineShader.bind(this._source.getWorldMatrix());
  82035. // Draw order
  82036. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  82037. this._lineShader.unbind();
  82038. engine.setDepthWrite(true);
  82039. };
  82040. return EdgesRenderer;
  82041. }());
  82042. BABYLON.EdgesRenderer = EdgesRenderer;
  82043. })(BABYLON || (BABYLON = {}));
  82044. //# sourceMappingURL=babylon.edgesRenderer.js.map
  82045. var __assign = (this && this.__assign) || Object.assign || function(t) {
  82046. for (var s, i = 1, n = arguments.length; i < n; i++) {
  82047. s = arguments[i];
  82048. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  82049. t[p] = s[p];
  82050. }
  82051. return t;
  82052. };
  82053. var BABYLON;
  82054. (function (BABYLON) {
  82055. /**
  82056. * The effect layer Helps adding post process effect blended with the main pass.
  82057. *
  82058. * This can be for instance use to generate glow or higlight effects on the scene.
  82059. *
  82060. * The effect layer class can not be used directly and is intented to inherited from to be
  82061. * customized per effects.
  82062. */
  82063. var EffectLayer = /** @class */ (function () {
  82064. /**
  82065. * Instantiates a new effect Layer and references it in the scene.
  82066. * @param name The name of the layer
  82067. * @param scene The scene to use the layer in
  82068. */
  82069. function EffectLayer(
  82070. /** The Friendly of the effect in the scene */
  82071. name, scene) {
  82072. this.name = name;
  82073. this._vertexBuffers = {};
  82074. this._maxSize = 0;
  82075. this._mainTextureDesiredSize = { width: 0, height: 0 };
  82076. this._shouldRender = true;
  82077. this._postProcesses = [];
  82078. this._textures = [];
  82079. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  82080. /**
  82081. * The clear color of the texture used to generate the glow map.
  82082. */
  82083. this.neutralColor = new BABYLON.Color4();
  82084. /**
  82085. * Specifies wether the highlight layer is enabled or not.
  82086. */
  82087. this.isEnabled = true;
  82088. /**
  82089. * An event triggered when the effect layer has been disposed.
  82090. */
  82091. this.onDisposeObservable = new BABYLON.Observable();
  82092. /**
  82093. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  82094. */
  82095. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  82096. /**
  82097. * An event triggered when the generated texture is being merged in the scene.
  82098. */
  82099. this.onBeforeComposeObservable = new BABYLON.Observable();
  82100. /**
  82101. * An event triggered when the generated texture has been merged in the scene.
  82102. */
  82103. this.onAfterComposeObservable = new BABYLON.Observable();
  82104. /**
  82105. * An event triggered when the efffect layer changes its size.
  82106. */
  82107. this.onSizeChangedObservable = new BABYLON.Observable();
  82108. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  82109. this._engine = scene.getEngine();
  82110. this._maxSize = this._engine.getCaps().maxTextureSize;
  82111. this._scene.effectLayers.push(this);
  82112. // Generate Buffers
  82113. this._generateIndexBuffer();
  82114. this._genrateVertexBuffer();
  82115. }
  82116. Object.defineProperty(EffectLayer.prototype, "camera", {
  82117. /**
  82118. * Gets the camera attached to the layer.
  82119. */
  82120. get: function () {
  82121. return this._effectLayerOptions.camera;
  82122. },
  82123. enumerable: true,
  82124. configurable: true
  82125. });
  82126. /**
  82127. * Initializes the effect layer with the required options.
  82128. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  82129. */
  82130. EffectLayer.prototype._init = function (options) {
  82131. // Adapt options
  82132. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  82133. this._setMainTextureSize();
  82134. this._createMainTexture();
  82135. this._createTextureAndPostProcesses();
  82136. this._mergeEffect = this._createMergeEffect();
  82137. };
  82138. /**
  82139. * Generates the index buffer of the full screen quad blending to the main canvas.
  82140. */
  82141. EffectLayer.prototype._generateIndexBuffer = function () {
  82142. // Indices
  82143. var indices = [];
  82144. indices.push(0);
  82145. indices.push(1);
  82146. indices.push(2);
  82147. indices.push(0);
  82148. indices.push(2);
  82149. indices.push(3);
  82150. this._indexBuffer = this._engine.createIndexBuffer(indices);
  82151. };
  82152. /**
  82153. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  82154. */
  82155. EffectLayer.prototype._genrateVertexBuffer = function () {
  82156. // VBO
  82157. var vertices = [];
  82158. vertices.push(1, 1);
  82159. vertices.push(-1, 1);
  82160. vertices.push(-1, -1);
  82161. vertices.push(1, -1);
  82162. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  82163. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  82164. };
  82165. /**
  82166. * Sets the main texture desired size which is the closest power of two
  82167. * of the engine canvas size.
  82168. */
  82169. EffectLayer.prototype._setMainTextureSize = function () {
  82170. if (this._effectLayerOptions.mainTextureFixedSize) {
  82171. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  82172. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  82173. }
  82174. else {
  82175. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  82176. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  82177. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  82178. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  82179. }
  82180. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  82181. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  82182. };
  82183. /**
  82184. * Creates the main texture for the effect layer.
  82185. */
  82186. EffectLayer.prototype._createMainTexture = function () {
  82187. var _this = this;
  82188. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  82189. width: this._mainTextureDesiredSize.width,
  82190. height: this._mainTextureDesiredSize.height
  82191. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  82192. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  82193. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  82194. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  82195. this._mainTexture.anisotropicFilteringLevel = 1;
  82196. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  82197. this._mainTexture.renderParticles = false;
  82198. this._mainTexture.renderList = null;
  82199. this._mainTexture.ignoreCameraViewport = true;
  82200. // Custom render function
  82201. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  82202. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  82203. var index;
  82204. var engine = _this._scene.getEngine();
  82205. if (depthOnlySubMeshes.length) {
  82206. engine.setColorWrite(false);
  82207. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  82208. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  82209. }
  82210. engine.setColorWrite(true);
  82211. }
  82212. for (index = 0; index < opaqueSubMeshes.length; index++) {
  82213. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  82214. }
  82215. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  82216. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  82217. }
  82218. for (index = 0; index < transparentSubMeshes.length; index++) {
  82219. _this._renderSubMesh(transparentSubMeshes.data[index]);
  82220. }
  82221. };
  82222. this._mainTexture.onClearObservable.add(function (engine) {
  82223. engine.clear(_this.neutralColor, true, true, true);
  82224. });
  82225. };
  82226. /**
  82227. * Checks for the readiness of the element composing the layer.
  82228. * @param subMesh the mesh to check for
  82229. * @param useInstances specify wether or not to use instances to render the mesh
  82230. * @param emissiveTexture the associated emissive texture used to generate the glow
  82231. * @return true if ready otherwise, false
  82232. */
  82233. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  82234. var material = subMesh.getMaterial();
  82235. if (!material) {
  82236. return false;
  82237. }
  82238. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  82239. return false;
  82240. }
  82241. var defines = [];
  82242. var attribs = [BABYLON.VertexBuffer.PositionKind];
  82243. var mesh = subMesh.getMesh();
  82244. var uv1 = false;
  82245. var uv2 = false;
  82246. // Alpha test
  82247. if (material && material.needAlphaTesting()) {
  82248. var alphaTexture = material.getAlphaTestTexture();
  82249. if (alphaTexture) {
  82250. defines.push("#define ALPHATEST");
  82251. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  82252. alphaTexture.coordinatesIndex === 1) {
  82253. defines.push("#define DIFFUSEUV2");
  82254. uv2 = true;
  82255. }
  82256. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  82257. defines.push("#define DIFFUSEUV1");
  82258. uv1 = true;
  82259. }
  82260. }
  82261. }
  82262. // Emissive
  82263. if (emissiveTexture) {
  82264. defines.push("#define EMISSIVE");
  82265. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  82266. emissiveTexture.coordinatesIndex === 1) {
  82267. defines.push("#define EMISSIVEUV2");
  82268. uv2 = true;
  82269. }
  82270. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  82271. defines.push("#define EMISSIVEUV1");
  82272. uv1 = true;
  82273. }
  82274. }
  82275. if (uv1) {
  82276. attribs.push(BABYLON.VertexBuffer.UVKind);
  82277. defines.push("#define UV1");
  82278. }
  82279. if (uv2) {
  82280. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  82281. defines.push("#define UV2");
  82282. }
  82283. // Bones
  82284. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  82285. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  82286. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  82287. if (mesh.numBoneInfluencers > 4) {
  82288. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  82289. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  82290. }
  82291. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  82292. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  82293. }
  82294. else {
  82295. defines.push("#define NUM_BONE_INFLUENCERS 0");
  82296. }
  82297. // Instances
  82298. if (useInstances) {
  82299. defines.push("#define INSTANCES");
  82300. attribs.push("world0");
  82301. attribs.push("world1");
  82302. attribs.push("world2");
  82303. attribs.push("world3");
  82304. }
  82305. // Get correct effect
  82306. var join = defines.join("\n");
  82307. if (this._cachedDefines !== join) {
  82308. this._cachedDefines = join;
  82309. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join);
  82310. }
  82311. return this._effectLayerMapGenerationEffect.isReady();
  82312. };
  82313. /**
  82314. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  82315. */
  82316. EffectLayer.prototype.render = function () {
  82317. var currentEffect = this._mergeEffect;
  82318. // Check
  82319. if (!currentEffect.isReady())
  82320. return;
  82321. for (var i = 0; i < this._postProcesses.length; i++) {
  82322. if (!this._postProcesses[i].isReady()) {
  82323. return;
  82324. }
  82325. }
  82326. var engine = this._scene.getEngine();
  82327. this.onBeforeComposeObservable.notifyObservers(this);
  82328. // Render
  82329. engine.enableEffect(currentEffect);
  82330. engine.setState(false);
  82331. // VBOs
  82332. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  82333. // Cache
  82334. var previousAlphaMode = engine.getAlphaMode();
  82335. // Go Blend.
  82336. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  82337. // Blends the map on the main canvas.
  82338. this._internalRender(currentEffect);
  82339. // Restore Alpha
  82340. engine.setAlphaMode(previousAlphaMode);
  82341. this.onAfterComposeObservable.notifyObservers(this);
  82342. // Handle size changes.
  82343. var size = this._mainTexture.getSize();
  82344. this._setMainTextureSize();
  82345. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  82346. // Recreate RTT and post processes on size change.
  82347. this.onSizeChangedObservable.notifyObservers(this);
  82348. this._disposeTextureAndPostProcesses();
  82349. this._createMainTexture();
  82350. this._createTextureAndPostProcesses();
  82351. }
  82352. };
  82353. /**
  82354. * Determine if a given mesh will be used in the current effect.
  82355. * @param mesh mesh to test
  82356. * @returns true if the mesh will be used
  82357. */
  82358. EffectLayer.prototype.hasMesh = function (mesh) {
  82359. return true;
  82360. };
  82361. /**
  82362. * Returns true if the layer contains information to display, otherwise false.
  82363. * @returns true if the glow layer should be rendered
  82364. */
  82365. EffectLayer.prototype.shouldRender = function () {
  82366. return this.isEnabled && this._shouldRender;
  82367. };
  82368. /**
  82369. * Returns true if the mesh should render, otherwise false.
  82370. * @param mesh The mesh to render
  82371. * @returns true if it should render otherwise false
  82372. */
  82373. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  82374. return true;
  82375. };
  82376. /**
  82377. * Returns true if the mesh should render, otherwise false.
  82378. * @param mesh The mesh to render
  82379. * @returns true if it should render otherwise false
  82380. */
  82381. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  82382. return true;
  82383. };
  82384. /**
  82385. * Renders the submesh passed in parameter to the generation map.
  82386. */
  82387. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  82388. var _this = this;
  82389. if (!this.shouldRender()) {
  82390. return;
  82391. }
  82392. var material = subMesh.getMaterial();
  82393. var mesh = subMesh.getRenderingMesh();
  82394. var scene = this._scene;
  82395. var engine = scene.getEngine();
  82396. if (!material) {
  82397. return;
  82398. }
  82399. // Do not block in blend mode.
  82400. if (material.needAlphaBlendingForMesh(mesh)) {
  82401. return;
  82402. }
  82403. // Culling
  82404. engine.setState(material.backFaceCulling);
  82405. // Managing instances
  82406. var batch = mesh._getInstancesRenderList(subMesh._id);
  82407. if (batch.mustReturn) {
  82408. return;
  82409. }
  82410. // Early Exit per mesh
  82411. if (!this._shouldRenderMesh(mesh)) {
  82412. return;
  82413. }
  82414. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  82415. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  82416. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  82417. engine.enableEffect(this._effectLayerMapGenerationEffect);
  82418. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  82419. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  82420. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  82421. // Alpha test
  82422. if (material && material.needAlphaTesting()) {
  82423. var alphaTexture = material.getAlphaTestTexture();
  82424. if (alphaTexture) {
  82425. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  82426. var textureMatrix = alphaTexture.getTextureMatrix();
  82427. if (textureMatrix) {
  82428. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  82429. }
  82430. }
  82431. }
  82432. // Glow emissive only
  82433. if (this._emissiveTextureAndColor.texture) {
  82434. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  82435. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  82436. }
  82437. // Bones
  82438. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  82439. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  82440. }
  82441. // Draw
  82442. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  82443. }
  82444. else {
  82445. // Need to reset refresh rate of the shadowMap
  82446. this._mainTexture.resetRefreshCounter();
  82447. }
  82448. };
  82449. /**
  82450. * Rebuild the required buffers.
  82451. * @ignore Internal use only.
  82452. */
  82453. EffectLayer.prototype._rebuild = function () {
  82454. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  82455. if (vb) {
  82456. vb._rebuild();
  82457. }
  82458. this._generateIndexBuffer();
  82459. };
  82460. /**
  82461. * Dispose only the render target textures and post process.
  82462. */
  82463. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  82464. this._mainTexture.dispose();
  82465. for (var i = 0; i < this._postProcesses.length; i++) {
  82466. if (this._postProcesses[i]) {
  82467. this._postProcesses[i].dispose();
  82468. }
  82469. }
  82470. this._postProcesses = [];
  82471. for (var i = 0; i < this._textures.length; i++) {
  82472. if (this._textures[i]) {
  82473. this._textures[i].dispose();
  82474. }
  82475. }
  82476. this._textures = [];
  82477. };
  82478. /**
  82479. * Dispose the highlight layer and free resources.
  82480. */
  82481. EffectLayer.prototype.dispose = function () {
  82482. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  82483. if (vertexBuffer) {
  82484. vertexBuffer.dispose();
  82485. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  82486. }
  82487. if (this._indexBuffer) {
  82488. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  82489. this._indexBuffer = null;
  82490. }
  82491. // Clean textures and post processes
  82492. this._disposeTextureAndPostProcesses();
  82493. // Remove from scene
  82494. var index = this._scene.effectLayers.indexOf(this, 0);
  82495. if (index > -1) {
  82496. this._scene.effectLayers.splice(index, 1);
  82497. }
  82498. // Callback
  82499. this.onDisposeObservable.notifyObservers(this);
  82500. this.onDisposeObservable.clear();
  82501. this.onBeforeRenderMainTextureObservable.clear();
  82502. this.onBeforeComposeObservable.clear();
  82503. this.onAfterComposeObservable.clear();
  82504. this.onSizeChangedObservable.clear();
  82505. };
  82506. return EffectLayer;
  82507. }());
  82508. BABYLON.EffectLayer = EffectLayer;
  82509. })(BABYLON || (BABYLON = {}));
  82510. //# sourceMappingURL=babylon.effectLayer.js.map
  82511. var BABYLON;
  82512. (function (BABYLON) {
  82513. /**
  82514. * Special Glow Blur post process only blurring the alpha channel
  82515. * It enforces keeping the most luminous color in the color channel.
  82516. */
  82517. var GlowBlurPostProcess = /** @class */ (function (_super) {
  82518. __extends(GlowBlurPostProcess, _super);
  82519. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  82520. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  82521. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  82522. _this.direction = direction;
  82523. _this.kernel = kernel;
  82524. _this.onApplyObservable.add(function (effect) {
  82525. effect.setFloat2("screenSize", _this.width, _this.height);
  82526. effect.setVector2("direction", _this.direction);
  82527. effect.setFloat("blurWidth", _this.kernel);
  82528. });
  82529. return _this;
  82530. }
  82531. return GlowBlurPostProcess;
  82532. }(BABYLON.PostProcess));
  82533. /**
  82534. * The highlight layer Helps adding a glow effect around a mesh.
  82535. *
  82536. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  82537. * glowy meshes to your scene.
  82538. *
  82539. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  82540. */
  82541. var HighlightLayer = /** @class */ (function (_super) {
  82542. __extends(HighlightLayer, _super);
  82543. /**
  82544. * Instantiates a new highlight Layer and references it to the scene..
  82545. * @param name The name of the layer
  82546. * @param scene The scene to use the layer in
  82547. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  82548. */
  82549. function HighlightLayer(name, scene, options) {
  82550. var _this = _super.call(this, name, scene) || this;
  82551. _this.name = name;
  82552. /**
  82553. * Specifies whether or not the inner glow is ACTIVE in the layer.
  82554. */
  82555. _this.innerGlow = true;
  82556. /**
  82557. * Specifies whether or not the outer glow is ACTIVE in the layer.
  82558. */
  82559. _this.outerGlow = true;
  82560. /**
  82561. * An event triggered when the highlight layer is being blurred.
  82562. */
  82563. _this.onBeforeBlurObservable = new BABYLON.Observable();
  82564. /**
  82565. * An event triggered when the highlight layer has been blurred.
  82566. */
  82567. _this.onAfterBlurObservable = new BABYLON.Observable();
  82568. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  82569. _this._meshes = {};
  82570. _this._excludedMeshes = {};
  82571. _this.neutralColor = HighlightLayer.NeutralColor;
  82572. // Warn on stencil
  82573. if (!_this._engine.isStencilEnable) {
  82574. 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 }");
  82575. }
  82576. // Adapt options
  82577. _this._options = __assign({ mainTextureRatio: 0.5, blurTextureSizeRatio: 0.5, blurHorizontalSize: 1.0, blurVerticalSize: 1.0, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  82578. // Initialize the layer
  82579. _this._init({
  82580. alphaBlendingMode: _this._options.alphaBlendingMode,
  82581. camera: _this._options.camera,
  82582. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  82583. mainTextureRatio: _this._options.mainTextureRatio
  82584. });
  82585. return _this;
  82586. }
  82587. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  82588. /**
  82589. * Gets the horizontal size of the blur.
  82590. */
  82591. get: function () {
  82592. return this._horizontalBlurPostprocess.kernel;
  82593. },
  82594. /**
  82595. * Specifies the horizontal size of the blur.
  82596. */
  82597. set: function (value) {
  82598. this._horizontalBlurPostprocess.kernel = value;
  82599. },
  82600. enumerable: true,
  82601. configurable: true
  82602. });
  82603. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  82604. /**
  82605. * Gets the vertical size of the blur.
  82606. */
  82607. get: function () {
  82608. return this._verticalBlurPostprocess.kernel;
  82609. },
  82610. /**
  82611. * Specifies the vertical size of the blur.
  82612. */
  82613. set: function (value) {
  82614. this._verticalBlurPostprocess.kernel = value;
  82615. },
  82616. enumerable: true,
  82617. configurable: true
  82618. });
  82619. /**
  82620. * Get the effect name of the layer.
  82621. * @return The effect name
  82622. */
  82623. HighlightLayer.prototype.getEffectName = function () {
  82624. return HighlightLayer.EffectName;
  82625. };
  82626. /**
  82627. * Create the merge effect. This is the shader use to blit the information back
  82628. * to the main canvas at the end of the scene rendering.
  82629. */
  82630. HighlightLayer.prototype._createMergeEffect = function () {
  82631. // Effect
  82632. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  82633. };
  82634. /**
  82635. * Creates the render target textures and post processes used in the highlight layer.
  82636. */
  82637. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  82638. var _this = this;
  82639. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  82640. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  82641. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  82642. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  82643. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  82644. width: blurTextureWidth,
  82645. height: blurTextureHeight
  82646. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  82647. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  82648. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  82649. this._blurTexture.anisotropicFilteringLevel = 16;
  82650. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  82651. this._blurTexture.renderParticles = false;
  82652. this._blurTexture.ignoreCameraViewport = true;
  82653. this._textures = [this._blurTexture];
  82654. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  82655. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  82656. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  82657. effect.setTexture("textureSampler", _this._mainTexture);
  82658. });
  82659. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  82660. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  82661. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  82662. });
  82663. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  82664. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  82665. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  82666. });
  82667. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  82668. }
  82669. else {
  82670. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  82671. width: blurTextureWidth,
  82672. height: blurTextureHeight
  82673. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  82674. this._horizontalBlurPostprocess.width = blurTextureWidth;
  82675. this._horizontalBlurPostprocess.height = blurTextureHeight;
  82676. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  82677. effect.setTexture("textureSampler", _this._mainTexture);
  82678. });
  82679. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  82680. width: blurTextureWidth,
  82681. height: blurTextureHeight
  82682. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  82683. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  82684. }
  82685. this._mainTexture.onAfterUnbindObservable.add(function () {
  82686. _this.onBeforeBlurObservable.notifyObservers(_this);
  82687. var internalTexture = _this._blurTexture.getInternalTexture();
  82688. if (internalTexture) {
  82689. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  82690. }
  82691. _this.onAfterBlurObservable.notifyObservers(_this);
  82692. });
  82693. // Prevent autoClear.
  82694. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  82695. };
  82696. /**
  82697. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  82698. */
  82699. HighlightLayer.prototype.needStencil = function () {
  82700. return true;
  82701. };
  82702. /**
  82703. * Checks for the readiness of the element composing the layer.
  82704. * @param subMesh the mesh to check for
  82705. * @param useInstances specify wether or not to use instances to render the mesh
  82706. * @param emissiveTexture the associated emissive texture used to generate the glow
  82707. * @return true if ready otherwise, false
  82708. */
  82709. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  82710. var material = subMesh.getMaterial();
  82711. var mesh = subMesh.getRenderingMesh();
  82712. if (!material || !mesh || !this._meshes) {
  82713. return false;
  82714. }
  82715. var emissiveTexture = null;
  82716. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  82717. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  82718. emissiveTexture = material.emissiveTexture;
  82719. }
  82720. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  82721. };
  82722. /**
  82723. * Implementation specific of rendering the generating effect on the main canvas.
  82724. * @param effect The effect used to render through
  82725. */
  82726. HighlightLayer.prototype._internalRender = function (effect) {
  82727. // Texture
  82728. effect.setTexture("textureSampler", this._blurTexture);
  82729. // Cache
  82730. var engine = this._engine;
  82731. var previousStencilBuffer = engine.getStencilBuffer();
  82732. var previousStencilFunction = engine.getStencilFunction();
  82733. var previousStencilMask = engine.getStencilMask();
  82734. var previousStencilOperationPass = engine.getStencilOperationPass();
  82735. var previousStencilOperationFail = engine.getStencilOperationFail();
  82736. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  82737. // Stencil operations
  82738. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  82739. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  82740. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  82741. // Draw order
  82742. engine.setStencilMask(0x00);
  82743. engine.setStencilBuffer(true);
  82744. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  82745. // 2 passes inner outer
  82746. if (this.outerGlow) {
  82747. effect.setFloat("offset", 0);
  82748. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  82749. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  82750. }
  82751. if (this.innerGlow) {
  82752. effect.setFloat("offset", 1);
  82753. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  82754. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  82755. }
  82756. // Restore Cache
  82757. engine.setStencilFunction(previousStencilFunction);
  82758. engine.setStencilMask(previousStencilMask);
  82759. engine.setStencilBuffer(previousStencilBuffer);
  82760. engine.setStencilOperationPass(previousStencilOperationPass);
  82761. engine.setStencilOperationFail(previousStencilOperationFail);
  82762. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  82763. };
  82764. /**
  82765. * Returns true if the layer contains information to display, otherwise false.
  82766. */
  82767. HighlightLayer.prototype.shouldRender = function () {
  82768. if (_super.prototype.shouldRender.call(this)) {
  82769. return this._meshes ? true : false;
  82770. }
  82771. return false;
  82772. };
  82773. /**
  82774. * Returns true if the mesh should render, otherwise false.
  82775. * @param mesh The mesh to render
  82776. * @returns true if it should render otherwise false
  82777. */
  82778. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  82779. // Excluded Mesh
  82780. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  82781. return false;
  82782. }
  82783. ;
  82784. return true;
  82785. };
  82786. /**
  82787. * Sets the required values for both the emissive texture and and the main color.
  82788. */
  82789. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  82790. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  82791. if (highlightLayerMesh) {
  82792. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  82793. }
  82794. else {
  82795. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  82796. }
  82797. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  82798. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  82799. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  82800. }
  82801. else {
  82802. this._emissiveTextureAndColor.texture = null;
  82803. }
  82804. };
  82805. /**
  82806. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  82807. * @param mesh The mesh to exclude from the highlight layer
  82808. */
  82809. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  82810. if (!this._excludedMeshes) {
  82811. return;
  82812. }
  82813. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  82814. if (!meshExcluded) {
  82815. this._excludedMeshes[mesh.uniqueId] = {
  82816. mesh: mesh,
  82817. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  82818. mesh.getEngine().setStencilBuffer(false);
  82819. }),
  82820. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  82821. mesh.getEngine().setStencilBuffer(true);
  82822. }),
  82823. };
  82824. }
  82825. };
  82826. /**
  82827. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  82828. * @param mesh The mesh to highlight
  82829. */
  82830. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  82831. if (!this._excludedMeshes) {
  82832. return;
  82833. }
  82834. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  82835. if (meshExcluded) {
  82836. if (meshExcluded.beforeRender) {
  82837. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  82838. }
  82839. if (meshExcluded.afterRender) {
  82840. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  82841. }
  82842. }
  82843. this._excludedMeshes[mesh.uniqueId] = null;
  82844. };
  82845. /**
  82846. * Determine if a given mesh will be highlighted by the current HighlightLayer
  82847. * @param mesh mesh to test
  82848. * @returns true if the mesh will be highlighted by the current HighlightLayer
  82849. */
  82850. HighlightLayer.prototype.hasMesh = function (mesh) {
  82851. if (!this._meshes) {
  82852. return false;
  82853. }
  82854. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  82855. };
  82856. /**
  82857. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  82858. * @param mesh The mesh to highlight
  82859. * @param color The color of the highlight
  82860. * @param glowEmissiveOnly Extract the glow from the emissive texture
  82861. */
  82862. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  82863. var _this = this;
  82864. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  82865. if (!this._meshes) {
  82866. return;
  82867. }
  82868. var meshHighlight = this._meshes[mesh.uniqueId];
  82869. if (meshHighlight) {
  82870. meshHighlight.color = color;
  82871. }
  82872. else {
  82873. this._meshes[mesh.uniqueId] = {
  82874. mesh: mesh,
  82875. color: color,
  82876. // Lambda required for capture due to Observable this context
  82877. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  82878. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  82879. _this._defaultStencilReference(mesh);
  82880. }
  82881. else {
  82882. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  82883. }
  82884. }),
  82885. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  82886. glowEmissiveOnly: glowEmissiveOnly
  82887. };
  82888. }
  82889. this._shouldRender = true;
  82890. };
  82891. /**
  82892. * Remove a mesh from the highlight layer in order to make it stop glowing.
  82893. * @param mesh The mesh to highlight
  82894. */
  82895. HighlightLayer.prototype.removeMesh = function (mesh) {
  82896. if (!this._meshes) {
  82897. return;
  82898. }
  82899. var meshHighlight = this._meshes[mesh.uniqueId];
  82900. if (meshHighlight) {
  82901. if (meshHighlight.observerHighlight) {
  82902. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  82903. }
  82904. if (meshHighlight.observerDefault) {
  82905. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  82906. }
  82907. delete this._meshes[mesh.uniqueId];
  82908. }
  82909. this._shouldRender = false;
  82910. for (var meshHighlightToCheck in this._meshes) {
  82911. if (this._meshes[meshHighlightToCheck]) {
  82912. this._shouldRender = true;
  82913. break;
  82914. }
  82915. }
  82916. };
  82917. /**
  82918. * Force the stencil to the normal expected value for none glowing parts
  82919. */
  82920. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  82921. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  82922. };
  82923. /**
  82924. * Free any resources and references associated to a mesh.
  82925. * Internal use
  82926. * @param mesh The mesh to free.
  82927. */
  82928. HighlightLayer.prototype._disposeMesh = function (mesh) {
  82929. this.removeMesh(mesh);
  82930. this.removeExcludedMesh(mesh);
  82931. };
  82932. /**
  82933. * Dispose the highlight layer and free resources.
  82934. */
  82935. HighlightLayer.prototype.dispose = function () {
  82936. if (this._meshes) {
  82937. // Clean mesh references
  82938. for (var id in this._meshes) {
  82939. var meshHighlight = this._meshes[id];
  82940. if (meshHighlight && meshHighlight.mesh) {
  82941. if (meshHighlight.observerHighlight) {
  82942. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  82943. }
  82944. if (meshHighlight.observerDefault) {
  82945. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  82946. }
  82947. }
  82948. }
  82949. this._meshes = null;
  82950. }
  82951. if (this._excludedMeshes) {
  82952. for (var id in this._excludedMeshes) {
  82953. var meshHighlight = this._excludedMeshes[id];
  82954. if (meshHighlight) {
  82955. if (meshHighlight.beforeRender) {
  82956. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  82957. }
  82958. if (meshHighlight.afterRender) {
  82959. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  82960. }
  82961. }
  82962. }
  82963. this._excludedMeshes = null;
  82964. }
  82965. _super.prototype.dispose.call(this);
  82966. };
  82967. /**
  82968. * Effect Name of the highlight layer.
  82969. */
  82970. HighlightLayer.EffectName = "HighlightLayer";
  82971. /**
  82972. * The neutral color used during the preparation of the glow effect.
  82973. * This is black by default as the blend operation is a blend operation.
  82974. */
  82975. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  82976. /**
  82977. * Stencil value used for glowing meshes.
  82978. */
  82979. HighlightLayer.GlowingMeshStencilReference = 0x02;
  82980. /**
  82981. * Stencil value used for the other meshes in the scene.
  82982. */
  82983. HighlightLayer.NormalMeshStencilReference = 0x01;
  82984. return HighlightLayer;
  82985. }(BABYLON.EffectLayer));
  82986. BABYLON.HighlightLayer = HighlightLayer;
  82987. })(BABYLON || (BABYLON = {}));
  82988. //# sourceMappingURL=babylon.highlightLayer.js.map
  82989. var BABYLON;
  82990. (function (BABYLON) {
  82991. /**
  82992. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  82993. *
  82994. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  82995. * glowy meshes to your scene.
  82996. *
  82997. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  82998. */
  82999. var GlowLayer = /** @class */ (function (_super) {
  83000. __extends(GlowLayer, _super);
  83001. /**
  83002. * Instantiates a new glow Layer and references it to the scene.
  83003. * @param name The name of the layer
  83004. * @param scene The scene to use the layer in
  83005. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  83006. */
  83007. function GlowLayer(name, scene, options) {
  83008. var _this = _super.call(this, name, scene) || this;
  83009. _this.name = name;
  83010. _this._intensity = 1.0;
  83011. _this._includedOnlyMeshes = [];
  83012. _this._excludedMeshes = [];
  83013. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  83014. // Adapt options
  83015. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1 }, options);
  83016. // Initialize the layer
  83017. _this._init({
  83018. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  83019. camera: _this._options.camera,
  83020. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  83021. mainTextureRatio: _this._options.mainTextureRatio
  83022. });
  83023. return _this;
  83024. }
  83025. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  83026. /**
  83027. * Gets the kernel size of the blur.
  83028. */
  83029. get: function () {
  83030. return this._horizontalBlurPostprocess1.kernel;
  83031. },
  83032. /**
  83033. * Sets the kernel size of the blur.
  83034. */
  83035. set: function (value) {
  83036. this._horizontalBlurPostprocess1.kernel = value;
  83037. this._verticalBlurPostprocess1.kernel = value;
  83038. this._horizontalBlurPostprocess2.kernel = value;
  83039. this._verticalBlurPostprocess2.kernel = value;
  83040. },
  83041. enumerable: true,
  83042. configurable: true
  83043. });
  83044. Object.defineProperty(GlowLayer.prototype, "intensity", {
  83045. /**
  83046. * Gets the glow intensity.
  83047. */
  83048. get: function () {
  83049. return this._intensity;
  83050. },
  83051. /**
  83052. * Sets the glow intensity.
  83053. */
  83054. set: function (value) {
  83055. this._intensity = value;
  83056. },
  83057. enumerable: true,
  83058. configurable: true
  83059. });
  83060. /**
  83061. * Get the effect name of the layer.
  83062. * @return The effect name
  83063. */
  83064. GlowLayer.prototype.getEffectName = function () {
  83065. return GlowLayer.EffectName;
  83066. };
  83067. /**
  83068. * Create the merge effect. This is the shader use to blit the information back
  83069. * to the main canvas at the end of the scene rendering.
  83070. */
  83071. GlowLayer.prototype._createMergeEffect = function () {
  83072. // Effect
  83073. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  83074. };
  83075. /**
  83076. * Creates the render target textures and post processes used in the glow layer.
  83077. */
  83078. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  83079. var _this = this;
  83080. var blurTextureWidth = this._mainTextureDesiredSize.width;
  83081. var blurTextureHeight = this._mainTextureDesiredSize.height;
  83082. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  83083. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  83084. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  83085. width: blurTextureWidth,
  83086. height: blurTextureHeight
  83087. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  83088. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  83089. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  83090. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  83091. this._blurTexture1.renderParticles = false;
  83092. this._blurTexture1.ignoreCameraViewport = true;
  83093. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  83094. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  83095. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  83096. width: blurTextureWidth2,
  83097. height: blurTextureHeight2
  83098. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  83099. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  83100. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  83101. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  83102. this._blurTexture2.renderParticles = false;
  83103. this._blurTexture2.ignoreCameraViewport = true;
  83104. this._textures = [this._blurTexture1, this._blurTexture2];
  83105. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  83106. width: blurTextureWidth,
  83107. height: blurTextureHeight
  83108. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  83109. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  83110. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  83111. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  83112. effect.setTexture("textureSampler", _this._mainTexture);
  83113. });
  83114. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  83115. width: blurTextureWidth,
  83116. height: blurTextureHeight
  83117. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  83118. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  83119. width: blurTextureWidth2,
  83120. height: blurTextureHeight2
  83121. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  83122. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  83123. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  83124. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  83125. effect.setTexture("textureSampler", _this._blurTexture1);
  83126. });
  83127. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  83128. width: blurTextureWidth2,
  83129. height: blurTextureHeight2
  83130. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  83131. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  83132. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  83133. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  83134. this._mainTexture.samples = this._options.mainTextureSamples;
  83135. this._mainTexture.onAfterUnbindObservable.add(function () {
  83136. var internalTexture = _this._blurTexture1.getInternalTexture();
  83137. if (internalTexture) {
  83138. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  83139. internalTexture = _this._blurTexture2.getInternalTexture();
  83140. if (internalTexture) {
  83141. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  83142. }
  83143. }
  83144. });
  83145. // Prevent autoClear.
  83146. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  83147. };
  83148. /**
  83149. * Checks for the readiness of the element composing the layer.
  83150. * @param subMesh the mesh to check for
  83151. * @param useInstances specify wether or not to use instances to render the mesh
  83152. * @param emissiveTexture the associated emissive texture used to generate the glow
  83153. * @return true if ready otherwise, false
  83154. */
  83155. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  83156. var material = subMesh.getMaterial();
  83157. var mesh = subMesh.getRenderingMesh();
  83158. if (!material || !mesh) {
  83159. return false;
  83160. }
  83161. var emissiveTexture = material.emissiveTexture;
  83162. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  83163. };
  83164. /**
  83165. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  83166. */
  83167. GlowLayer.prototype.needStencil = function () {
  83168. return false;
  83169. };
  83170. /**
  83171. * Implementation specific of rendering the generating effect on the main canvas.
  83172. * @param effect The effect used to render through
  83173. */
  83174. GlowLayer.prototype._internalRender = function (effect) {
  83175. // Texture
  83176. effect.setTexture("textureSampler", this._blurTexture1);
  83177. effect.setTexture("textureSampler2", this._blurTexture2);
  83178. effect.setFloat("offset", this._intensity);
  83179. // Cache
  83180. var engine = this._engine;
  83181. var previousStencilBuffer = engine.getStencilBuffer();
  83182. // Draw order
  83183. engine.setStencilBuffer(false);
  83184. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  83185. // Draw order
  83186. engine.setStencilBuffer(previousStencilBuffer);
  83187. };
  83188. /**
  83189. * Sets the required values for both the emissive texture and and the main color.
  83190. */
  83191. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  83192. var textureLevel = 1.0;
  83193. if (material) {
  83194. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  83195. if (this._emissiveTextureAndColor.texture) {
  83196. textureLevel = this._emissiveTextureAndColor.texture.level;
  83197. }
  83198. }
  83199. else {
  83200. this._emissiveTextureAndColor.texture = null;
  83201. }
  83202. if (material.emissiveColor) {
  83203. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  83204. }
  83205. else {
  83206. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  83207. }
  83208. };
  83209. /**
  83210. * Returns true if the mesh should render, otherwise false.
  83211. * @param mesh The mesh to render
  83212. * @returns true if it should render otherwise false
  83213. */
  83214. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  83215. return this.hasMesh(mesh);
  83216. };
  83217. /**
  83218. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  83219. * @param mesh The mesh to exclude from the glow layer
  83220. */
  83221. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  83222. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  83223. this._excludedMeshes.push(mesh.uniqueId);
  83224. }
  83225. };
  83226. /**
  83227. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  83228. * @param mesh The mesh to remove
  83229. */
  83230. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  83231. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  83232. if (index !== -1) {
  83233. this._excludedMeshes.splice(index, 1);
  83234. }
  83235. };
  83236. /**
  83237. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  83238. * @param mesh The mesh to include in the glow layer
  83239. */
  83240. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  83241. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  83242. this._includedOnlyMeshes.push(mesh.uniqueId);
  83243. }
  83244. };
  83245. /**
  83246. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  83247. * @param mesh The mesh to remove
  83248. */
  83249. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  83250. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  83251. if (index !== -1) {
  83252. this._includedOnlyMeshes.splice(index, 1);
  83253. }
  83254. };
  83255. /**
  83256. * Determine if a given mesh will be used in the glow layer
  83257. * @param mesh The mesh to test
  83258. * @returns true if the mesh will be highlighted by the current glow layer
  83259. */
  83260. GlowLayer.prototype.hasMesh = function (mesh) {
  83261. // Included Mesh
  83262. if (this._includedOnlyMeshes.length) {
  83263. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  83264. }
  83265. ;
  83266. // Excluded Mesh
  83267. if (this._excludedMeshes.length) {
  83268. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  83269. }
  83270. ;
  83271. return true;
  83272. };
  83273. /**
  83274. * Free any resources and references associated to a mesh.
  83275. * Internal use
  83276. * @param mesh The mesh to free.
  83277. */
  83278. GlowLayer.prototype._disposeMesh = function (mesh) {
  83279. this.removeIncludedOnlyMesh(mesh);
  83280. this.removeExcludedMesh(mesh);
  83281. };
  83282. /**
  83283. * Effect Name of the layer.
  83284. */
  83285. GlowLayer.EffectName = "GlowLayer";
  83286. /**
  83287. * The default blur kernel size used for the glow.
  83288. */
  83289. GlowLayer.DefaultBlurKernelSize = 32;
  83290. /**
  83291. * The default texture size ratio used for the glow.
  83292. */
  83293. GlowLayer.DefaultTextureRatio = 0.5;
  83294. return GlowLayer;
  83295. }(BABYLON.EffectLayer));
  83296. BABYLON.GlowLayer = GlowLayer;
  83297. })(BABYLON || (BABYLON = {}));
  83298. //# sourceMappingURL=babylon.glowLayer.js.map
  83299. var BABYLON;
  83300. (function (BABYLON) {
  83301. /**
  83302. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  83303. */
  83304. var AssetTaskState;
  83305. (function (AssetTaskState) {
  83306. /**
  83307. * Initialization
  83308. */
  83309. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  83310. /**
  83311. * Running
  83312. */
  83313. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  83314. /**
  83315. * Done
  83316. */
  83317. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  83318. /**
  83319. * Error
  83320. */
  83321. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  83322. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  83323. /**
  83324. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  83325. */
  83326. var AbstractAssetTask = /** @class */ (function () {
  83327. /**
  83328. * Creates a new {BABYLON.AssetsManager}
  83329. * @param name defines the name of the task
  83330. */
  83331. function AbstractAssetTask(
  83332. /**
  83333. * Task name
  83334. */ name) {
  83335. this.name = name;
  83336. this._isCompleted = false;
  83337. this._taskState = AssetTaskState.INIT;
  83338. }
  83339. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  83340. /**
  83341. * Get if the task is completed
  83342. */
  83343. get: function () {
  83344. return this._isCompleted;
  83345. },
  83346. enumerable: true,
  83347. configurable: true
  83348. });
  83349. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  83350. /**
  83351. * Gets the current state of the task
  83352. */
  83353. get: function () {
  83354. return this._taskState;
  83355. },
  83356. enumerable: true,
  83357. configurable: true
  83358. });
  83359. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  83360. /**
  83361. * Gets the current error object (if task is in error)
  83362. */
  83363. get: function () {
  83364. return this._errorObject;
  83365. },
  83366. enumerable: true,
  83367. configurable: true
  83368. });
  83369. /**
  83370. * Internal only
  83371. * @ignore
  83372. */
  83373. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  83374. if (this._errorObject) {
  83375. return;
  83376. }
  83377. this._errorObject = {
  83378. message: message,
  83379. exception: exception
  83380. };
  83381. };
  83382. /**
  83383. * Execute the current task
  83384. * @param scene defines the scene where you want your assets to be loaded
  83385. * @param onSuccess is a callback called when the task is successfully executed
  83386. * @param onError is a callback called if an error occurs
  83387. */
  83388. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  83389. var _this = this;
  83390. this._taskState = AssetTaskState.RUNNING;
  83391. this.runTask(scene, function () {
  83392. _this.onDoneCallback(onSuccess, onError);
  83393. }, function (msg, exception) {
  83394. _this.onErrorCallback(onError, msg, exception);
  83395. });
  83396. };
  83397. /**
  83398. * Execute the current task
  83399. * @param scene defines the scene where you want your assets to be loaded
  83400. * @param onSuccess is a callback called when the task is successfully executed
  83401. * @param onError is a callback called if an error occurs
  83402. */
  83403. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  83404. throw new Error("runTask is not implemented");
  83405. };
  83406. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  83407. this._taskState = AssetTaskState.ERROR;
  83408. this._errorObject = {
  83409. message: message,
  83410. exception: exception
  83411. };
  83412. if (this.onError) {
  83413. this.onError(this, message, exception);
  83414. }
  83415. onError();
  83416. };
  83417. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  83418. try {
  83419. this._taskState = AssetTaskState.DONE;
  83420. this._isCompleted = true;
  83421. if (this.onSuccess) {
  83422. this.onSuccess(this);
  83423. }
  83424. onSuccess();
  83425. }
  83426. catch (e) {
  83427. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  83428. }
  83429. };
  83430. return AbstractAssetTask;
  83431. }());
  83432. BABYLON.AbstractAssetTask = AbstractAssetTask;
  83433. /**
  83434. * Class used to share progress information about assets loading
  83435. */
  83436. var AssetsProgressEvent = /** @class */ (function () {
  83437. /**
  83438. * Creates a {BABYLON.AssetsProgressEvent}
  83439. * @param remainingCount defines the number of remaining tasks to process
  83440. * @param totalCount defines the total number of tasks
  83441. * @param task defines the task that was just processed
  83442. */
  83443. function AssetsProgressEvent(remainingCount, totalCount, task) {
  83444. this.remainingCount = remainingCount;
  83445. this.totalCount = totalCount;
  83446. this.task = task;
  83447. }
  83448. return AssetsProgressEvent;
  83449. }());
  83450. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  83451. /**
  83452. * Define a task used by {BABYLON.AssetsManager} to load meshes
  83453. */
  83454. var MeshAssetTask = /** @class */ (function (_super) {
  83455. __extends(MeshAssetTask, _super);
  83456. /**
  83457. * Creates a new {BABYLON.MeshAssetTask}
  83458. * @param name defines the name of the task
  83459. * @param meshesNames defines the list of mesh's names you want to load
  83460. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  83461. * @param sceneFilename defines the filename of the scene to load from
  83462. */
  83463. function MeshAssetTask(
  83464. /**
  83465. * Defines the name of the task
  83466. */
  83467. name,
  83468. /**
  83469. * Defines the list of mesh's names you want to load
  83470. */
  83471. meshesNames,
  83472. /**
  83473. * Defines the root url to use as a base to load your meshes and associated resources
  83474. */
  83475. rootUrl,
  83476. /**
  83477. * Defines the filename of the scene to load from
  83478. */
  83479. sceneFilename) {
  83480. var _this = _super.call(this, name) || this;
  83481. _this.name = name;
  83482. _this.meshesNames = meshesNames;
  83483. _this.rootUrl = rootUrl;
  83484. _this.sceneFilename = sceneFilename;
  83485. return _this;
  83486. }
  83487. /**
  83488. * Execute the current task
  83489. * @param scene defines the scene where you want your assets to be loaded
  83490. * @param onSuccess is a callback called when the task is successfully executed
  83491. * @param onError is a callback called if an error occurs
  83492. */
  83493. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  83494. var _this = this;
  83495. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  83496. _this.loadedMeshes = meshes;
  83497. _this.loadedParticleSystems = particleSystems;
  83498. _this.loadedSkeletons = skeletons;
  83499. onSuccess();
  83500. }, null, function (scene, message, exception) {
  83501. onError(message, exception);
  83502. });
  83503. };
  83504. return MeshAssetTask;
  83505. }(AbstractAssetTask));
  83506. BABYLON.MeshAssetTask = MeshAssetTask;
  83507. /**
  83508. * Define a task used by {BABYLON.AssetsManager} to load text content
  83509. */
  83510. var TextFileAssetTask = /** @class */ (function (_super) {
  83511. __extends(TextFileAssetTask, _super);
  83512. /**
  83513. * Creates a new TextFileAssetTask object
  83514. * @param name defines the name of the task
  83515. * @param url defines the location of the file to load
  83516. */
  83517. function TextFileAssetTask(
  83518. /**
  83519. * Defines the name of the task
  83520. */
  83521. name,
  83522. /**
  83523. * Defines the location of the file to load
  83524. */
  83525. url) {
  83526. var _this = _super.call(this, name) || this;
  83527. _this.name = name;
  83528. _this.url = url;
  83529. return _this;
  83530. }
  83531. /**
  83532. * Execute the current task
  83533. * @param scene defines the scene where you want your assets to be loaded
  83534. * @param onSuccess is a callback called when the task is successfully executed
  83535. * @param onError is a callback called if an error occurs
  83536. */
  83537. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  83538. var _this = this;
  83539. scene._loadFile(this.url, function (data) {
  83540. _this.text = data;
  83541. onSuccess();
  83542. }, undefined, false, true, function (request, exception) {
  83543. if (request) {
  83544. onError(request.status + " " + request.statusText, exception);
  83545. }
  83546. });
  83547. };
  83548. return TextFileAssetTask;
  83549. }(AbstractAssetTask));
  83550. BABYLON.TextFileAssetTask = TextFileAssetTask;
  83551. /**
  83552. * Define a task used by {BABYLON.AssetsManager} to load binary data
  83553. */
  83554. var BinaryFileAssetTask = /** @class */ (function (_super) {
  83555. __extends(BinaryFileAssetTask, _super);
  83556. /**
  83557. * Creates a new BinaryFileAssetTask object
  83558. * @param name defines the name of the new task
  83559. * @param url defines the location of the file to load
  83560. */
  83561. function BinaryFileAssetTask(
  83562. /**
  83563. * Defines the name of the task
  83564. */
  83565. name,
  83566. /**
  83567. * Defines the location of the file to load
  83568. */
  83569. url) {
  83570. var _this = _super.call(this, name) || this;
  83571. _this.name = name;
  83572. _this.url = url;
  83573. return _this;
  83574. }
  83575. /**
  83576. * Execute the current task
  83577. * @param scene defines the scene where you want your assets to be loaded
  83578. * @param onSuccess is a callback called when the task is successfully executed
  83579. * @param onError is a callback called if an error occurs
  83580. */
  83581. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  83582. var _this = this;
  83583. scene._loadFile(this.url, function (data) {
  83584. _this.data = data;
  83585. onSuccess();
  83586. }, undefined, true, true, function (request, exception) {
  83587. if (request) {
  83588. onError(request.status + " " + request.statusText, exception);
  83589. }
  83590. });
  83591. };
  83592. return BinaryFileAssetTask;
  83593. }(AbstractAssetTask));
  83594. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  83595. /**
  83596. * Define a task used by {BABYLON.AssetsManager} to load images
  83597. */
  83598. var ImageAssetTask = /** @class */ (function (_super) {
  83599. __extends(ImageAssetTask, _super);
  83600. /**
  83601. * Creates a new ImageAssetTask
  83602. * @param name defines the name of the task
  83603. * @param url defines the location of the image to load
  83604. */
  83605. function ImageAssetTask(
  83606. /**
  83607. * Defines the name of the task
  83608. */
  83609. name,
  83610. /**
  83611. * Defines the location of the image to load
  83612. */
  83613. url) {
  83614. var _this = _super.call(this, name) || this;
  83615. _this.name = name;
  83616. _this.url = url;
  83617. return _this;
  83618. }
  83619. /**
  83620. * Execute the current task
  83621. * @param scene defines the scene where you want your assets to be loaded
  83622. * @param onSuccess is a callback called when the task is successfully executed
  83623. * @param onError is a callback called if an error occurs
  83624. */
  83625. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  83626. var _this = this;
  83627. var img = new Image();
  83628. BABYLON.Tools.SetCorsBehavior(this.url, img);
  83629. img.onload = function () {
  83630. _this.image = img;
  83631. onSuccess();
  83632. };
  83633. img.onerror = function (err) {
  83634. onError("Error loading image", err);
  83635. };
  83636. img.src = this.url;
  83637. };
  83638. return ImageAssetTask;
  83639. }(AbstractAssetTask));
  83640. BABYLON.ImageAssetTask = ImageAssetTask;
  83641. /**
  83642. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  83643. */
  83644. var TextureAssetTask = /** @class */ (function (_super) {
  83645. __extends(TextureAssetTask, _super);
  83646. /**
  83647. * Creates a new TextureAssetTask object
  83648. * @param name defines the name of the task
  83649. * @param url defines the location of the file to load
  83650. * @param noMipmap defines if mipmap should not be generated (default is false)
  83651. * @param invertY defines if texture must be inverted on Y axis (default is false)
  83652. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  83653. */
  83654. function TextureAssetTask(
  83655. /**
  83656. * Defines the name of the task
  83657. */
  83658. name,
  83659. /**
  83660. * Defines the location of the file to load
  83661. */
  83662. url,
  83663. /**
  83664. * Defines if mipmap should not be generated (default is false)
  83665. */
  83666. noMipmap,
  83667. /**
  83668. * Defines if texture must be inverted on Y axis (default is false)
  83669. */
  83670. invertY,
  83671. /**
  83672. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  83673. */
  83674. samplingMode) {
  83675. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  83676. var _this = _super.call(this, name) || this;
  83677. _this.name = name;
  83678. _this.url = url;
  83679. _this.noMipmap = noMipmap;
  83680. _this.invertY = invertY;
  83681. _this.samplingMode = samplingMode;
  83682. return _this;
  83683. }
  83684. /**
  83685. * Execute the current task
  83686. * @param scene defines the scene where you want your assets to be loaded
  83687. * @param onSuccess is a callback called when the task is successfully executed
  83688. * @param onError is a callback called if an error occurs
  83689. */
  83690. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  83691. var onload = function () {
  83692. onSuccess();
  83693. };
  83694. var onerror = function (message, exception) {
  83695. onError(message, exception);
  83696. };
  83697. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  83698. };
  83699. return TextureAssetTask;
  83700. }(AbstractAssetTask));
  83701. BABYLON.TextureAssetTask = TextureAssetTask;
  83702. /**
  83703. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  83704. */
  83705. var CubeTextureAssetTask = /** @class */ (function (_super) {
  83706. __extends(CubeTextureAssetTask, _super);
  83707. /**
  83708. * Creates a new CubeTextureAssetTask
  83709. * @param name defines the name of the task
  83710. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  83711. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  83712. * @param noMipmap defines if mipmaps should not be generated (default is false)
  83713. * @param files defines the explicit list of files (undefined by default)
  83714. */
  83715. function CubeTextureAssetTask(
  83716. /**
  83717. * Defines the name of the task
  83718. */
  83719. name,
  83720. /**
  83721. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  83722. */
  83723. url,
  83724. /**
  83725. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  83726. */
  83727. extensions,
  83728. /**
  83729. * Defines if mipmaps should not be generated (default is false)
  83730. */
  83731. noMipmap,
  83732. /**
  83733. * Defines the explicit list of files (undefined by default)
  83734. */
  83735. files) {
  83736. var _this = _super.call(this, name) || this;
  83737. _this.name = name;
  83738. _this.url = url;
  83739. _this.extensions = extensions;
  83740. _this.noMipmap = noMipmap;
  83741. _this.files = files;
  83742. return _this;
  83743. }
  83744. /**
  83745. * Execute the current task
  83746. * @param scene defines the scene where you want your assets to be loaded
  83747. * @param onSuccess is a callback called when the task is successfully executed
  83748. * @param onError is a callback called if an error occurs
  83749. */
  83750. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  83751. var onload = function () {
  83752. onSuccess();
  83753. };
  83754. var onerror = function (message, exception) {
  83755. onError(message, exception);
  83756. };
  83757. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  83758. };
  83759. return CubeTextureAssetTask;
  83760. }(AbstractAssetTask));
  83761. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  83762. /**
  83763. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  83764. */
  83765. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  83766. __extends(HDRCubeTextureAssetTask, _super);
  83767. /**
  83768. * Creates a new HDRCubeTextureAssetTask object
  83769. * @param name defines the name of the task
  83770. * @param url defines the location of the file to load
  83771. * @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.
  83772. * @param noMipmap defines if mipmaps should not be generated (default is false)
  83773. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  83774. * @param useInGammaSpace 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)
  83775. * @param usePMREMGenerator specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  83776. */
  83777. function HDRCubeTextureAssetTask(
  83778. /**
  83779. * Defines the name of the task
  83780. */
  83781. name,
  83782. /**
  83783. * Defines the location of the file to load
  83784. */
  83785. url,
  83786. /**
  83787. * 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.
  83788. */
  83789. size,
  83790. /**
  83791. * Defines if mipmaps should not be generated (default is false)
  83792. */
  83793. noMipmap,
  83794. /**
  83795. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  83796. */
  83797. generateHarmonics,
  83798. /**
  83799. * 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)
  83800. */
  83801. useInGammaSpace,
  83802. /**
  83803. * Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  83804. */
  83805. usePMREMGenerator) {
  83806. if (noMipmap === void 0) { noMipmap = false; }
  83807. if (generateHarmonics === void 0) { generateHarmonics = true; }
  83808. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  83809. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  83810. var _this = _super.call(this, name) || this;
  83811. _this.name = name;
  83812. _this.url = url;
  83813. _this.size = size;
  83814. _this.noMipmap = noMipmap;
  83815. _this.generateHarmonics = generateHarmonics;
  83816. _this.useInGammaSpace = useInGammaSpace;
  83817. _this.usePMREMGenerator = usePMREMGenerator;
  83818. return _this;
  83819. }
  83820. /**
  83821. * Execute the current task
  83822. * @param scene defines the scene where you want your assets to be loaded
  83823. * @param onSuccess is a callback called when the task is successfully executed
  83824. * @param onError is a callback called if an error occurs
  83825. */
  83826. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  83827. var onload = function () {
  83828. onSuccess();
  83829. };
  83830. var onerror = function (message, exception) {
  83831. onError(message, exception);
  83832. };
  83833. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  83834. };
  83835. return HDRCubeTextureAssetTask;
  83836. }(AbstractAssetTask));
  83837. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  83838. /**
  83839. * This class can be used to easily import assets into a scene
  83840. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  83841. */
  83842. var AssetsManager = /** @class */ (function () {
  83843. /**
  83844. * Creates a new AssetsManager
  83845. * @param scene defines the scene to work on
  83846. */
  83847. function AssetsManager(scene) {
  83848. this._isLoading = false;
  83849. this._tasks = new Array();
  83850. this._waitingTasksCount = 0;
  83851. this._totalTasksCount = 0;
  83852. /**
  83853. * Observable called when all tasks are processed
  83854. */
  83855. this.onTaskSuccessObservable = new BABYLON.Observable();
  83856. /**
  83857. * Observable called when a task had an error
  83858. */
  83859. this.onTaskErrorObservable = new BABYLON.Observable();
  83860. /**
  83861. * Observable called when a task is successful
  83862. */
  83863. this.onTasksDoneObservable = new BABYLON.Observable();
  83864. /**
  83865. * Observable called when a task is done (whatever the result is)
  83866. */
  83867. this.onProgressObservable = new BABYLON.Observable();
  83868. /**
  83869. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  83870. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  83871. */
  83872. this.useDefaultLoadingScreen = true;
  83873. this._scene = scene;
  83874. }
  83875. /**
  83876. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  83877. * @param taskName defines the name of the new task
  83878. * @param meshesNames defines the name of meshes to load
  83879. * @param rootUrl defines the root url to use to locate files
  83880. * @param sceneFilename defines the filename of the scene file
  83881. * @returns a new {BABYLON.MeshAssetTask} object
  83882. */
  83883. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  83884. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  83885. this._tasks.push(task);
  83886. return task;
  83887. };
  83888. /**
  83889. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  83890. * @param taskName defines the name of the new task
  83891. * @param url defines the url of the file to load
  83892. * @returns a new {BABYLON.TextFileAssetTask} object
  83893. */
  83894. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  83895. var task = new TextFileAssetTask(taskName, url);
  83896. this._tasks.push(task);
  83897. return task;
  83898. };
  83899. /**
  83900. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  83901. * @param taskName defines the name of the new task
  83902. * @param url defines the url of the file to load
  83903. * @returns a new {BABYLON.BinaryFileAssetTask} object
  83904. */
  83905. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  83906. var task = new BinaryFileAssetTask(taskName, url);
  83907. this._tasks.push(task);
  83908. return task;
  83909. };
  83910. /**
  83911. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  83912. * @param taskName defines the name of the new task
  83913. * @param url defines the url of the file to load
  83914. * @returns a new {BABYLON.ImageAssetTask} object
  83915. */
  83916. AssetsManager.prototype.addImageTask = function (taskName, url) {
  83917. var task = new ImageAssetTask(taskName, url);
  83918. this._tasks.push(task);
  83919. return task;
  83920. };
  83921. /**
  83922. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  83923. * @param taskName defines the name of the new task
  83924. * @param url defines the url of the file to load
  83925. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  83926. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  83927. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  83928. * @returns a new {BABYLON.TextureAssetTask} object
  83929. */
  83930. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  83931. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  83932. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  83933. this._tasks.push(task);
  83934. return task;
  83935. };
  83936. /**
  83937. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  83938. * @param taskName defines the name of the new task
  83939. * @param url defines the url of the file to load
  83940. * @param extensions defines the extension to use to load the cube map (can be null)
  83941. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  83942. * @param files defines the list of files to load (can be null)
  83943. * @returns a new {BABYLON.CubeTextureAssetTask} object
  83944. */
  83945. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  83946. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  83947. this._tasks.push(task);
  83948. return task;
  83949. };
  83950. /**
  83951. *
  83952. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  83953. * @param taskName defines the name of the new task
  83954. * @param url defines the url of the file to load
  83955. * @param size defines the size you want for the cubemap (can be null)
  83956. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  83957. * @param generateHarmonics defines if you want to automatically generate (true by default)
  83958. * @param useInGammaSpace defines if the texture must be considered in gamma space (false by default)
  83959. * @param usePMREMGenerator is a reserved parameter and must be set to false or ignored
  83960. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  83961. */
  83962. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  83963. if (noMipmap === void 0) { noMipmap = false; }
  83964. if (generateHarmonics === void 0) { generateHarmonics = true; }
  83965. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  83966. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  83967. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator);
  83968. this._tasks.push(task);
  83969. return task;
  83970. };
  83971. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  83972. var _this = this;
  83973. this._waitingTasksCount--;
  83974. try {
  83975. if (task.taskState === AssetTaskState.DONE) {
  83976. // Let's remove successfull tasks
  83977. BABYLON.Tools.SetImmediate(function () {
  83978. var index = _this._tasks.indexOf(task);
  83979. if (index > -1) {
  83980. _this._tasks.splice(index, 1);
  83981. }
  83982. });
  83983. }
  83984. if (this.onProgress) {
  83985. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  83986. }
  83987. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  83988. }
  83989. catch (e) {
  83990. BABYLON.Tools.Error("Error running progress callbacks.");
  83991. console.log(e);
  83992. }
  83993. if (this._waitingTasksCount === 0) {
  83994. try {
  83995. if (this.onFinish) {
  83996. this.onFinish(this._tasks);
  83997. }
  83998. this.onTasksDoneObservable.notifyObservers(this._tasks);
  83999. }
  84000. catch (e) {
  84001. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  84002. console.log(e);
  84003. }
  84004. this._isLoading = false;
  84005. this._scene.getEngine().hideLoadingUI();
  84006. }
  84007. };
  84008. AssetsManager.prototype._runTask = function (task) {
  84009. var _this = this;
  84010. var done = function () {
  84011. try {
  84012. if (_this.onTaskSuccess) {
  84013. _this.onTaskSuccess(task);
  84014. }
  84015. _this.onTaskSuccessObservable.notifyObservers(task);
  84016. _this._decreaseWaitingTasksCount(task);
  84017. }
  84018. catch (e) {
  84019. error("Error executing task success callbacks", e);
  84020. }
  84021. };
  84022. var error = function (message, exception) {
  84023. task._setErrorObject(message, exception);
  84024. if (_this.onTaskError) {
  84025. _this.onTaskError(task);
  84026. }
  84027. _this.onTaskErrorObservable.notifyObservers(task);
  84028. _this._decreaseWaitingTasksCount(task);
  84029. };
  84030. task.run(this._scene, done, error);
  84031. };
  84032. /**
  84033. * Reset the {BABYLON.AssetsManager} and remove all tasks
  84034. * @return the current instance of the {BABYLON.AssetsManager}
  84035. */
  84036. AssetsManager.prototype.reset = function () {
  84037. this._isLoading = false;
  84038. this._tasks = new Array();
  84039. return this;
  84040. };
  84041. /**
  84042. * Start the loading process
  84043. * @return the current instance of the {BABYLON.AssetsManager}
  84044. */
  84045. AssetsManager.prototype.load = function () {
  84046. if (this._isLoading) {
  84047. return this;
  84048. }
  84049. this._isLoading = true;
  84050. this._waitingTasksCount = this._tasks.length;
  84051. this._totalTasksCount = this._tasks.length;
  84052. if (this._waitingTasksCount === 0) {
  84053. if (this.onFinish) {
  84054. this.onFinish(this._tasks);
  84055. }
  84056. this.onTasksDoneObservable.notifyObservers(this._tasks);
  84057. return this;
  84058. }
  84059. if (this.useDefaultLoadingScreen) {
  84060. this._scene.getEngine().displayLoadingUI();
  84061. }
  84062. for (var index = 0; index < this._tasks.length; index++) {
  84063. var task = this._tasks[index];
  84064. this._runTask(task);
  84065. }
  84066. return this;
  84067. };
  84068. return AssetsManager;
  84069. }());
  84070. BABYLON.AssetsManager = AssetsManager;
  84071. })(BABYLON || (BABYLON = {}));
  84072. //# sourceMappingURL=babylon.assetsManager.js.map
  84073. var BABYLON;
  84074. (function (BABYLON) {
  84075. var serializedGeometries = [];
  84076. var serializeGeometry = function (geometry, serializationGeometries) {
  84077. if (serializedGeometries[geometry.id]) {
  84078. return;
  84079. }
  84080. if (geometry.doNotSerialize) {
  84081. return;
  84082. }
  84083. if (geometry instanceof BABYLON.BoxGeometry) {
  84084. serializationGeometries.boxes.push(geometry.serialize());
  84085. }
  84086. else if (geometry instanceof BABYLON.SphereGeometry) {
  84087. serializationGeometries.spheres.push(geometry.serialize());
  84088. }
  84089. else if (geometry instanceof BABYLON.CylinderGeometry) {
  84090. serializationGeometries.cylinders.push(geometry.serialize());
  84091. }
  84092. else if (geometry instanceof BABYLON.TorusGeometry) {
  84093. serializationGeometries.toruses.push(geometry.serialize());
  84094. }
  84095. else if (geometry instanceof BABYLON.GroundGeometry) {
  84096. serializationGeometries.grounds.push(geometry.serialize());
  84097. }
  84098. else if (geometry instanceof BABYLON.Plane) {
  84099. serializationGeometries.planes.push(geometry.serialize());
  84100. }
  84101. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  84102. serializationGeometries.torusKnots.push(geometry.serialize());
  84103. }
  84104. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  84105. throw new Error("Unknown primitive type");
  84106. }
  84107. else {
  84108. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  84109. }
  84110. serializedGeometries[geometry.id] = true;
  84111. };
  84112. var serializeMesh = function (mesh, serializationScene) {
  84113. var serializationObject = {};
  84114. // Geometry
  84115. var geometry = mesh._geometry;
  84116. if (geometry) {
  84117. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  84118. // 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
  84119. serializeGeometry(geometry, serializationScene.geometries);
  84120. }
  84121. }
  84122. // Custom
  84123. if (mesh.serialize) {
  84124. mesh.serialize(serializationObject);
  84125. }
  84126. return serializationObject;
  84127. };
  84128. var finalizeSingleMesh = function (mesh, serializationObject) {
  84129. //only works if the mesh is already loaded
  84130. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  84131. //serialize material
  84132. if (mesh.material) {
  84133. if (mesh.material instanceof BABYLON.StandardMaterial) {
  84134. serializationObject.materials = serializationObject.materials || [];
  84135. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  84136. serializationObject.materials.push(mesh.material.serialize());
  84137. }
  84138. }
  84139. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  84140. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  84141. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  84142. serializationObject.multiMaterials.push(mesh.material.serialize());
  84143. }
  84144. }
  84145. }
  84146. //serialize geometry
  84147. var geometry = mesh._geometry;
  84148. if (geometry) {
  84149. if (!serializationObject.geometries) {
  84150. serializationObject.geometries = {};
  84151. serializationObject.geometries.boxes = [];
  84152. serializationObject.geometries.spheres = [];
  84153. serializationObject.geometries.cylinders = [];
  84154. serializationObject.geometries.toruses = [];
  84155. serializationObject.geometries.grounds = [];
  84156. serializationObject.geometries.planes = [];
  84157. serializationObject.geometries.torusKnots = [];
  84158. serializationObject.geometries.vertexData = [];
  84159. }
  84160. serializeGeometry(geometry, serializationObject.geometries);
  84161. }
  84162. // Skeletons
  84163. if (mesh.skeleton) {
  84164. serializationObject.skeletons = serializationObject.skeletons || [];
  84165. serializationObject.skeletons.push(mesh.skeleton.serialize());
  84166. }
  84167. //serialize the actual mesh
  84168. serializationObject.meshes = serializationObject.meshes || [];
  84169. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  84170. }
  84171. };
  84172. var SceneSerializer = /** @class */ (function () {
  84173. function SceneSerializer() {
  84174. }
  84175. SceneSerializer.ClearCache = function () {
  84176. serializedGeometries = [];
  84177. };
  84178. SceneSerializer.Serialize = function (scene) {
  84179. var serializationObject = {};
  84180. SceneSerializer.ClearCache();
  84181. // Scene
  84182. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  84183. serializationObject.autoClear = scene.autoClear;
  84184. serializationObject.clearColor = scene.clearColor.asArray();
  84185. serializationObject.ambientColor = scene.ambientColor.asArray();
  84186. serializationObject.gravity = scene.gravity.asArray();
  84187. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  84188. serializationObject.workerCollisions = scene.workerCollisions;
  84189. // Fog
  84190. if (scene.fogMode && scene.fogMode !== 0) {
  84191. serializationObject.fogMode = scene.fogMode;
  84192. serializationObject.fogColor = scene.fogColor.asArray();
  84193. serializationObject.fogStart = scene.fogStart;
  84194. serializationObject.fogEnd = scene.fogEnd;
  84195. serializationObject.fogDensity = scene.fogDensity;
  84196. }
  84197. //Physics
  84198. if (scene.isPhysicsEnabled()) {
  84199. var physicEngine = scene.getPhysicsEngine();
  84200. if (physicEngine) {
  84201. serializationObject.physicsEnabled = true;
  84202. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  84203. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  84204. }
  84205. }
  84206. // Metadata
  84207. if (scene.metadata) {
  84208. serializationObject.metadata = scene.metadata;
  84209. }
  84210. // Morph targets
  84211. serializationObject.morphTargetManagers = [];
  84212. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  84213. var abstractMesh = _a[_i];
  84214. var manager = abstractMesh.morphTargetManager;
  84215. if (manager) {
  84216. serializationObject.morphTargetManagers.push(manager.serialize());
  84217. }
  84218. }
  84219. // Lights
  84220. serializationObject.lights = [];
  84221. var index;
  84222. var light;
  84223. for (index = 0; index < scene.lights.length; index++) {
  84224. light = scene.lights[index];
  84225. if (!light.doNotSerialize) {
  84226. serializationObject.lights.push(light.serialize());
  84227. }
  84228. }
  84229. // Cameras
  84230. serializationObject.cameras = [];
  84231. for (index = 0; index < scene.cameras.length; index++) {
  84232. var camera = scene.cameras[index];
  84233. if (!camera.doNotSerialize) {
  84234. serializationObject.cameras.push(camera.serialize());
  84235. }
  84236. }
  84237. if (scene.activeCamera) {
  84238. serializationObject.activeCameraID = scene.activeCamera.id;
  84239. }
  84240. // Animations
  84241. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  84242. // Materials
  84243. serializationObject.materials = [];
  84244. serializationObject.multiMaterials = [];
  84245. var material;
  84246. for (index = 0; index < scene.materials.length; index++) {
  84247. material = scene.materials[index];
  84248. if (!material.doNotSerialize) {
  84249. serializationObject.materials.push(material.serialize());
  84250. }
  84251. }
  84252. // MultiMaterials
  84253. serializationObject.multiMaterials = [];
  84254. for (index = 0; index < scene.multiMaterials.length; index++) {
  84255. var multiMaterial = scene.multiMaterials[index];
  84256. serializationObject.multiMaterials.push(multiMaterial.serialize());
  84257. }
  84258. // Environment texture
  84259. if (scene.environmentTexture) {
  84260. serializationObject.environmentTexture = scene.environmentTexture.name;
  84261. }
  84262. // Skeletons
  84263. serializationObject.skeletons = [];
  84264. for (index = 0; index < scene.skeletons.length; index++) {
  84265. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  84266. }
  84267. // Transform nodes
  84268. serializationObject.transformNodes = [];
  84269. for (index = 0; index < scene.transformNodes.length; index++) {
  84270. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  84271. }
  84272. // Geometries
  84273. serializationObject.geometries = {};
  84274. serializationObject.geometries.boxes = [];
  84275. serializationObject.geometries.spheres = [];
  84276. serializationObject.geometries.cylinders = [];
  84277. serializationObject.geometries.toruses = [];
  84278. serializationObject.geometries.grounds = [];
  84279. serializationObject.geometries.planes = [];
  84280. serializationObject.geometries.torusKnots = [];
  84281. serializationObject.geometries.vertexData = [];
  84282. serializedGeometries = [];
  84283. var geometries = scene.getGeometries();
  84284. for (index = 0; index < geometries.length; index++) {
  84285. var geometry = geometries[index];
  84286. if (geometry.isReady()) {
  84287. serializeGeometry(geometry, serializationObject.geometries);
  84288. }
  84289. }
  84290. // Meshes
  84291. serializationObject.meshes = [];
  84292. for (index = 0; index < scene.meshes.length; index++) {
  84293. var abstractMesh = scene.meshes[index];
  84294. if (abstractMesh instanceof BABYLON.Mesh) {
  84295. var mesh = abstractMesh;
  84296. if (!mesh.doNotSerialize) {
  84297. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  84298. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  84299. }
  84300. }
  84301. }
  84302. }
  84303. // Particles Systems
  84304. serializationObject.particleSystems = [];
  84305. for (index = 0; index < scene.particleSystems.length; index++) {
  84306. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  84307. }
  84308. // Lens flares
  84309. serializationObject.lensFlareSystems = [];
  84310. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  84311. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  84312. }
  84313. // Shadows
  84314. serializationObject.shadowGenerators = [];
  84315. for (index = 0; index < scene.lights.length; index++) {
  84316. light = scene.lights[index];
  84317. var shadowGenerator = light.getShadowGenerator();
  84318. if (shadowGenerator) {
  84319. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  84320. }
  84321. }
  84322. // Action Manager
  84323. if (scene.actionManager) {
  84324. serializationObject.actions = scene.actionManager.serialize("scene");
  84325. }
  84326. // Audio
  84327. serializationObject.sounds = [];
  84328. for (index = 0; index < scene.soundTracks.length; index++) {
  84329. var soundtrack = scene.soundTracks[index];
  84330. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  84331. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  84332. }
  84333. }
  84334. return serializationObject;
  84335. };
  84336. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  84337. if (withParents === void 0) { withParents = false; }
  84338. if (withChildren === void 0) { withChildren = false; }
  84339. var serializationObject = {};
  84340. SceneSerializer.ClearCache();
  84341. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  84342. if (withParents || withChildren) {
  84343. //deliberate for loop! not for each, appended should be processed as well.
  84344. for (var i = 0; i < toSerialize.length; ++i) {
  84345. if (withChildren) {
  84346. toSerialize[i].getDescendants().forEach(function (node) {
  84347. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  84348. toSerialize.push(node);
  84349. }
  84350. });
  84351. }
  84352. //make sure the array doesn't contain the object already
  84353. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  84354. toSerialize.push(toSerialize[i].parent);
  84355. }
  84356. }
  84357. }
  84358. toSerialize.forEach(function (mesh) {
  84359. finalizeSingleMesh(mesh, serializationObject);
  84360. });
  84361. return serializationObject;
  84362. };
  84363. return SceneSerializer;
  84364. }());
  84365. BABYLON.SceneSerializer = SceneSerializer;
  84366. })(BABYLON || (BABYLON = {}));
  84367. //# sourceMappingURL=babylon.sceneSerializer.js.map
  84368. var BABYLON;
  84369. (function (BABYLON) {
  84370. var ReflectionProbe = /** @class */ (function () {
  84371. function ReflectionProbe(name, size, scene, generateMipMaps) {
  84372. if (generateMipMaps === void 0) { generateMipMaps = true; }
  84373. var _this = this;
  84374. this.name = name;
  84375. this._viewMatrix = BABYLON.Matrix.Identity();
  84376. this._target = BABYLON.Vector3.Zero();
  84377. this._add = BABYLON.Vector3.Zero();
  84378. this.invertYAxis = false;
  84379. this.position = BABYLON.Vector3.Zero();
  84380. this._scene = scene;
  84381. this._scene.reflectionProbes.push(this);
  84382. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  84383. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  84384. switch (faceIndex) {
  84385. case 0:
  84386. _this._add.copyFromFloats(1, 0, 0);
  84387. break;
  84388. case 1:
  84389. _this._add.copyFromFloats(-1, 0, 0);
  84390. break;
  84391. case 2:
  84392. _this._add.copyFromFloats(0, _this.invertYAxis ? 1 : -1, 0);
  84393. break;
  84394. case 3:
  84395. _this._add.copyFromFloats(0, _this.invertYAxis ? -1 : 1, 0);
  84396. break;
  84397. case 4:
  84398. _this._add.copyFromFloats(0, 0, 1);
  84399. break;
  84400. case 5:
  84401. _this._add.copyFromFloats(0, 0, -1);
  84402. break;
  84403. }
  84404. if (_this._attachedMesh) {
  84405. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  84406. }
  84407. _this.position.addToRef(_this._add, _this._target);
  84408. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  84409. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  84410. scene._forcedViewPosition = _this.position;
  84411. });
  84412. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  84413. scene._forcedViewPosition = null;
  84414. scene.updateTransformMatrix(true);
  84415. });
  84416. if (scene.activeCamera) {
  84417. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  84418. }
  84419. }
  84420. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  84421. get: function () {
  84422. return this._renderTargetTexture.samples;
  84423. },
  84424. set: function (value) {
  84425. this._renderTargetTexture.samples = value;
  84426. },
  84427. enumerable: true,
  84428. configurable: true
  84429. });
  84430. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  84431. get: function () {
  84432. return this._renderTargetTexture.refreshRate;
  84433. },
  84434. set: function (value) {
  84435. this._renderTargetTexture.refreshRate = value;
  84436. },
  84437. enumerable: true,
  84438. configurable: true
  84439. });
  84440. ReflectionProbe.prototype.getScene = function () {
  84441. return this._scene;
  84442. };
  84443. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  84444. get: function () {
  84445. return this._renderTargetTexture;
  84446. },
  84447. enumerable: true,
  84448. configurable: true
  84449. });
  84450. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  84451. get: function () {
  84452. return this._renderTargetTexture.renderList;
  84453. },
  84454. enumerable: true,
  84455. configurable: true
  84456. });
  84457. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  84458. this._attachedMesh = mesh;
  84459. };
  84460. /**
  84461. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  84462. *
  84463. * @param renderingGroupId The rendering group id corresponding to its index
  84464. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  84465. */
  84466. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  84467. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  84468. };
  84469. ReflectionProbe.prototype.dispose = function () {
  84470. var index = this._scene.reflectionProbes.indexOf(this);
  84471. if (index !== -1) {
  84472. // Remove from the scene if found
  84473. this._scene.reflectionProbes.splice(index, 1);
  84474. }
  84475. if (this._renderTargetTexture) {
  84476. this._renderTargetTexture.dispose();
  84477. this._renderTargetTexture = null;
  84478. }
  84479. };
  84480. return ReflectionProbe;
  84481. }());
  84482. BABYLON.ReflectionProbe = ReflectionProbe;
  84483. })(BABYLON || (BABYLON = {}));
  84484. //# sourceMappingURL=babylon.reflectionProbe.js.map
  84485. var BABYLON;
  84486. (function (BABYLON) {
  84487. var Layer = /** @class */ (function () {
  84488. function Layer(name, imgUrl, scene, isBackground, color) {
  84489. this.name = name;
  84490. this.scale = new BABYLON.Vector2(1, 1);
  84491. this.offset = new BABYLON.Vector2(0, 0);
  84492. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  84493. this.layerMask = 0x0FFFFFFF;
  84494. this._vertexBuffers = {};
  84495. // Events
  84496. /**
  84497. * An event triggered when the layer is disposed.
  84498. * @type {BABYLON.Observable}
  84499. */
  84500. this.onDisposeObservable = new BABYLON.Observable();
  84501. /**
  84502. * An event triggered before rendering the scene
  84503. * @type {BABYLON.Observable}
  84504. */
  84505. this.onBeforeRenderObservable = new BABYLON.Observable();
  84506. /**
  84507. * An event triggered after rendering the scene
  84508. * @type {BABYLON.Observable}
  84509. */
  84510. this.onAfterRenderObservable = new BABYLON.Observable();
  84511. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  84512. this.isBackground = isBackground === undefined ? true : isBackground;
  84513. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  84514. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  84515. this._scene.layers.push(this);
  84516. var engine = this._scene.getEngine();
  84517. // VBO
  84518. var vertices = [];
  84519. vertices.push(1, 1);
  84520. vertices.push(-1, 1);
  84521. vertices.push(-1, -1);
  84522. vertices.push(1, -1);
  84523. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  84524. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  84525. this._createIndexBuffer();
  84526. // Effects
  84527. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  84528. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  84529. }
  84530. Object.defineProperty(Layer.prototype, "onDispose", {
  84531. set: function (callback) {
  84532. if (this._onDisposeObserver) {
  84533. this.onDisposeObservable.remove(this._onDisposeObserver);
  84534. }
  84535. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  84536. },
  84537. enumerable: true,
  84538. configurable: true
  84539. });
  84540. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  84541. set: function (callback) {
  84542. if (this._onBeforeRenderObserver) {
  84543. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  84544. }
  84545. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  84546. },
  84547. enumerable: true,
  84548. configurable: true
  84549. });
  84550. Object.defineProperty(Layer.prototype, "onAfterRender", {
  84551. set: function (callback) {
  84552. if (this._onAfterRenderObserver) {
  84553. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  84554. }
  84555. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  84556. },
  84557. enumerable: true,
  84558. configurable: true
  84559. });
  84560. Layer.prototype._createIndexBuffer = function () {
  84561. var engine = this._scene.getEngine();
  84562. // Indices
  84563. var indices = [];
  84564. indices.push(0);
  84565. indices.push(1);
  84566. indices.push(2);
  84567. indices.push(0);
  84568. indices.push(2);
  84569. indices.push(3);
  84570. this._indexBuffer = engine.createIndexBuffer(indices);
  84571. };
  84572. Layer.prototype._rebuild = function () {
  84573. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  84574. if (vb) {
  84575. vb._rebuild();
  84576. }
  84577. this._createIndexBuffer();
  84578. };
  84579. Layer.prototype.render = function () {
  84580. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  84581. // Check
  84582. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  84583. return;
  84584. var engine = this._scene.getEngine();
  84585. this.onBeforeRenderObservable.notifyObservers(this);
  84586. // Render
  84587. engine.enableEffect(currentEffect);
  84588. engine.setState(false);
  84589. // Texture
  84590. currentEffect.setTexture("textureSampler", this.texture);
  84591. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  84592. // Color
  84593. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  84594. // Scale / offset
  84595. currentEffect.setVector2("offset", this.offset);
  84596. currentEffect.setVector2("scale", this.scale);
  84597. // VBOs
  84598. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  84599. // Draw order
  84600. if (!this.alphaTest) {
  84601. engine.setAlphaMode(this.alphaBlendingMode);
  84602. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  84603. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  84604. }
  84605. else {
  84606. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  84607. }
  84608. this.onAfterRenderObservable.notifyObservers(this);
  84609. };
  84610. Layer.prototype.dispose = function () {
  84611. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  84612. if (vertexBuffer) {
  84613. vertexBuffer.dispose();
  84614. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  84615. }
  84616. if (this._indexBuffer) {
  84617. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  84618. this._indexBuffer = null;
  84619. }
  84620. if (this.texture) {
  84621. this.texture.dispose();
  84622. this.texture = null;
  84623. }
  84624. // Remove from scene
  84625. var index = this._scene.layers.indexOf(this);
  84626. this._scene.layers.splice(index, 1);
  84627. // Callback
  84628. this.onDisposeObservable.notifyObservers(this);
  84629. this.onDisposeObservable.clear();
  84630. this.onAfterRenderObservable.clear();
  84631. this.onBeforeRenderObservable.clear();
  84632. };
  84633. return Layer;
  84634. }());
  84635. BABYLON.Layer = Layer;
  84636. })(BABYLON || (BABYLON = {}));
  84637. //# sourceMappingURL=babylon.layer.js.map
  84638. var BABYLON;
  84639. (function (BABYLON) {
  84640. var TextureTools = /** @class */ (function () {
  84641. function TextureTools() {
  84642. }
  84643. /**
  84644. * Uses the GPU to create a copy texture rescaled at a given size
  84645. * @param texture Texture to copy from
  84646. * @param width Desired width
  84647. * @param height Desired height
  84648. * @return Generated texture
  84649. */
  84650. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  84651. if (useBilinearMode === void 0) { useBilinearMode = true; }
  84652. var scene = texture.getScene();
  84653. var engine = scene.getEngine();
  84654. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  84655. rtt.wrapU = texture.wrapU;
  84656. rtt.wrapV = texture.wrapV;
  84657. rtt.uOffset = texture.uOffset;
  84658. rtt.vOffset = texture.vOffset;
  84659. rtt.uScale = texture.uScale;
  84660. rtt.vScale = texture.vScale;
  84661. rtt.uAng = texture.uAng;
  84662. rtt.vAng = texture.vAng;
  84663. rtt.wAng = texture.wAng;
  84664. rtt.coordinatesIndex = texture.coordinatesIndex;
  84665. rtt.level = texture.level;
  84666. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  84667. rtt._texture.isReady = false;
  84668. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  84669. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  84670. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  84671. passPostProcess.getEffect().executeWhenCompiled(function () {
  84672. passPostProcess.onApply = function (effect) {
  84673. effect.setTexture("textureSampler", texture);
  84674. };
  84675. var internalTexture = rtt.getInternalTexture();
  84676. if (internalTexture) {
  84677. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  84678. engine.unBindFramebuffer(internalTexture);
  84679. rtt.disposeFramebufferObjects();
  84680. passPostProcess.dispose();
  84681. internalTexture.isReady = true;
  84682. }
  84683. });
  84684. return rtt;
  84685. };
  84686. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  84687. if (!scene._environmentBRDFTexture) {
  84688. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  84689. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  84690. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  84691. scene._environmentBRDFTexture = texture;
  84692. }
  84693. return scene._environmentBRDFTexture;
  84694. };
  84695. 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=";
  84696. return TextureTools;
  84697. }());
  84698. BABYLON.TextureTools = TextureTools;
  84699. })(BABYLON || (BABYLON = {}));
  84700. //# sourceMappingURL=babylon.textureTools.js.map
  84701. var BABYLON;
  84702. (function (BABYLON) {
  84703. var FramingBehavior = /** @class */ (function () {
  84704. function FramingBehavior() {
  84705. this._mode = FramingBehavior.FitFrustumSidesMode;
  84706. this._radiusScale = 1.0;
  84707. this._positionScale = 0.5;
  84708. this._defaultElevation = 0.3;
  84709. this._elevationReturnTime = 1500;
  84710. this._elevationReturnWaitTime = 1000;
  84711. this._zoomStopsAnimation = false;
  84712. this._framingTime = 1500;
  84713. this._isPointerDown = false;
  84714. this._lastInteractionTime = -Infinity;
  84715. // Framing control
  84716. this._animatables = new Array();
  84717. this._betaIsAnimating = false;
  84718. }
  84719. Object.defineProperty(FramingBehavior.prototype, "name", {
  84720. get: function () {
  84721. return "Framing";
  84722. },
  84723. enumerable: true,
  84724. configurable: true
  84725. });
  84726. Object.defineProperty(FramingBehavior.prototype, "mode", {
  84727. /**
  84728. * Gets current mode used by the behavior.
  84729. */
  84730. get: function () {
  84731. return this._mode;
  84732. },
  84733. /**
  84734. * Sets the current mode used by the behavior
  84735. */
  84736. set: function (mode) {
  84737. this._mode = mode;
  84738. },
  84739. enumerable: true,
  84740. configurable: true
  84741. });
  84742. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  84743. /**
  84744. * Gets the scale applied to the radius
  84745. */
  84746. get: function () {
  84747. return this._radiusScale;
  84748. },
  84749. /**
  84750. * Sets the scale applied to the radius (1 by default)
  84751. */
  84752. set: function (radius) {
  84753. this._radiusScale = radius;
  84754. },
  84755. enumerable: true,
  84756. configurable: true
  84757. });
  84758. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  84759. /**
  84760. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  84761. */
  84762. get: function () {
  84763. return this._positionScale;
  84764. },
  84765. /**
  84766. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  84767. */
  84768. set: function (scale) {
  84769. this._positionScale = scale;
  84770. },
  84771. enumerable: true,
  84772. configurable: true
  84773. });
  84774. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  84775. /**
  84776. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  84777. * behaviour is triggered, in radians.
  84778. */
  84779. get: function () {
  84780. return this._defaultElevation;
  84781. },
  84782. /**
  84783. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  84784. * behaviour is triggered, in radians.
  84785. */
  84786. set: function (elevation) {
  84787. this._defaultElevation = elevation;
  84788. },
  84789. enumerable: true,
  84790. configurable: true
  84791. });
  84792. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  84793. /**
  84794. * Gets the time (in milliseconds) taken to return to the default beta position.
  84795. * Negative value indicates camera should not return to default.
  84796. */
  84797. get: function () {
  84798. return this._elevationReturnTime;
  84799. },
  84800. /**
  84801. * Sets the time (in milliseconds) taken to return to the default beta position.
  84802. * Negative value indicates camera should not return to default.
  84803. */
  84804. set: function (speed) {
  84805. this._elevationReturnTime = speed;
  84806. },
  84807. enumerable: true,
  84808. configurable: true
  84809. });
  84810. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  84811. /**
  84812. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  84813. */
  84814. get: function () {
  84815. return this._elevationReturnWaitTime;
  84816. },
  84817. /**
  84818. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  84819. */
  84820. set: function (time) {
  84821. this._elevationReturnWaitTime = time;
  84822. },
  84823. enumerable: true,
  84824. configurable: true
  84825. });
  84826. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  84827. /**
  84828. * Gets the flag that indicates if user zooming should stop animation.
  84829. */
  84830. get: function () {
  84831. return this._zoomStopsAnimation;
  84832. },
  84833. /**
  84834. * Sets the flag that indicates if user zooming should stop animation.
  84835. */
  84836. set: function (flag) {
  84837. this._zoomStopsAnimation = flag;
  84838. },
  84839. enumerable: true,
  84840. configurable: true
  84841. });
  84842. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  84843. /**
  84844. * Gets the transition time when framing the mesh, in milliseconds
  84845. */
  84846. get: function () {
  84847. return this._framingTime;
  84848. },
  84849. /**
  84850. * Sets the transition time when framing the mesh, in milliseconds
  84851. */
  84852. set: function (time) {
  84853. this._framingTime = time;
  84854. },
  84855. enumerable: true,
  84856. configurable: true
  84857. });
  84858. FramingBehavior.prototype.init = function () {
  84859. // Do notihng
  84860. };
  84861. FramingBehavior.prototype.attach = function (camera) {
  84862. var _this = this;
  84863. this._attachedCamera = camera;
  84864. var scene = this._attachedCamera.getScene();
  84865. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  84866. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  84867. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  84868. _this._isPointerDown = true;
  84869. return;
  84870. }
  84871. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  84872. _this._isPointerDown = false;
  84873. }
  84874. });
  84875. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  84876. if (mesh) {
  84877. _this.zoomOnMesh(mesh);
  84878. }
  84879. });
  84880. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  84881. // Stop the animation if there is user interaction and the animation should stop for this interaction
  84882. _this._applyUserInteraction();
  84883. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  84884. // back to the default position after a given timeout
  84885. _this._maintainCameraAboveGround();
  84886. });
  84887. };
  84888. FramingBehavior.prototype.detach = function () {
  84889. if (!this._attachedCamera) {
  84890. return;
  84891. }
  84892. var scene = this._attachedCamera.getScene();
  84893. if (this._onPrePointerObservableObserver) {
  84894. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  84895. }
  84896. if (this._onAfterCheckInputsObserver) {
  84897. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  84898. }
  84899. if (this._onMeshTargetChangedObserver) {
  84900. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  84901. }
  84902. this._attachedCamera = null;
  84903. };
  84904. /**
  84905. * Targets the given mesh and updates zoom level accordingly.
  84906. * @param mesh The mesh to target.
  84907. * @param radius Optional. If a cached radius position already exists, overrides default.
  84908. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  84909. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  84910. * @param onAnimationEnd Callback triggered at the end of the framing animation
  84911. */
  84912. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  84913. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  84914. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  84915. mesh.computeWorldMatrix(true);
  84916. var boundingBox = mesh.getBoundingInfo().boundingBox;
  84917. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  84918. };
  84919. /**
  84920. * Targets the given mesh with its children and updates zoom level accordingly.
  84921. * @param mesh The mesh to target.
  84922. * @param radius Optional. If a cached radius position already exists, overrides default.
  84923. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  84924. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  84925. * @param onAnimationEnd Callback triggered at the end of the framing animation
  84926. */
  84927. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  84928. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  84929. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  84930. mesh.computeWorldMatrix(true);
  84931. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  84932. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  84933. };
  84934. /**
  84935. * Targets the given meshes with their children and updates zoom level accordingly.
  84936. * @param meshes The mesh to target.
  84937. * @param radius Optional. If a cached radius position already exists, overrides default.
  84938. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  84939. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  84940. * @param onAnimationEnd Callback triggered at the end of the framing animation
  84941. */
  84942. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  84943. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  84944. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  84945. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  84946. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  84947. for (var i = 0; i < meshes.length; i++) {
  84948. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  84949. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  84950. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  84951. }
  84952. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  84953. };
  84954. /**
  84955. * Targets the given mesh and updates zoom level accordingly.
  84956. * @param mesh The mesh to target.
  84957. * @param radius Optional. If a cached radius position already exists, overrides default.
  84958. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  84959. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  84960. * @param onAnimationEnd Callback triggered at the end of the framing animation
  84961. */
  84962. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  84963. var _this = this;
  84964. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  84965. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  84966. var zoomTarget;
  84967. if (!this._attachedCamera) {
  84968. return;
  84969. }
  84970. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  84971. var bottom = minimumWorld.y;
  84972. var top = maximumWorld.y;
  84973. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  84974. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  84975. if (focusOnOriginXZ) {
  84976. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  84977. }
  84978. else {
  84979. var centerWorld = minimumWorld.add(radiusWorld);
  84980. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  84981. }
  84982. if (!this._vectorTransition) {
  84983. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  84984. }
  84985. this._betaIsAnimating = true;
  84986. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  84987. if (animatable) {
  84988. this._animatables.push(animatable);
  84989. }
  84990. // sets the radius and lower radius bounds
  84991. // Small delta ensures camera is not always at lower zoom limit.
  84992. var radius = 0;
  84993. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  84994. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  84995. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  84996. radius = position;
  84997. }
  84998. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  84999. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  85000. if (this._attachedCamera.lowerRadiusLimit === null) {
  85001. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  85002. }
  85003. }
  85004. // Set sensibilities
  85005. var extend = maximumWorld.subtract(minimumWorld).length();
  85006. this._attachedCamera.panningSensibility = 5000 / extend;
  85007. this._attachedCamera.wheelPrecision = 100 / radius;
  85008. // transition to new radius
  85009. if (!this._radiusTransition) {
  85010. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  85011. }
  85012. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  85013. if (onAnimationEnd) {
  85014. onAnimationEnd();
  85015. }
  85016. if (_this._attachedCamera) {
  85017. _this._attachedCamera.storeState();
  85018. }
  85019. });
  85020. if (animatable) {
  85021. this._animatables.push(animatable);
  85022. }
  85023. };
  85024. /**
  85025. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  85026. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  85027. * frustum width.
  85028. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  85029. * to fully enclose the mesh in the viewing frustum.
  85030. */
  85031. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  85032. var size = maximumWorld.subtract(minimumWorld);
  85033. var boxVectorGlobalDiagonal = size.length();
  85034. var frustumSlope = this._getFrustumSlope();
  85035. // Formula for setting distance
  85036. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  85037. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  85038. // Horizon distance
  85039. var radius = radiusWithoutFraming * this._radiusScale;
  85040. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  85041. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  85042. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  85043. var camera = this._attachedCamera;
  85044. if (!camera) {
  85045. return 0;
  85046. }
  85047. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  85048. // Don't exceed the requested limit
  85049. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  85050. }
  85051. // Don't exceed the upper radius limit
  85052. if (camera.upperRadiusLimit) {
  85053. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  85054. }
  85055. return distance;
  85056. };
  85057. /**
  85058. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  85059. * is automatically returned to its default position (expected to be above ground plane).
  85060. */
  85061. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  85062. var _this = this;
  85063. if (this._elevationReturnTime < 0) {
  85064. return;
  85065. }
  85066. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  85067. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  85068. var limitBeta = Math.PI * 0.5;
  85069. // Bring the camera back up if below the ground plane
  85070. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  85071. this._betaIsAnimating = true;
  85072. //Transition to new position
  85073. this.stopAllAnimations();
  85074. if (!this._betaTransition) {
  85075. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  85076. }
  85077. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  85078. _this._clearAnimationLocks();
  85079. _this.stopAllAnimations();
  85080. });
  85081. if (animatabe) {
  85082. this._animatables.push(animatabe);
  85083. }
  85084. }
  85085. };
  85086. /**
  85087. * Returns the frustum slope based on the canvas ratio and camera FOV
  85088. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  85089. */
  85090. FramingBehavior.prototype._getFrustumSlope = function () {
  85091. // Calculate the viewport ratio
  85092. // Aspect Ratio is Height/Width.
  85093. var camera = this._attachedCamera;
  85094. if (!camera) {
  85095. return BABYLON.Vector2.Zero();
  85096. }
  85097. var engine = camera.getScene().getEngine();
  85098. var aspectRatio = engine.getAspectRatio(camera);
  85099. // Camera FOV is the vertical field of view (top-bottom) in radians.
  85100. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  85101. var frustumSlopeY = Math.tan(camera.fov / 2);
  85102. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  85103. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  85104. // along the forward vector.
  85105. var frustumSlopeX = frustumSlopeY * aspectRatio;
  85106. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  85107. };
  85108. /**
  85109. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  85110. */
  85111. FramingBehavior.prototype._clearAnimationLocks = function () {
  85112. this._betaIsAnimating = false;
  85113. };
  85114. /**
  85115. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  85116. */
  85117. FramingBehavior.prototype._applyUserInteraction = function () {
  85118. if (this.isUserIsMoving) {
  85119. this._lastInteractionTime = BABYLON.Tools.Now;
  85120. this.stopAllAnimations();
  85121. this._clearAnimationLocks();
  85122. }
  85123. };
  85124. /**
  85125. * Stops and removes all animations that have been applied to the camera
  85126. */
  85127. FramingBehavior.prototype.stopAllAnimations = function () {
  85128. if (this._attachedCamera) {
  85129. this._attachedCamera.animations = [];
  85130. }
  85131. while (this._animatables.length) {
  85132. if (this._animatables[0]) {
  85133. this._animatables[0].onAnimationEnd = null;
  85134. this._animatables[0].stop();
  85135. }
  85136. this._animatables.shift();
  85137. }
  85138. };
  85139. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  85140. /**
  85141. * Gets a value indicating if the user is moving the camera
  85142. */
  85143. get: function () {
  85144. if (!this._attachedCamera) {
  85145. return false;
  85146. }
  85147. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  85148. this._attachedCamera.inertialBetaOffset !== 0 ||
  85149. this._attachedCamera.inertialRadiusOffset !== 0 ||
  85150. this._attachedCamera.inertialPanningX !== 0 ||
  85151. this._attachedCamera.inertialPanningY !== 0 ||
  85152. this._isPointerDown;
  85153. },
  85154. enumerable: true,
  85155. configurable: true
  85156. });
  85157. /**
  85158. * The easing function used by animations
  85159. */
  85160. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  85161. /**
  85162. * The easing mode used by animations
  85163. */
  85164. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  85165. // Statics
  85166. /**
  85167. * The camera can move all the way towards the mesh.
  85168. */
  85169. FramingBehavior.IgnoreBoundsSizeMode = 0;
  85170. /**
  85171. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  85172. */
  85173. FramingBehavior.FitFrustumSidesMode = 1;
  85174. return FramingBehavior;
  85175. }());
  85176. BABYLON.FramingBehavior = FramingBehavior;
  85177. })(BABYLON || (BABYLON = {}));
  85178. //# sourceMappingURL=babylon.framingBehavior.js.map
  85179. var BABYLON;
  85180. (function (BABYLON) {
  85181. /**
  85182. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  85183. */
  85184. var BouncingBehavior = /** @class */ (function () {
  85185. function BouncingBehavior() {
  85186. /**
  85187. * The duration of the animation, in milliseconds
  85188. */
  85189. this.transitionDuration = 450;
  85190. /**
  85191. * Length of the distance animated by the transition when lower radius is reached
  85192. */
  85193. this.lowerRadiusTransitionRange = 2;
  85194. /**
  85195. * Length of the distance animated by the transition when upper radius is reached
  85196. */
  85197. this.upperRadiusTransitionRange = -2;
  85198. this._autoTransitionRange = false;
  85199. // Animations
  85200. this._radiusIsAnimating = false;
  85201. this._radiusBounceTransition = null;
  85202. this._animatables = new Array();
  85203. }
  85204. Object.defineProperty(BouncingBehavior.prototype, "name", {
  85205. get: function () {
  85206. return "Bouncing";
  85207. },
  85208. enumerable: true,
  85209. configurable: true
  85210. });
  85211. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  85212. /**
  85213. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  85214. */
  85215. get: function () {
  85216. return this._autoTransitionRange;
  85217. },
  85218. /**
  85219. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  85220. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  85221. */
  85222. set: function (value) {
  85223. var _this = this;
  85224. if (this._autoTransitionRange === value) {
  85225. return;
  85226. }
  85227. this._autoTransitionRange = value;
  85228. var camera = this._attachedCamera;
  85229. if (!camera) {
  85230. return;
  85231. }
  85232. if (value) {
  85233. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  85234. if (!mesh) {
  85235. return;
  85236. }
  85237. mesh.computeWorldMatrix(true);
  85238. var diagonal = mesh.getBoundingInfo().diagonalLength;
  85239. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  85240. _this.upperRadiusTransitionRange = diagonal * 0.05;
  85241. });
  85242. }
  85243. else if (this._onMeshTargetChangedObserver) {
  85244. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  85245. }
  85246. },
  85247. enumerable: true,
  85248. configurable: true
  85249. });
  85250. BouncingBehavior.prototype.init = function () {
  85251. // Do notihng
  85252. };
  85253. BouncingBehavior.prototype.attach = function (camera) {
  85254. var _this = this;
  85255. this._attachedCamera = camera;
  85256. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  85257. if (!_this._attachedCamera) {
  85258. return;
  85259. }
  85260. // Add the bounce animation to the lower radius limit
  85261. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  85262. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  85263. }
  85264. // Add the bounce animation to the upper radius limit
  85265. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  85266. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  85267. }
  85268. });
  85269. };
  85270. BouncingBehavior.prototype.detach = function () {
  85271. if (!this._attachedCamera) {
  85272. return;
  85273. }
  85274. if (this._onAfterCheckInputsObserver) {
  85275. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  85276. }
  85277. if (this._onMeshTargetChangedObserver) {
  85278. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  85279. }
  85280. this._attachedCamera = null;
  85281. };
  85282. /**
  85283. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  85284. * @param radiusLimit The limit to check against.
  85285. * @return Bool to indicate if at limit.
  85286. */
  85287. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  85288. if (!this._attachedCamera) {
  85289. return false;
  85290. }
  85291. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  85292. return true;
  85293. }
  85294. return false;
  85295. };
  85296. /**
  85297. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  85298. * @param radiusDelta The delta by which to animate to. Can be negative.
  85299. */
  85300. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  85301. var _this = this;
  85302. if (!this._attachedCamera) {
  85303. return;
  85304. }
  85305. if (!this._radiusBounceTransition) {
  85306. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  85307. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  85308. }
  85309. // Prevent zoom until bounce has completed
  85310. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  85311. this._attachedCamera.wheelPrecision = Infinity;
  85312. this._attachedCamera.inertialRadiusOffset = 0;
  85313. // Animate to the radius limit
  85314. this.stopAllAnimations();
  85315. this._radiusIsAnimating = true;
  85316. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  85317. if (animatable) {
  85318. this._animatables.push(animatable);
  85319. }
  85320. };
  85321. /**
  85322. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  85323. */
  85324. BouncingBehavior.prototype._clearAnimationLocks = function () {
  85325. this._radiusIsAnimating = false;
  85326. if (this._attachedCamera) {
  85327. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  85328. }
  85329. };
  85330. /**
  85331. * Stops and removes all animations that have been applied to the camera
  85332. */
  85333. BouncingBehavior.prototype.stopAllAnimations = function () {
  85334. if (this._attachedCamera) {
  85335. this._attachedCamera.animations = [];
  85336. }
  85337. while (this._animatables.length) {
  85338. this._animatables[0].onAnimationEnd = null;
  85339. this._animatables[0].stop();
  85340. this._animatables.shift();
  85341. }
  85342. };
  85343. /**
  85344. * The easing function used by animations
  85345. */
  85346. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  85347. /**
  85348. * The easing mode used by animations
  85349. */
  85350. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  85351. return BouncingBehavior;
  85352. }());
  85353. BABYLON.BouncingBehavior = BouncingBehavior;
  85354. })(BABYLON || (BABYLON = {}));
  85355. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  85356. var BABYLON;
  85357. (function (BABYLON) {
  85358. var AutoRotationBehavior = /** @class */ (function () {
  85359. function AutoRotationBehavior() {
  85360. this._zoomStopsAnimation = false;
  85361. this._idleRotationSpeed = 0.05;
  85362. this._idleRotationWaitTime = 2000;
  85363. this._idleRotationSpinupTime = 2000;
  85364. this._isPointerDown = false;
  85365. this._lastFrameTime = null;
  85366. this._lastInteractionTime = -Infinity;
  85367. this._cameraRotationSpeed = 0;
  85368. this._lastFrameRadius = 0;
  85369. }
  85370. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  85371. get: function () {
  85372. return "AutoRotation";
  85373. },
  85374. enumerable: true,
  85375. configurable: true
  85376. });
  85377. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  85378. /**
  85379. * Gets the flag that indicates if user zooming should stop animation.
  85380. */
  85381. get: function () {
  85382. return this._zoomStopsAnimation;
  85383. },
  85384. /**
  85385. * Sets the flag that indicates if user zooming should stop animation.
  85386. */
  85387. set: function (flag) {
  85388. this._zoomStopsAnimation = flag;
  85389. },
  85390. enumerable: true,
  85391. configurable: true
  85392. });
  85393. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  85394. /**
  85395. * Gets the default speed at which the camera rotates around the model.
  85396. */
  85397. get: function () {
  85398. return this._idleRotationSpeed;
  85399. },
  85400. /**
  85401. * Sets the default speed at which the camera rotates around the model.
  85402. */
  85403. set: function (speed) {
  85404. this._idleRotationSpeed = speed;
  85405. },
  85406. enumerable: true,
  85407. configurable: true
  85408. });
  85409. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  85410. /**
  85411. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  85412. */
  85413. get: function () {
  85414. return this._idleRotationWaitTime;
  85415. },
  85416. /**
  85417. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  85418. */
  85419. set: function (time) {
  85420. this._idleRotationWaitTime = time;
  85421. },
  85422. enumerable: true,
  85423. configurable: true
  85424. });
  85425. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  85426. /**
  85427. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  85428. */
  85429. get: function () {
  85430. return this._idleRotationSpinupTime;
  85431. },
  85432. /**
  85433. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  85434. */
  85435. set: function (time) {
  85436. this._idleRotationSpinupTime = time;
  85437. },
  85438. enumerable: true,
  85439. configurable: true
  85440. });
  85441. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  85442. /**
  85443. * Gets a value indicating if the camera is currently rotating because of this behavior
  85444. */
  85445. get: function () {
  85446. return Math.abs(this._cameraRotationSpeed) > 0;
  85447. },
  85448. enumerable: true,
  85449. configurable: true
  85450. });
  85451. AutoRotationBehavior.prototype.init = function () {
  85452. // Do notihng
  85453. };
  85454. AutoRotationBehavior.prototype.attach = function (camera) {
  85455. var _this = this;
  85456. this._attachedCamera = camera;
  85457. var scene = this._attachedCamera.getScene();
  85458. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  85459. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  85460. _this._isPointerDown = true;
  85461. return;
  85462. }
  85463. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  85464. _this._isPointerDown = false;
  85465. }
  85466. });
  85467. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  85468. var now = BABYLON.Tools.Now;
  85469. var dt = 0;
  85470. if (_this._lastFrameTime != null) {
  85471. dt = now - _this._lastFrameTime;
  85472. }
  85473. _this._lastFrameTime = now;
  85474. // Stop the animation if there is user interaction and the animation should stop for this interaction
  85475. _this._applyUserInteraction();
  85476. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  85477. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  85478. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  85479. // Step camera rotation by rotation speed
  85480. if (_this._attachedCamera) {
  85481. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  85482. }
  85483. });
  85484. };
  85485. AutoRotationBehavior.prototype.detach = function () {
  85486. if (!this._attachedCamera) {
  85487. return;
  85488. }
  85489. var scene = this._attachedCamera.getScene();
  85490. if (this._onPrePointerObservableObserver) {
  85491. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  85492. }
  85493. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  85494. this._attachedCamera = null;
  85495. };
  85496. /**
  85497. * Returns true if user is scrolling.
  85498. * @return true if user is scrolling.
  85499. */
  85500. AutoRotationBehavior.prototype._userIsZooming = function () {
  85501. if (!this._attachedCamera) {
  85502. return false;
  85503. }
  85504. return this._attachedCamera.inertialRadiusOffset !== 0;
  85505. };
  85506. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  85507. if (!this._attachedCamera) {
  85508. return false;
  85509. }
  85510. var zoomHasHitLimit = false;
  85511. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  85512. zoomHasHitLimit = true;
  85513. }
  85514. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  85515. this._lastFrameRadius = this._attachedCamera.radius;
  85516. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  85517. };
  85518. /**
  85519. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  85520. */
  85521. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  85522. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  85523. this._lastInteractionTime = BABYLON.Tools.Now;
  85524. }
  85525. };
  85526. // Tools
  85527. AutoRotationBehavior.prototype._userIsMoving = function () {
  85528. if (!this._attachedCamera) {
  85529. return false;
  85530. }
  85531. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  85532. this._attachedCamera.inertialBetaOffset !== 0 ||
  85533. this._attachedCamera.inertialRadiusOffset !== 0 ||
  85534. this._attachedCamera.inertialPanningX !== 0 ||
  85535. this._attachedCamera.inertialPanningY !== 0 ||
  85536. this._isPointerDown;
  85537. };
  85538. return AutoRotationBehavior;
  85539. }());
  85540. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  85541. })(BABYLON || (BABYLON = {}));
  85542. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  85543. var BABYLON;
  85544. (function (BABYLON) {
  85545. /**
  85546. * This class can be used to get instrumentation data from a Babylon engine
  85547. */
  85548. var EngineInstrumentation = /** @class */ (function () {
  85549. function EngineInstrumentation(engine) {
  85550. this.engine = engine;
  85551. this._captureGPUFrameTime = false;
  85552. this._gpuFrameTime = new BABYLON.PerfCounter();
  85553. this._captureShaderCompilationTime = false;
  85554. this._shaderCompilationTime = new BABYLON.PerfCounter();
  85555. // Observers
  85556. this._onBeginFrameObserver = null;
  85557. this._onEndFrameObserver = null;
  85558. this._onBeforeShaderCompilationObserver = null;
  85559. this._onAfterShaderCompilationObserver = null;
  85560. }
  85561. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  85562. // Properties
  85563. /**
  85564. * Gets the perf counter used for GPU frame time
  85565. */
  85566. get: function () {
  85567. return this._gpuFrameTime;
  85568. },
  85569. enumerable: true,
  85570. configurable: true
  85571. });
  85572. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  85573. /**
  85574. * Gets the GPU frame time capture status
  85575. */
  85576. get: function () {
  85577. return this._captureGPUFrameTime;
  85578. },
  85579. /**
  85580. * Enable or disable the GPU frame time capture
  85581. */
  85582. set: function (value) {
  85583. var _this = this;
  85584. if (value === this._captureGPUFrameTime) {
  85585. return;
  85586. }
  85587. this._captureGPUFrameTime = value;
  85588. if (value) {
  85589. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  85590. if (!_this._gpuFrameTimeToken) {
  85591. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  85592. }
  85593. });
  85594. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  85595. if (!_this._gpuFrameTimeToken) {
  85596. return;
  85597. }
  85598. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  85599. if (time > -1) {
  85600. _this._gpuFrameTimeToken = null;
  85601. _this._gpuFrameTime.fetchNewFrame();
  85602. _this._gpuFrameTime.addCount(time, true);
  85603. }
  85604. });
  85605. }
  85606. else {
  85607. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  85608. this._onBeginFrameObserver = null;
  85609. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  85610. this._onEndFrameObserver = null;
  85611. }
  85612. },
  85613. enumerable: true,
  85614. configurable: true
  85615. });
  85616. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  85617. /**
  85618. * Gets the perf counter used for shader compilation time
  85619. */
  85620. get: function () {
  85621. return this._shaderCompilationTime;
  85622. },
  85623. enumerable: true,
  85624. configurable: true
  85625. });
  85626. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  85627. /**
  85628. * Gets the shader compilation time capture status
  85629. */
  85630. get: function () {
  85631. return this._captureShaderCompilationTime;
  85632. },
  85633. /**
  85634. * Enable or disable the shader compilation time capture
  85635. */
  85636. set: function (value) {
  85637. var _this = this;
  85638. if (value === this._captureShaderCompilationTime) {
  85639. return;
  85640. }
  85641. this._captureShaderCompilationTime = value;
  85642. if (value) {
  85643. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  85644. _this._shaderCompilationTime.fetchNewFrame();
  85645. _this._shaderCompilationTime.beginMonitoring();
  85646. });
  85647. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  85648. _this._shaderCompilationTime.endMonitoring();
  85649. });
  85650. }
  85651. else {
  85652. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  85653. this._onBeforeShaderCompilationObserver = null;
  85654. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  85655. this._onAfterShaderCompilationObserver = null;
  85656. }
  85657. },
  85658. enumerable: true,
  85659. configurable: true
  85660. });
  85661. EngineInstrumentation.prototype.dispose = function () {
  85662. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  85663. this._onBeginFrameObserver = null;
  85664. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  85665. this._onEndFrameObserver = null;
  85666. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  85667. this._onBeforeShaderCompilationObserver = null;
  85668. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  85669. this._onAfterShaderCompilationObserver = null;
  85670. this.engine = null;
  85671. };
  85672. return EngineInstrumentation;
  85673. }());
  85674. BABYLON.EngineInstrumentation = EngineInstrumentation;
  85675. })(BABYLON || (BABYLON = {}));
  85676. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  85677. var BABYLON;
  85678. (function (BABYLON) {
  85679. /**
  85680. * This class can be used to get instrumentation data from a Babylon engine
  85681. */
  85682. var SceneInstrumentation = /** @class */ (function () {
  85683. function SceneInstrumentation(scene) {
  85684. var _this = this;
  85685. this.scene = scene;
  85686. this._captureActiveMeshesEvaluationTime = false;
  85687. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  85688. this._captureRenderTargetsRenderTime = false;
  85689. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  85690. this._captureFrameTime = false;
  85691. this._frameTime = new BABYLON.PerfCounter();
  85692. this._captureRenderTime = false;
  85693. this._renderTime = new BABYLON.PerfCounter();
  85694. this._captureInterFrameTime = false;
  85695. this._interFrameTime = new BABYLON.PerfCounter();
  85696. this._captureParticlesRenderTime = false;
  85697. this._particlesRenderTime = new BABYLON.PerfCounter();
  85698. this._captureSpritesRenderTime = false;
  85699. this._spritesRenderTime = new BABYLON.PerfCounter();
  85700. this._capturePhysicsTime = false;
  85701. this._physicsTime = new BABYLON.PerfCounter();
  85702. this._captureAnimationsTime = false;
  85703. this._animationsTime = new BABYLON.PerfCounter();
  85704. // Observers
  85705. this._onBeforeActiveMeshesEvaluationObserver = null;
  85706. this._onAfterActiveMeshesEvaluationObserver = null;
  85707. this._onBeforeRenderTargetsRenderObserver = null;
  85708. this._onAfterRenderTargetsRenderObserver = null;
  85709. this._onAfterRenderObserver = null;
  85710. this._onBeforeDrawPhaseObserver = null;
  85711. this._onAfterDrawPhaseObserver = null;
  85712. this._onBeforeAnimationsObserver = null;
  85713. this._onBeforeParticlesRenderingObserver = null;
  85714. this._onAfterParticlesRenderingObserver = null;
  85715. this._onBeforeSpritesRenderingObserver = null;
  85716. this._onAfterSpritesRenderingObserver = null;
  85717. this._onBeforePhysicsObserver = null;
  85718. this._onAfterPhysicsObserver = null;
  85719. this._onAfterAnimationsObserver = null;
  85720. // Before render
  85721. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  85722. if (_this._captureActiveMeshesEvaluationTime) {
  85723. _this._activeMeshesEvaluationTime.fetchNewFrame();
  85724. }
  85725. if (_this._captureRenderTargetsRenderTime) {
  85726. _this._renderTargetsRenderTime.fetchNewFrame();
  85727. }
  85728. if (_this._captureFrameTime) {
  85729. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  85730. _this._frameTime.beginMonitoring();
  85731. }
  85732. if (_this._captureInterFrameTime) {
  85733. _this._interFrameTime.endMonitoring();
  85734. }
  85735. if (_this._captureParticlesRenderTime) {
  85736. _this._particlesRenderTime.fetchNewFrame();
  85737. }
  85738. if (_this._captureSpritesRenderTime) {
  85739. _this._spritesRenderTime.fetchNewFrame();
  85740. }
  85741. if (_this._captureAnimationsTime) {
  85742. _this._animationsTime.beginMonitoring();
  85743. }
  85744. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  85745. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  85746. });
  85747. // After render
  85748. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  85749. if (_this._captureFrameTime) {
  85750. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  85751. _this._frameTime.endMonitoring();
  85752. }
  85753. if (_this._captureRenderTime) {
  85754. _this._renderTime.endMonitoring(false);
  85755. }
  85756. if (_this._captureInterFrameTime) {
  85757. _this._interFrameTime.beginMonitoring();
  85758. }
  85759. });
  85760. }
  85761. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  85762. // Properties
  85763. /**
  85764. * Gets the perf counter used for active meshes evaluation time
  85765. */
  85766. get: function () {
  85767. return this._activeMeshesEvaluationTime;
  85768. },
  85769. enumerable: true,
  85770. configurable: true
  85771. });
  85772. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  85773. /**
  85774. * Gets the active meshes evaluation time capture status
  85775. */
  85776. get: function () {
  85777. return this._captureActiveMeshesEvaluationTime;
  85778. },
  85779. /**
  85780. * Enable or disable the active meshes evaluation time capture
  85781. */
  85782. set: function (value) {
  85783. var _this = this;
  85784. if (value === this._captureActiveMeshesEvaluationTime) {
  85785. return;
  85786. }
  85787. this._captureActiveMeshesEvaluationTime = value;
  85788. if (value) {
  85789. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  85790. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  85791. _this._activeMeshesEvaluationTime.beginMonitoring();
  85792. });
  85793. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  85794. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  85795. _this._activeMeshesEvaluationTime.endMonitoring();
  85796. });
  85797. }
  85798. else {
  85799. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  85800. this._onBeforeActiveMeshesEvaluationObserver = null;
  85801. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  85802. this._onAfterActiveMeshesEvaluationObserver = null;
  85803. }
  85804. },
  85805. enumerable: true,
  85806. configurable: true
  85807. });
  85808. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  85809. /**
  85810. * Gets the perf counter used for render targets render time
  85811. */
  85812. get: function () {
  85813. return this._renderTargetsRenderTime;
  85814. },
  85815. enumerable: true,
  85816. configurable: true
  85817. });
  85818. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  85819. /**
  85820. * Gets the render targets render time capture status
  85821. */
  85822. get: function () {
  85823. return this._captureRenderTargetsRenderTime;
  85824. },
  85825. /**
  85826. * Enable or disable the render targets render time capture
  85827. */
  85828. set: function (value) {
  85829. var _this = this;
  85830. if (value === this._captureRenderTargetsRenderTime) {
  85831. return;
  85832. }
  85833. this._captureRenderTargetsRenderTime = value;
  85834. if (value) {
  85835. this._onBeforeRenderTargetsRenderObserver = this.scene.OnBeforeRenderTargetsRenderObservable.add(function () {
  85836. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  85837. _this._renderTargetsRenderTime.beginMonitoring();
  85838. });
  85839. this._onAfterRenderTargetsRenderObserver = this.scene.OnAfterRenderTargetsRenderObservable.add(function () {
  85840. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  85841. _this._renderTargetsRenderTime.endMonitoring(false);
  85842. });
  85843. }
  85844. else {
  85845. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  85846. this._onBeforeRenderTargetsRenderObserver = null;
  85847. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  85848. this._onAfterRenderTargetsRenderObserver = null;
  85849. }
  85850. },
  85851. enumerable: true,
  85852. configurable: true
  85853. });
  85854. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  85855. /**
  85856. * Gets the perf counter used for particles render time
  85857. */
  85858. get: function () {
  85859. return this._particlesRenderTime;
  85860. },
  85861. enumerable: true,
  85862. configurable: true
  85863. });
  85864. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  85865. /**
  85866. * Gets the particles render time capture status
  85867. */
  85868. get: function () {
  85869. return this._captureParticlesRenderTime;
  85870. },
  85871. /**
  85872. * Enable or disable the particles render time capture
  85873. */
  85874. set: function (value) {
  85875. var _this = this;
  85876. if (value === this._captureParticlesRenderTime) {
  85877. return;
  85878. }
  85879. this._captureParticlesRenderTime = value;
  85880. if (value) {
  85881. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  85882. BABYLON.Tools.StartPerformanceCounter("Particles");
  85883. _this._particlesRenderTime.beginMonitoring();
  85884. });
  85885. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  85886. BABYLON.Tools.EndPerformanceCounter("Particles");
  85887. _this._particlesRenderTime.endMonitoring(false);
  85888. });
  85889. }
  85890. else {
  85891. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  85892. this._onBeforeParticlesRenderingObserver = null;
  85893. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  85894. this._onAfterParticlesRenderingObserver = null;
  85895. }
  85896. },
  85897. enumerable: true,
  85898. configurable: true
  85899. });
  85900. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  85901. /**
  85902. * Gets the perf counter used for sprites render time
  85903. */
  85904. get: function () {
  85905. return this._spritesRenderTime;
  85906. },
  85907. enumerable: true,
  85908. configurable: true
  85909. });
  85910. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  85911. /**
  85912. * Gets the sprites render time capture status
  85913. */
  85914. get: function () {
  85915. return this._captureSpritesRenderTime;
  85916. },
  85917. /**
  85918. * Enable or disable the sprites render time capture
  85919. */
  85920. set: function (value) {
  85921. var _this = this;
  85922. if (value === this._captureSpritesRenderTime) {
  85923. return;
  85924. }
  85925. this._captureSpritesRenderTime = value;
  85926. if (value) {
  85927. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  85928. BABYLON.Tools.StartPerformanceCounter("Sprites");
  85929. _this._spritesRenderTime.beginMonitoring();
  85930. });
  85931. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  85932. BABYLON.Tools.EndPerformanceCounter("Sprites");
  85933. _this._spritesRenderTime.endMonitoring(false);
  85934. });
  85935. }
  85936. else {
  85937. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  85938. this._onBeforeSpritesRenderingObserver = null;
  85939. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  85940. this._onAfterSpritesRenderingObserver = null;
  85941. }
  85942. },
  85943. enumerable: true,
  85944. configurable: true
  85945. });
  85946. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  85947. /**
  85948. * Gets the perf counter used for physics time
  85949. */
  85950. get: function () {
  85951. return this._physicsTime;
  85952. },
  85953. enumerable: true,
  85954. configurable: true
  85955. });
  85956. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  85957. /**
  85958. * Gets the physics time capture status
  85959. */
  85960. get: function () {
  85961. return this._capturePhysicsTime;
  85962. },
  85963. /**
  85964. * Enable or disable the physics time capture
  85965. */
  85966. set: function (value) {
  85967. var _this = this;
  85968. if (value === this._capturePhysicsTime) {
  85969. return;
  85970. }
  85971. this._capturePhysicsTime = value;
  85972. if (value) {
  85973. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  85974. BABYLON.Tools.StartPerformanceCounter("Physics");
  85975. _this._physicsTime.beginMonitoring();
  85976. });
  85977. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  85978. BABYLON.Tools.EndPerformanceCounter("Physics");
  85979. _this._physicsTime.endMonitoring();
  85980. });
  85981. }
  85982. else {
  85983. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  85984. this._onBeforePhysicsObserver = null;
  85985. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  85986. this._onAfterPhysicsObserver = null;
  85987. }
  85988. },
  85989. enumerable: true,
  85990. configurable: true
  85991. });
  85992. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  85993. /**
  85994. * Gets the perf counter used for animations time
  85995. */
  85996. get: function () {
  85997. return this._animationsTime;
  85998. },
  85999. enumerable: true,
  86000. configurable: true
  86001. });
  86002. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  86003. /**
  86004. * Gets the animations time capture status
  86005. */
  86006. get: function () {
  86007. return this._captureAnimationsTime;
  86008. },
  86009. /**
  86010. * Enable or disable the animations time capture
  86011. */
  86012. set: function (value) {
  86013. var _this = this;
  86014. if (value === this._captureAnimationsTime) {
  86015. return;
  86016. }
  86017. this._captureAnimationsTime = value;
  86018. if (value) {
  86019. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  86020. _this._animationsTime.endMonitoring();
  86021. });
  86022. }
  86023. else {
  86024. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  86025. this._onAfterAnimationsObserver = null;
  86026. }
  86027. },
  86028. enumerable: true,
  86029. configurable: true
  86030. });
  86031. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  86032. /**
  86033. * Gets the perf counter used for frame time capture
  86034. */
  86035. get: function () {
  86036. return this._frameTime;
  86037. },
  86038. enumerable: true,
  86039. configurable: true
  86040. });
  86041. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  86042. /**
  86043. * Gets the frame time capture status
  86044. */
  86045. get: function () {
  86046. return this._captureFrameTime;
  86047. },
  86048. /**
  86049. * Enable or disable the frame time capture
  86050. */
  86051. set: function (value) {
  86052. this._captureFrameTime = value;
  86053. },
  86054. enumerable: true,
  86055. configurable: true
  86056. });
  86057. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  86058. /**
  86059. * Gets the perf counter used for inter-frames time capture
  86060. */
  86061. get: function () {
  86062. return this._interFrameTime;
  86063. },
  86064. enumerable: true,
  86065. configurable: true
  86066. });
  86067. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  86068. /**
  86069. * Gets the inter-frames time capture status
  86070. */
  86071. get: function () {
  86072. return this._captureInterFrameTime;
  86073. },
  86074. /**
  86075. * Enable or disable the inter-frames time capture
  86076. */
  86077. set: function (value) {
  86078. this._captureInterFrameTime = value;
  86079. },
  86080. enumerable: true,
  86081. configurable: true
  86082. });
  86083. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  86084. /**
  86085. * Gets the perf counter used for render time capture
  86086. */
  86087. get: function () {
  86088. return this._renderTime;
  86089. },
  86090. enumerable: true,
  86091. configurable: true
  86092. });
  86093. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  86094. /**
  86095. * Gets the render time capture status
  86096. */
  86097. get: function () {
  86098. return this._captureRenderTime;
  86099. },
  86100. /**
  86101. * Enable or disable the render time capture
  86102. */
  86103. set: function (value) {
  86104. var _this = this;
  86105. if (value === this._captureRenderTime) {
  86106. return;
  86107. }
  86108. this._captureRenderTime = value;
  86109. if (value) {
  86110. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  86111. _this._renderTime.beginMonitoring();
  86112. BABYLON.Tools.StartPerformanceCounter("Main render");
  86113. });
  86114. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  86115. _this._renderTime.endMonitoring(false);
  86116. BABYLON.Tools.EndPerformanceCounter("Main render");
  86117. });
  86118. }
  86119. else {
  86120. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  86121. this._onBeforeDrawPhaseObserver = null;
  86122. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  86123. this._onAfterDrawPhaseObserver = null;
  86124. }
  86125. },
  86126. enumerable: true,
  86127. configurable: true
  86128. });
  86129. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  86130. /**
  86131. * Gets the perf counter used for draw calls
  86132. */
  86133. get: function () {
  86134. return this.scene.getEngine()._drawCalls;
  86135. },
  86136. enumerable: true,
  86137. configurable: true
  86138. });
  86139. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  86140. /**
  86141. * Gets the perf counter used for texture collisions
  86142. */
  86143. get: function () {
  86144. return this.scene.getEngine()._textureCollisions;
  86145. },
  86146. enumerable: true,
  86147. configurable: true
  86148. });
  86149. SceneInstrumentation.prototype.dispose = function () {
  86150. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  86151. this._onAfterRenderObserver = null;
  86152. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  86153. this._onBeforeActiveMeshesEvaluationObserver = null;
  86154. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  86155. this._onAfterActiveMeshesEvaluationObserver = null;
  86156. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  86157. this._onBeforeRenderTargetsRenderObserver = null;
  86158. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  86159. this._onAfterRenderTargetsRenderObserver = null;
  86160. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  86161. this._onBeforeAnimationsObserver = null;
  86162. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  86163. this._onBeforeParticlesRenderingObserver = null;
  86164. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  86165. this._onAfterParticlesRenderingObserver = null;
  86166. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  86167. this._onBeforeSpritesRenderingObserver = null;
  86168. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  86169. this._onAfterSpritesRenderingObserver = null;
  86170. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  86171. this._onBeforeDrawPhaseObserver = null;
  86172. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  86173. this._onAfterDrawPhaseObserver = null;
  86174. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  86175. this._onBeforePhysicsObserver = null;
  86176. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  86177. this._onAfterPhysicsObserver = null;
  86178. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  86179. this._onAfterAnimationsObserver = null;
  86180. this.scene = null;
  86181. };
  86182. return SceneInstrumentation;
  86183. }());
  86184. BABYLON.SceneInstrumentation = SceneInstrumentation;
  86185. })(BABYLON || (BABYLON = {}));
  86186. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  86187. var BABYLON;
  86188. (function (BABYLON) {
  86189. var _TimeToken = /** @class */ (function () {
  86190. function _TimeToken() {
  86191. this._timeElapsedQueryEnded = false;
  86192. }
  86193. return _TimeToken;
  86194. }());
  86195. BABYLON._TimeToken = _TimeToken;
  86196. })(BABYLON || (BABYLON = {}));
  86197. //# sourceMappingURL=babylon.timeToken.js.map
  86198. var BABYLON;
  86199. (function (BABYLON) {
  86200. /**
  86201. * Background material defines definition.
  86202. * @ignore Mainly internal Use
  86203. */
  86204. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  86205. __extends(BackgroundMaterialDefines, _super);
  86206. /**
  86207. * Constructor of the defines.
  86208. */
  86209. function BackgroundMaterialDefines() {
  86210. var _this = _super.call(this) || this;
  86211. /**
  86212. * True if the diffuse texture is in use.
  86213. */
  86214. _this.DIFFUSE = false;
  86215. /**
  86216. * The direct UV channel to use.
  86217. */
  86218. _this.DIFFUSEDIRECTUV = 0;
  86219. /**
  86220. * True if the diffuse texture is in gamma space.
  86221. */
  86222. _this.GAMMADIFFUSE = false;
  86223. /**
  86224. * True if the diffuse texture has opacity in the alpha channel.
  86225. */
  86226. _this.DIFFUSEHASALPHA = false;
  86227. /**
  86228. * True if you want the material to fade to transparent at grazing angle.
  86229. */
  86230. _this.OPACITYFRESNEL = false;
  86231. /**
  86232. * True if an extra blur needs to be added in the reflection.
  86233. */
  86234. _this.REFLECTIONBLUR = false;
  86235. /**
  86236. * True if you want the material to fade to reflection at grazing angle.
  86237. */
  86238. _this.REFLECTIONFRESNEL = false;
  86239. /**
  86240. * True if you want the material to falloff as far as you move away from the scene center.
  86241. */
  86242. _this.REFLECTIONFALLOFF = false;
  86243. /**
  86244. * False if the current Webgl implementation does not support the texture lod extension.
  86245. */
  86246. _this.TEXTURELODSUPPORT = false;
  86247. /**
  86248. * True to ensure the data are premultiplied.
  86249. */
  86250. _this.PREMULTIPLYALPHA = false;
  86251. /**
  86252. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  86253. */
  86254. _this.USERGBCOLOR = false;
  86255. /**
  86256. * True to add noise in order to reduce the banding effect.
  86257. */
  86258. _this.NOISE = false;
  86259. // Image Processing Configuration.
  86260. _this.IMAGEPROCESSING = false;
  86261. _this.VIGNETTE = false;
  86262. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  86263. _this.VIGNETTEBLENDMODEOPAQUE = false;
  86264. _this.TONEMAPPING = false;
  86265. _this.CONTRAST = false;
  86266. _this.COLORCURVES = false;
  86267. _this.COLORGRADING = false;
  86268. _this.COLORGRADING3D = false;
  86269. _this.SAMPLER3DGREENDEPTH = false;
  86270. _this.SAMPLER3DBGRMAP = false;
  86271. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  86272. _this.EXPOSURE = false;
  86273. // Reflection.
  86274. _this.REFLECTION = false;
  86275. _this.REFLECTIONMAP_3D = false;
  86276. _this.REFLECTIONMAP_SPHERICAL = false;
  86277. _this.REFLECTIONMAP_PLANAR = false;
  86278. _this.REFLECTIONMAP_CUBIC = false;
  86279. _this.REFLECTIONMAP_PROJECTION = false;
  86280. _this.REFLECTIONMAP_SKYBOX = false;
  86281. _this.REFLECTIONMAP_EXPLICIT = false;
  86282. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  86283. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  86284. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  86285. _this.INVERTCUBICMAP = false;
  86286. _this.REFLECTIONMAP_OPPOSITEZ = false;
  86287. _this.LODINREFLECTIONALPHA = false;
  86288. _this.GAMMAREFLECTION = false;
  86289. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  86290. // Default BJS.
  86291. _this.MAINUV1 = false;
  86292. _this.MAINUV2 = false;
  86293. _this.UV1 = false;
  86294. _this.UV2 = false;
  86295. _this.CLIPPLANE = false;
  86296. _this.POINTSIZE = false;
  86297. _this.FOG = false;
  86298. _this.NORMAL = false;
  86299. _this.NUM_BONE_INFLUENCERS = 0;
  86300. _this.BonesPerMesh = 0;
  86301. _this.INSTANCES = false;
  86302. _this.SHADOWFLOAT = false;
  86303. _this.rebuild();
  86304. return _this;
  86305. }
  86306. return BackgroundMaterialDefines;
  86307. }(BABYLON.MaterialDefines));
  86308. /**
  86309. * Background material used to create an efficient environement around your scene.
  86310. */
  86311. var BackgroundMaterial = /** @class */ (function (_super) {
  86312. __extends(BackgroundMaterial, _super);
  86313. /**
  86314. * Instantiates a Background Material in the given scene
  86315. * @param name The friendly name of the material
  86316. * @param scene The scene to add the material to
  86317. */
  86318. function BackgroundMaterial(name, scene) {
  86319. var _this = _super.call(this, name, scene) || this;
  86320. /**
  86321. * Key light Color (multiply against the R channel of the environement texture)
  86322. */
  86323. _this.primaryColor = BABYLON.Color3.White();
  86324. /**
  86325. * Key light Level (allowing HDR output of the background)
  86326. */
  86327. _this.primaryLevel = 1;
  86328. /**
  86329. * Secondary light Color (multiply against the G channel of the environement texture)
  86330. */
  86331. _this.secondaryColor = BABYLON.Color3.Gray();
  86332. /**
  86333. * Secondary light Level (allowing HDR output of the background)
  86334. */
  86335. _this.secondaryLevel = 1;
  86336. /**
  86337. * Tertiary light Color (multiply against the B channel of the environement texture)
  86338. */
  86339. _this.tertiaryColor = BABYLON.Color3.Black();
  86340. /**
  86341. * Tertiary light Level (allowing HDR output of the background)
  86342. */
  86343. _this.tertiaryLevel = 1;
  86344. /**
  86345. * Reflection Texture used in the material.
  86346. * Should be author in a specific way for the best result (refer to the documentation).
  86347. */
  86348. _this.reflectionTexture = null;
  86349. /**
  86350. * Reflection Texture level of blur.
  86351. *
  86352. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  86353. * texture twice.
  86354. */
  86355. _this.reflectionBlur = 0;
  86356. /**
  86357. * Diffuse Texture used in the material.
  86358. * Should be author in a specific way for the best result (refer to the documentation).
  86359. */
  86360. _this.diffuseTexture = null;
  86361. _this._shadowLights = null;
  86362. /**
  86363. * Specify the list of lights casting shadow on the material.
  86364. * All scene shadow lights will be included if null.
  86365. */
  86366. _this.shadowLights = null;
  86367. /**
  86368. * For the lights having a blurred shadow generator, this can add a second blur pass in order to reach
  86369. * soft lighting on the background.
  86370. */
  86371. _this.shadowBlurScale = 1;
  86372. /**
  86373. * Helps adjusting the shadow to a softer level if required.
  86374. * 0 means black shadows and 1 means no shadows.
  86375. */
  86376. _this.shadowLevel = 0;
  86377. /**
  86378. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  86379. * It is usually zero but might be interesting to modify according to your setup.
  86380. */
  86381. _this.sceneCenter = BABYLON.Vector3.Zero();
  86382. /**
  86383. * This helps specifying that the material is falling off to the sky box at grazing angle.
  86384. * This helps ensuring a nice transition when the camera goes under the ground.
  86385. */
  86386. _this.opacityFresnel = true;
  86387. /**
  86388. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  86389. * This helps adding a mirror texture on the ground.
  86390. */
  86391. _this.reflectionFresnel = false;
  86392. /**
  86393. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  86394. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  86395. */
  86396. _this.reflectionFalloffDistance = 0.0;
  86397. /**
  86398. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  86399. */
  86400. _this.reflectionAmount = 1.0;
  86401. /**
  86402. * This specifies the weight of the reflection at grazing angle.
  86403. */
  86404. _this.reflectionReflectance0 = 0.05;
  86405. /**
  86406. * This specifies the weight of the reflection at a perpendicular point of view.
  86407. */
  86408. _this.reflectionReflectance90 = 0.5;
  86409. /**
  86410. * Helps to directly use the maps channels instead of their level.
  86411. */
  86412. _this.useRGBColor = true;
  86413. /**
  86414. * This helps reducing the banding effect that could occur on the background.
  86415. */
  86416. _this.enableNoise = false;
  86417. _this._fovMultiplier = 1.0;
  86418. /**
  86419. * Enable the FOV adjustment feature controlled by fovMultiplier.
  86420. * @type {boolean}
  86421. */
  86422. _this.useEquirectangularFOV = false;
  86423. _this._maxSimultaneousLights = 4;
  86424. /**
  86425. * Number of Simultaneous lights allowed on the material.
  86426. */
  86427. _this.maxSimultaneousLights = 4;
  86428. /**
  86429. * Keep track of the image processing observer to allow dispose and replace.
  86430. */
  86431. _this._imageProcessingObserver = null;
  86432. // Temp values kept as cache in the material.
  86433. _this._renderTargets = new BABYLON.SmartArray(16);
  86434. _this._reflectionControls = BABYLON.Vector4.Zero();
  86435. // Setup the default processing configuration to the scene.
  86436. _this._attachImageProcessingConfiguration(null);
  86437. _this.getRenderTargetTextures = function () {
  86438. _this._renderTargets.reset();
  86439. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  86440. _this._renderTargets.push(_this._diffuseTexture);
  86441. }
  86442. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  86443. _this._renderTargets.push(_this._reflectionTexture);
  86444. }
  86445. return _this._renderTargets;
  86446. };
  86447. return _this;
  86448. }
  86449. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  86450. /**
  86451. * Sets the reflection reflectance fresnel values according to the default standard
  86452. * empirically know to work well :-)
  86453. */
  86454. set: function (value) {
  86455. var reflectionWeight = value;
  86456. if (reflectionWeight < 0.5) {
  86457. reflectionWeight = reflectionWeight * 2.0;
  86458. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  86459. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  86460. }
  86461. else {
  86462. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  86463. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  86464. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  86465. }
  86466. },
  86467. enumerable: true,
  86468. configurable: true
  86469. });
  86470. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  86471. /**
  86472. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  86473. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  86474. * Recommended to be keep at 1.0 except for special cases.
  86475. */
  86476. get: function () {
  86477. return this._fovMultiplier;
  86478. },
  86479. set: function (value) {
  86480. if (isNaN(value)) {
  86481. value = 1.0;
  86482. }
  86483. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  86484. },
  86485. enumerable: true,
  86486. configurable: true
  86487. });
  86488. /**
  86489. * Attaches a new image processing configuration to the PBR Material.
  86490. * @param configuration (if null the scene configuration will be use)
  86491. */
  86492. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  86493. var _this = this;
  86494. if (configuration === this._imageProcessingConfiguration) {
  86495. return;
  86496. }
  86497. // Detaches observer.
  86498. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  86499. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  86500. }
  86501. // Pick the scene configuration if needed.
  86502. if (!configuration) {
  86503. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  86504. }
  86505. else {
  86506. this._imageProcessingConfiguration = configuration;
  86507. }
  86508. // Attaches observer.
  86509. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  86510. _this._markAllSubMeshesAsImageProcessingDirty();
  86511. });
  86512. };
  86513. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  86514. /**
  86515. * Gets the image processing configuration used either in this material.
  86516. */
  86517. get: function () {
  86518. return this._imageProcessingConfiguration;
  86519. },
  86520. /**
  86521. * Sets the Default image processing configuration used either in the this material.
  86522. *
  86523. * If sets to null, the scene one is in use.
  86524. */
  86525. set: function (value) {
  86526. this._attachImageProcessingConfiguration(value);
  86527. // Ensure the effect will be rebuilt.
  86528. this._markAllSubMeshesAsTexturesDirty();
  86529. },
  86530. enumerable: true,
  86531. configurable: true
  86532. });
  86533. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  86534. /**
  86535. * Gets wether the color curves effect is enabled.
  86536. */
  86537. get: function () {
  86538. return this.imageProcessingConfiguration.colorCurvesEnabled;
  86539. },
  86540. /**
  86541. * Sets wether the color curves effect is enabled.
  86542. */
  86543. set: function (value) {
  86544. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  86545. },
  86546. enumerable: true,
  86547. configurable: true
  86548. });
  86549. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  86550. /**
  86551. * Gets wether the color grading effect is enabled.
  86552. */
  86553. get: function () {
  86554. return this.imageProcessingConfiguration.colorGradingEnabled;
  86555. },
  86556. /**
  86557. * Gets wether the color grading effect is enabled.
  86558. */
  86559. set: function (value) {
  86560. this.imageProcessingConfiguration.colorGradingEnabled = value;
  86561. },
  86562. enumerable: true,
  86563. configurable: true
  86564. });
  86565. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  86566. /**
  86567. * Gets wether tonemapping is enabled or not.
  86568. */
  86569. get: function () {
  86570. return this._imageProcessingConfiguration.toneMappingEnabled;
  86571. },
  86572. /**
  86573. * Sets wether tonemapping is enabled or not
  86574. */
  86575. set: function (value) {
  86576. this._imageProcessingConfiguration.toneMappingEnabled = value;
  86577. },
  86578. enumerable: true,
  86579. configurable: true
  86580. });
  86581. ;
  86582. ;
  86583. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  86584. /**
  86585. * The camera exposure used on this material.
  86586. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  86587. * This corresponds to a photographic exposure.
  86588. */
  86589. get: function () {
  86590. return this._imageProcessingConfiguration.exposure;
  86591. },
  86592. /**
  86593. * The camera exposure used on this material.
  86594. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  86595. * This corresponds to a photographic exposure.
  86596. */
  86597. set: function (value) {
  86598. this._imageProcessingConfiguration.exposure = value;
  86599. },
  86600. enumerable: true,
  86601. configurable: true
  86602. });
  86603. ;
  86604. ;
  86605. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  86606. /**
  86607. * Gets The camera contrast used on this material.
  86608. */
  86609. get: function () {
  86610. return this._imageProcessingConfiguration.contrast;
  86611. },
  86612. /**
  86613. * Sets The camera contrast used on this material.
  86614. */
  86615. set: function (value) {
  86616. this._imageProcessingConfiguration.contrast = value;
  86617. },
  86618. enumerable: true,
  86619. configurable: true
  86620. });
  86621. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  86622. /**
  86623. * Gets the Color Grading 2D Lookup Texture.
  86624. */
  86625. get: function () {
  86626. return this._imageProcessingConfiguration.colorGradingTexture;
  86627. },
  86628. /**
  86629. * Sets the Color Grading 2D Lookup Texture.
  86630. */
  86631. set: function (value) {
  86632. this.imageProcessingConfiguration.colorGradingTexture = value;
  86633. },
  86634. enumerable: true,
  86635. configurable: true
  86636. });
  86637. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  86638. /**
  86639. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  86640. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  86641. * 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;
  86642. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  86643. */
  86644. get: function () {
  86645. return this.imageProcessingConfiguration.colorCurves;
  86646. },
  86647. /**
  86648. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  86649. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  86650. * 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;
  86651. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  86652. */
  86653. set: function (value) {
  86654. this.imageProcessingConfiguration.colorCurves = value;
  86655. },
  86656. enumerable: true,
  86657. configurable: true
  86658. });
  86659. /**
  86660. * The entire material has been created in order to prevent overdraw.
  86661. * @returns false
  86662. */
  86663. BackgroundMaterial.prototype.needAlphaTesting = function () {
  86664. return true;
  86665. };
  86666. /**
  86667. * The entire material has been created in order to prevent overdraw.
  86668. * @returns true if blending is enable
  86669. */
  86670. BackgroundMaterial.prototype.needAlphaBlending = function () {
  86671. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  86672. };
  86673. /**
  86674. * Checks wether the material is ready to be rendered for a given mesh.
  86675. * @param mesh The mesh to render
  86676. * @param subMesh The submesh to check against
  86677. * @param useInstances Specify wether or not the material is used with instances
  86678. * @returns true if all the dependencies are ready (Textures, Effects...)
  86679. */
  86680. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  86681. var _this = this;
  86682. if (useInstances === void 0) { useInstances = false; }
  86683. if (subMesh.effect && this.isFrozen) {
  86684. if (this._wasPreviouslyReady) {
  86685. return true;
  86686. }
  86687. }
  86688. if (!subMesh._materialDefines) {
  86689. subMesh._materialDefines = new BackgroundMaterialDefines();
  86690. }
  86691. var scene = this.getScene();
  86692. var defines = subMesh._materialDefines;
  86693. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  86694. if (defines._renderId === scene.getRenderId()) {
  86695. return true;
  86696. }
  86697. }
  86698. var engine = scene.getEngine();
  86699. // Lights
  86700. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  86701. defines._needNormals = true;
  86702. // Textures
  86703. if (defines._areTexturesDirty) {
  86704. defines._needUVs = false;
  86705. if (scene.texturesEnabled) {
  86706. if (scene.getEngine().getCaps().textureLOD) {
  86707. defines.TEXTURELODSUPPORT = true;
  86708. }
  86709. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  86710. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  86711. return false;
  86712. }
  86713. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  86714. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  86715. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  86716. defines.OPACITYFRESNEL = this._opacityFresnel;
  86717. }
  86718. else {
  86719. defines.DIFFUSE = false;
  86720. defines.DIFFUSEHASALPHA = false;
  86721. defines.GAMMADIFFUSE = false;
  86722. defines.OPACITYFRESNEL = false;
  86723. }
  86724. var reflectionTexture = this._reflectionTexture;
  86725. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  86726. if (!reflectionTexture.isReadyOrNotBlocking()) {
  86727. return false;
  86728. }
  86729. defines.REFLECTION = true;
  86730. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  86731. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  86732. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  86733. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  86734. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  86735. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  86736. defines.INVERTCUBICMAP = true;
  86737. }
  86738. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  86739. switch (reflectionTexture.coordinatesMode) {
  86740. case BABYLON.Texture.CUBIC_MODE:
  86741. case BABYLON.Texture.INVCUBIC_MODE:
  86742. defines.REFLECTIONMAP_CUBIC = true;
  86743. break;
  86744. case BABYLON.Texture.EXPLICIT_MODE:
  86745. defines.REFLECTIONMAP_EXPLICIT = true;
  86746. break;
  86747. case BABYLON.Texture.PLANAR_MODE:
  86748. defines.REFLECTIONMAP_PLANAR = true;
  86749. break;
  86750. case BABYLON.Texture.PROJECTION_MODE:
  86751. defines.REFLECTIONMAP_PROJECTION = true;
  86752. break;
  86753. case BABYLON.Texture.SKYBOX_MODE:
  86754. defines.REFLECTIONMAP_SKYBOX = true;
  86755. break;
  86756. case BABYLON.Texture.SPHERICAL_MODE:
  86757. defines.REFLECTIONMAP_SPHERICAL = true;
  86758. break;
  86759. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  86760. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  86761. break;
  86762. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  86763. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  86764. break;
  86765. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  86766. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  86767. break;
  86768. }
  86769. if (this.reflectionFresnel) {
  86770. defines.REFLECTIONFRESNEL = true;
  86771. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  86772. this._reflectionControls.x = this.reflectionAmount;
  86773. this._reflectionControls.y = this.reflectionReflectance0;
  86774. this._reflectionControls.z = this.reflectionReflectance90;
  86775. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  86776. }
  86777. else {
  86778. defines.REFLECTIONFRESNEL = false;
  86779. defines.REFLECTIONFALLOFF = false;
  86780. }
  86781. }
  86782. else {
  86783. defines.REFLECTION = false;
  86784. defines.REFLECTIONFALLOFF = false;
  86785. defines.REFLECTIONBLUR = false;
  86786. defines.REFLECTIONMAP_3D = false;
  86787. defines.REFLECTIONMAP_SPHERICAL = false;
  86788. defines.REFLECTIONMAP_PLANAR = false;
  86789. defines.REFLECTIONMAP_CUBIC = false;
  86790. defines.REFLECTIONMAP_PROJECTION = false;
  86791. defines.REFLECTIONMAP_SKYBOX = false;
  86792. defines.REFLECTIONMAP_EXPLICIT = false;
  86793. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  86794. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  86795. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  86796. defines.INVERTCUBICMAP = false;
  86797. defines.REFLECTIONMAP_OPPOSITEZ = false;
  86798. defines.LODINREFLECTIONALPHA = false;
  86799. defines.GAMMAREFLECTION = false;
  86800. }
  86801. }
  86802. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  86803. defines.USERGBCOLOR = this._useRGBColor;
  86804. defines.NOISE = this._enableNoise;
  86805. }
  86806. if (defines._areImageProcessingDirty) {
  86807. if (!this._imageProcessingConfiguration.isReady()) {
  86808. return false;
  86809. }
  86810. this._imageProcessingConfiguration.prepareDefines(defines);
  86811. }
  86812. // Misc.
  86813. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  86814. // Values that need to be evaluated on every frame
  86815. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  86816. // Attribs
  86817. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  86818. if (mesh) {
  86819. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  86820. mesh.createNormals(true);
  86821. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  86822. }
  86823. }
  86824. }
  86825. // Get correct effect
  86826. if (defines.isDirty) {
  86827. defines.markAsProcessed();
  86828. scene.resetCachedMaterial();
  86829. // Fallbacks
  86830. var fallbacks = new BABYLON.EffectFallbacks();
  86831. if (defines.FOG) {
  86832. fallbacks.addFallback(0, "FOG");
  86833. }
  86834. if (defines.POINTSIZE) {
  86835. fallbacks.addFallback(1, "POINTSIZE");
  86836. }
  86837. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  86838. if (defines.NUM_BONE_INFLUENCERS > 0) {
  86839. fallbacks.addCPUSkinningFallback(0, mesh);
  86840. }
  86841. //Attributes
  86842. var attribs = [BABYLON.VertexBuffer.PositionKind];
  86843. if (defines.NORMAL) {
  86844. attribs.push(BABYLON.VertexBuffer.NormalKind);
  86845. }
  86846. if (defines.UV1) {
  86847. attribs.push(BABYLON.VertexBuffer.UVKind);
  86848. }
  86849. if (defines.UV2) {
  86850. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  86851. }
  86852. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  86853. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  86854. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  86855. "vFogInfos", "vFogColor", "pointSize",
  86856. "vClipPlane", "mBones",
  86857. "vPrimaryColor", "vSecondaryColor", "vTertiaryColor",
  86858. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  86859. "shadowLevel", "alpha",
  86860. "vBackgroundCenter", "vReflectionControl",
  86861. "vDiffuseInfos", "diffuseMatrix",
  86862. ];
  86863. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  86864. var uniformBuffers = ["Material", "Scene"];
  86865. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  86866. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  86867. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  86868. uniformsNames: uniforms,
  86869. uniformBuffersNames: uniformBuffers,
  86870. samplers: samplers,
  86871. defines: defines,
  86872. maxSimultaneousLights: this._maxSimultaneousLights
  86873. });
  86874. var onCompiled = function (effect) {
  86875. if (_this.onCompiled) {
  86876. _this.onCompiled(effect);
  86877. }
  86878. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  86879. };
  86880. var join = defines.toString();
  86881. subMesh.setEffect(scene.getEngine().createEffect("background", {
  86882. attributes: attribs,
  86883. uniformsNames: uniforms,
  86884. uniformBuffersNames: uniformBuffers,
  86885. samplers: samplers,
  86886. defines: join,
  86887. fallbacks: fallbacks,
  86888. onCompiled: onCompiled,
  86889. onError: this.onError,
  86890. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  86891. }, engine), defines);
  86892. this.buildUniformLayout();
  86893. }
  86894. if (!subMesh.effect || !subMesh.effect.isReady()) {
  86895. return false;
  86896. }
  86897. defines._renderId = scene.getRenderId();
  86898. this._wasPreviouslyReady = true;
  86899. return true;
  86900. };
  86901. /**
  86902. * Build the uniform buffer used in the material.
  86903. */
  86904. BackgroundMaterial.prototype.buildUniformLayout = function () {
  86905. // Order is important !
  86906. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  86907. this._uniformBuffer.addUniform("vSecondaryColor", 4);
  86908. this._uniformBuffer.addUniform("vTertiaryColor", 4);
  86909. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  86910. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  86911. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  86912. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  86913. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  86914. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  86915. this._uniformBuffer.addUniform("pointSize", 1);
  86916. this._uniformBuffer.addUniform("shadowLevel", 1);
  86917. this._uniformBuffer.addUniform("alpha", 1);
  86918. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  86919. this._uniformBuffer.addUniform("vReflectionControl", 4);
  86920. this._uniformBuffer.create();
  86921. };
  86922. /**
  86923. * Unbind the material.
  86924. */
  86925. BackgroundMaterial.prototype.unbind = function () {
  86926. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  86927. this._uniformBuffer.setTexture("diffuseSampler", null);
  86928. }
  86929. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  86930. this._uniformBuffer.setTexture("reflectionSampler", null);
  86931. }
  86932. _super.prototype.unbind.call(this);
  86933. };
  86934. /**
  86935. * Bind only the world matrix to the material.
  86936. * @param world The world matrix to bind.
  86937. */
  86938. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  86939. this._activeEffect.setMatrix("world", world);
  86940. };
  86941. /**
  86942. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  86943. * @param world The world matrix to bind.
  86944. * @param subMesh The submesh to bind for.
  86945. */
  86946. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  86947. var scene = this.getScene();
  86948. var defines = subMesh._materialDefines;
  86949. if (!defines) {
  86950. return;
  86951. }
  86952. var effect = subMesh.effect;
  86953. if (!effect) {
  86954. return;
  86955. }
  86956. this._activeEffect = effect;
  86957. // Matrices
  86958. this.bindOnlyWorldMatrix(world);
  86959. // Bones
  86960. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  86961. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  86962. if (mustRebind) {
  86963. this._uniformBuffer.bindToEffect(effect, "Material");
  86964. this.bindViewProjection(effect);
  86965. var reflectionTexture = this._reflectionTexture;
  86966. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  86967. // Texture uniforms
  86968. if (scene.texturesEnabled) {
  86969. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  86970. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  86971. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  86972. }
  86973. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  86974. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  86975. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  86976. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  86977. }
  86978. }
  86979. if (this.shadowLevel > 0) {
  86980. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  86981. }
  86982. this._uniformBuffer.updateFloat("alpha", this.alpha);
  86983. // Point size
  86984. if (this.pointsCloud) {
  86985. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  86986. }
  86987. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, this._primaryLevel);
  86988. this._uniformBuffer.updateColor4("vSecondaryColor", this._secondaryColor, this._secondaryLevel);
  86989. this._uniformBuffer.updateColor4("vTertiaryColor", this._tertiaryColor, this._tertiaryLevel);
  86990. }
  86991. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  86992. // Textures
  86993. if (scene.texturesEnabled) {
  86994. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  86995. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  86996. }
  86997. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  86998. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  86999. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  87000. }
  87001. else if (!defines.REFLECTIONBLUR) {
  87002. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  87003. }
  87004. else {
  87005. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  87006. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  87007. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  87008. }
  87009. if (defines.REFLECTIONFRESNEL) {
  87010. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  87011. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  87012. }
  87013. }
  87014. }
  87015. // Clip plane
  87016. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  87017. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  87018. }
  87019. if (mustRebind || !this.isFrozen) {
  87020. if (scene.lightsEnabled) {
  87021. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  87022. }
  87023. // View
  87024. this.bindView(effect);
  87025. // Fog
  87026. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  87027. // image processing
  87028. this._imageProcessingConfiguration.bind(this._activeEffect);
  87029. }
  87030. this._uniformBuffer.update();
  87031. this._afterBind(mesh);
  87032. };
  87033. /**
  87034. * Dispose the material.
  87035. * @param forceDisposeEffect Force disposal of the associated effect.
  87036. * @param forceDisposeTextures Force disposal of the associated textures.
  87037. */
  87038. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  87039. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  87040. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  87041. if (forceDisposeTextures) {
  87042. if (this.diffuseTexture) {
  87043. this.diffuseTexture.dispose();
  87044. }
  87045. if (this.reflectionTexture) {
  87046. this.reflectionTexture.dispose();
  87047. }
  87048. }
  87049. this._renderTargets.dispose();
  87050. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  87051. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  87052. }
  87053. _super.prototype.dispose.call(this, forceDisposeEffect);
  87054. };
  87055. /**
  87056. * Clones the material.
  87057. * @param name The cloned name.
  87058. * @returns The cloned material.
  87059. */
  87060. BackgroundMaterial.prototype.clone = function (name) {
  87061. var _this = this;
  87062. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  87063. };
  87064. /**
  87065. * Serializes the current material to its JSON representation.
  87066. * @returns The JSON representation.
  87067. */
  87068. BackgroundMaterial.prototype.serialize = function () {
  87069. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  87070. serializationObject.customType = "BABYLON.BackgroundMaterial";
  87071. return serializationObject;
  87072. };
  87073. /**
  87074. * Gets the class name of the material
  87075. * @returns "BackgroundMaterial"
  87076. */
  87077. BackgroundMaterial.prototype.getClassName = function () {
  87078. return "BackgroundMaterial";
  87079. };
  87080. /**
  87081. * Parse a JSON input to create back a background material.
  87082. * @param source The JSON data to parse
  87083. * @param scene The scene to create the parsed material in
  87084. * @param rootUrl The root url of the assets the material depends upon
  87085. * @returns the instantiated BackgroundMaterial.
  87086. */
  87087. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  87088. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  87089. };
  87090. /**
  87091. * Standard reflectance value at parallel view angle.
  87092. */
  87093. BackgroundMaterial.StandardReflectance0 = 0.05;
  87094. /**
  87095. * Standard reflectance value at grazing angle.
  87096. */
  87097. BackgroundMaterial.StandardReflectance90 = 0.5;
  87098. __decorate([
  87099. BABYLON.serializeAsColor3()
  87100. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  87101. __decorate([
  87102. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  87103. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  87104. __decorate([
  87105. BABYLON.serialize()
  87106. ], BackgroundMaterial.prototype, "_primaryLevel", void 0);
  87107. __decorate([
  87108. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  87109. ], BackgroundMaterial.prototype, "primaryLevel", void 0);
  87110. __decorate([
  87111. BABYLON.serializeAsColor3()
  87112. ], BackgroundMaterial.prototype, "_secondaryColor", void 0);
  87113. __decorate([
  87114. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  87115. ], BackgroundMaterial.prototype, "secondaryColor", void 0);
  87116. __decorate([
  87117. BABYLON.serialize()
  87118. ], BackgroundMaterial.prototype, "_secondaryLevel", void 0);
  87119. __decorate([
  87120. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  87121. ], BackgroundMaterial.prototype, "secondaryLevel", void 0);
  87122. __decorate([
  87123. BABYLON.serializeAsColor3()
  87124. ], BackgroundMaterial.prototype, "_tertiaryColor", void 0);
  87125. __decorate([
  87126. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  87127. ], BackgroundMaterial.prototype, "tertiaryColor", void 0);
  87128. __decorate([
  87129. BABYLON.serialize()
  87130. ], BackgroundMaterial.prototype, "_tertiaryLevel", void 0);
  87131. __decorate([
  87132. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  87133. ], BackgroundMaterial.prototype, "tertiaryLevel", void 0);
  87134. __decorate([
  87135. BABYLON.serializeAsTexture()
  87136. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  87137. __decorate([
  87138. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87139. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  87140. __decorate([
  87141. BABYLON.serialize()
  87142. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  87143. __decorate([
  87144. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87145. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  87146. __decorate([
  87147. BABYLON.serializeAsTexture()
  87148. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  87149. __decorate([
  87150. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87151. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  87152. __decorate([
  87153. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87154. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  87155. __decorate([
  87156. BABYLON.serialize()
  87157. ], BackgroundMaterial.prototype, "_shadowBlurScale", void 0);
  87158. __decorate([
  87159. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87160. ], BackgroundMaterial.prototype, "shadowBlurScale", void 0);
  87161. __decorate([
  87162. BABYLON.serialize()
  87163. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  87164. __decorate([
  87165. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87166. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  87167. __decorate([
  87168. BABYLON.serializeAsVector3()
  87169. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  87170. __decorate([
  87171. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87172. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  87173. __decorate([
  87174. BABYLON.serialize()
  87175. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  87176. __decorate([
  87177. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87178. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  87179. __decorate([
  87180. BABYLON.serialize()
  87181. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  87182. __decorate([
  87183. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87184. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  87185. __decorate([
  87186. BABYLON.serialize()
  87187. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  87188. __decorate([
  87189. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87190. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  87191. __decorate([
  87192. BABYLON.serialize()
  87193. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  87194. __decorate([
  87195. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87196. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  87197. __decorate([
  87198. BABYLON.serialize()
  87199. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  87200. __decorate([
  87201. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87202. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  87203. __decorate([
  87204. BABYLON.serialize()
  87205. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  87206. __decorate([
  87207. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87208. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  87209. __decorate([
  87210. BABYLON.serialize()
  87211. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  87212. __decorate([
  87213. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87214. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  87215. __decorate([
  87216. BABYLON.serialize()
  87217. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  87218. __decorate([
  87219. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87220. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  87221. __decorate([
  87222. BABYLON.serialize()
  87223. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  87224. __decorate([
  87225. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87226. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  87227. __decorate([
  87228. BABYLON.serializeAsImageProcessingConfiguration()
  87229. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  87230. return BackgroundMaterial;
  87231. }(BABYLON.PushMaterial));
  87232. BABYLON.BackgroundMaterial = BackgroundMaterial;
  87233. })(BABYLON || (BABYLON = {}));
  87234. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  87235. var __assign = (this && this.__assign) || Object.assign || function(t) {
  87236. for (var s, i = 1, n = arguments.length; i < n; i++) {
  87237. s = arguments[i];
  87238. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  87239. t[p] = s[p];
  87240. }
  87241. return t;
  87242. };
  87243. var BABYLON;
  87244. (function (BABYLON) {
  87245. /**
  87246. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  87247. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  87248. * It also helps with the default setup of your imageProcessing configuration.
  87249. */
  87250. var EnvironmentHelper = /** @class */ (function () {
  87251. /**
  87252. * constructor
  87253. * @param options
  87254. * @param scene The scene to add the material to
  87255. */
  87256. function EnvironmentHelper(options, scene) {
  87257. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  87258. this._scene = scene;
  87259. this._setupBackground();
  87260. this._setupImageProcessing();
  87261. }
  87262. /**
  87263. * Creates the default options for the helper.
  87264. */
  87265. EnvironmentHelper._getDefaultOptions = function () {
  87266. return {
  87267. createGround: true,
  87268. groundSize: 15,
  87269. groundTexture: this._groundTextureCDNUrl,
  87270. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  87271. groundOpacity: 0.9,
  87272. enableGroundShadow: true,
  87273. groundShadowLevel: 0.5,
  87274. enableGroundMirror: false,
  87275. groundMirrorSizeRatio: 0.3,
  87276. groundMirrorBlurKernel: 64,
  87277. groundMirrorAmount: 1,
  87278. groundMirrorFresnelWeight: 1,
  87279. groundMirrorFallOffDistance: 0,
  87280. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  87281. groundYBias: 0.00001,
  87282. createSkybox: true,
  87283. skyboxSize: 20,
  87284. skyboxTexture: this._skyboxTextureCDNUrl,
  87285. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  87286. backgroundYRotation: 0,
  87287. sizeAuto: true,
  87288. rootPosition: BABYLON.Vector3.Zero(),
  87289. setupImageProcessing: true,
  87290. environmentTexture: this._environmentTextureCDNUrl,
  87291. cameraExposure: 0.8,
  87292. cameraContrast: 1.2,
  87293. toneMappingEnabled: true,
  87294. };
  87295. };
  87296. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  87297. /**
  87298. * Gets the root mesh created by the helper.
  87299. */
  87300. get: function () {
  87301. return this._rootMesh;
  87302. },
  87303. enumerable: true,
  87304. configurable: true
  87305. });
  87306. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  87307. /**
  87308. * Gets the skybox created by the helper.
  87309. */
  87310. get: function () {
  87311. return this._skybox;
  87312. },
  87313. enumerable: true,
  87314. configurable: true
  87315. });
  87316. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  87317. /**
  87318. * Gets the skybox texture created by the helper.
  87319. */
  87320. get: function () {
  87321. return this._skyboxTexture;
  87322. },
  87323. enumerable: true,
  87324. configurable: true
  87325. });
  87326. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  87327. /**
  87328. * Gets the skybox material created by the helper.
  87329. */
  87330. get: function () {
  87331. return this._skyboxMaterial;
  87332. },
  87333. enumerable: true,
  87334. configurable: true
  87335. });
  87336. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  87337. /**
  87338. * Gets the ground mesh created by the helper.
  87339. */
  87340. get: function () {
  87341. return this._ground;
  87342. },
  87343. enumerable: true,
  87344. configurable: true
  87345. });
  87346. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  87347. /**
  87348. * Gets the ground texture created by the helper.
  87349. */
  87350. get: function () {
  87351. return this._groundTexture;
  87352. },
  87353. enumerable: true,
  87354. configurable: true
  87355. });
  87356. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  87357. /**
  87358. * Gets the ground mirror created by the helper.
  87359. */
  87360. get: function () {
  87361. return this._groundMirror;
  87362. },
  87363. enumerable: true,
  87364. configurable: true
  87365. });
  87366. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  87367. /**
  87368. * Gets the ground mirror render list to helps pushing the meshes
  87369. * you wish in the ground reflection.
  87370. */
  87371. get: function () {
  87372. if (this._groundMirror) {
  87373. return this._groundMirror.renderList;
  87374. }
  87375. return null;
  87376. },
  87377. enumerable: true,
  87378. configurable: true
  87379. });
  87380. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  87381. /**
  87382. * Gets the ground material created by the helper.
  87383. */
  87384. get: function () {
  87385. return this._groundMaterial;
  87386. },
  87387. enumerable: true,
  87388. configurable: true
  87389. });
  87390. /**
  87391. * Updates the background according to the new options
  87392. * @param options
  87393. */
  87394. EnvironmentHelper.prototype.updateOptions = function (options) {
  87395. var newOptions = __assign({}, this._options, options);
  87396. if (this._ground && !newOptions.createGround) {
  87397. this._ground.dispose();
  87398. this._ground = null;
  87399. }
  87400. if (this._groundMaterial && !newOptions.createGround) {
  87401. this._groundMaterial.dispose();
  87402. this._groundMaterial = null;
  87403. }
  87404. if (this._groundTexture) {
  87405. if (this._options.groundTexture != newOptions.groundTexture) {
  87406. this._groundTexture.dispose();
  87407. this._groundTexture = null;
  87408. }
  87409. }
  87410. if (this._skybox && !newOptions.createSkybox) {
  87411. this._skybox.dispose();
  87412. this._skybox = null;
  87413. }
  87414. if (this._skyboxMaterial && !newOptions.createSkybox) {
  87415. this._skyboxMaterial.dispose();
  87416. this._skyboxMaterial = null;
  87417. }
  87418. if (this._skyboxTexture) {
  87419. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  87420. this._skyboxTexture.dispose();
  87421. this._skyboxTexture = null;
  87422. }
  87423. }
  87424. if (this._groundMirror && !newOptions.enableGroundMirror) {
  87425. this._groundMirror.dispose();
  87426. this._groundMirror = null;
  87427. }
  87428. if (this._scene.environmentTexture) {
  87429. if (this._options.environmentTexture != newOptions.environmentTexture) {
  87430. this._scene.environmentTexture.dispose();
  87431. }
  87432. }
  87433. this._options = newOptions;
  87434. this._setupBackground();
  87435. this._setupImageProcessing();
  87436. };
  87437. /**
  87438. * Sets the primary color of all the available elements.
  87439. * @param color
  87440. */
  87441. EnvironmentHelper.prototype.setMainColor = function (color) {
  87442. if (this.groundMaterial) {
  87443. this.groundMaterial.primaryColor = color;
  87444. }
  87445. if (this.skyboxMaterial) {
  87446. this.skyboxMaterial.primaryColor = color;
  87447. }
  87448. if (this.groundMirror) {
  87449. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  87450. }
  87451. };
  87452. /**
  87453. * Setup the image processing according to the specified options.
  87454. */
  87455. EnvironmentHelper.prototype._setupImageProcessing = function () {
  87456. if (this._options.setupImageProcessing) {
  87457. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  87458. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  87459. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  87460. this._setupEnvironmentTexture();
  87461. }
  87462. };
  87463. /**
  87464. * Setup the environment texture according to the specified options.
  87465. */
  87466. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  87467. if (this._scene.environmentTexture) {
  87468. return;
  87469. }
  87470. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  87471. this._scene.environmentTexture = this._options.environmentTexture;
  87472. return;
  87473. }
  87474. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  87475. this._scene.environmentTexture = environmentTexture;
  87476. };
  87477. /**
  87478. * Setup the background according to the specified options.
  87479. */
  87480. EnvironmentHelper.prototype._setupBackground = function () {
  87481. if (!this._rootMesh) {
  87482. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  87483. }
  87484. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  87485. var sceneSize = this._getSceneSize();
  87486. if (this._options.createGround) {
  87487. this._setupGround(sceneSize);
  87488. this._setupGroundMaterial();
  87489. this._setupGroundDiffuseTexture();
  87490. if (this._options.enableGroundMirror) {
  87491. this._setupGroundMirrorTexture(sceneSize);
  87492. }
  87493. this._setupMirrorInGroundMaterial();
  87494. }
  87495. if (this._options.createSkybox) {
  87496. this._setupSkybox(sceneSize);
  87497. this._setupSkyboxMaterial();
  87498. this._setupSkyboxReflectionTexture();
  87499. }
  87500. this._rootMesh.position.x = sceneSize.rootPosition.x;
  87501. this._rootMesh.position.z = sceneSize.rootPosition.z;
  87502. this._rootMesh.position.y = sceneSize.rootPosition.y;
  87503. };
  87504. /**
  87505. * Get the scene sizes according to the setup.
  87506. */
  87507. EnvironmentHelper.prototype._getSceneSize = function () {
  87508. var groundSize = this._options.groundSize;
  87509. var skyboxSize = this._options.skyboxSize;
  87510. var rootPosition = this._options.rootPosition;
  87511. if (!this._scene.meshes || this._scene.meshes.length === 1) {
  87512. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  87513. }
  87514. var sceneExtends = this._scene.getWorldExtends();
  87515. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  87516. if (this._options.sizeAuto) {
  87517. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  87518. this._scene.activeCamera.upperRadiusLimit) {
  87519. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  87520. skyboxSize = groundSize;
  87521. }
  87522. var sceneDiagonalLenght = sceneDiagonal.length();
  87523. if (sceneDiagonalLenght > groundSize) {
  87524. groundSize = sceneDiagonalLenght * 2;
  87525. skyboxSize = groundSize;
  87526. }
  87527. // 10 % bigger.
  87528. groundSize *= 1.1;
  87529. skyboxSize *= 1.5;
  87530. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  87531. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  87532. }
  87533. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  87534. };
  87535. /**
  87536. * Setup the ground according to the specified options.
  87537. */
  87538. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  87539. var _this = this;
  87540. if (!this._ground) {
  87541. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  87542. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  87543. this._ground.parent = this._rootMesh;
  87544. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  87545. }
  87546. this._ground.receiveShadows = this._options.enableGroundShadow;
  87547. };
  87548. /**
  87549. * Setup the ground material according to the specified options.
  87550. */
  87551. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  87552. if (!this._groundMaterial) {
  87553. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  87554. }
  87555. this._groundMaterial.alpha = this._options.groundOpacity;
  87556. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  87557. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  87558. this._groundMaterial.primaryLevel = 1;
  87559. this._groundMaterial.primaryColor = this._options.groundColor;
  87560. this._groundMaterial.secondaryLevel = 0;
  87561. this._groundMaterial.tertiaryLevel = 0;
  87562. this._groundMaterial.useRGBColor = false;
  87563. this._groundMaterial.enableNoise = true;
  87564. if (this._ground) {
  87565. this._ground.material = this._groundMaterial;
  87566. }
  87567. };
  87568. /**
  87569. * Setup the ground diffuse texture according to the specified options.
  87570. */
  87571. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  87572. if (!this._groundMaterial) {
  87573. return;
  87574. }
  87575. if (this._groundTexture) {
  87576. return;
  87577. }
  87578. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  87579. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  87580. return;
  87581. }
  87582. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene);
  87583. diffuseTexture.gammaSpace = false;
  87584. diffuseTexture.hasAlpha = true;
  87585. this._groundMaterial.diffuseTexture = diffuseTexture;
  87586. };
  87587. /**
  87588. * Setup the ground mirror texture according to the specified options.
  87589. */
  87590. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  87591. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  87592. if (!this._groundMirror) {
  87593. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  87594. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  87595. this._groundMirror.anisotropicFilteringLevel = 1;
  87596. this._groundMirror.wrapU = wrapping;
  87597. this._groundMirror.wrapV = wrapping;
  87598. this._groundMirror.gammaSpace = false;
  87599. if (this._groundMirror.renderList) {
  87600. for (var i = 0; i < this._scene.meshes.length; i++) {
  87601. var mesh = this._scene.meshes[i];
  87602. if (mesh !== this._ground &&
  87603. mesh !== this._skybox &&
  87604. mesh !== this._rootMesh) {
  87605. this._groundMirror.renderList.push(mesh);
  87606. }
  87607. }
  87608. }
  87609. }
  87610. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  87611. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  87612. };
  87613. /**
  87614. * Setup the ground to receive the mirror texture.
  87615. */
  87616. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  87617. if (this._groundMaterial) {
  87618. this._groundMaterial.reflectionTexture = this._groundMirror;
  87619. this._groundMaterial.reflectionFresnel = true;
  87620. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  87621. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  87622. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  87623. }
  87624. };
  87625. /**
  87626. * Setup the skybox according to the specified options.
  87627. */
  87628. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  87629. var _this = this;
  87630. if (!this._skybox) {
  87631. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  87632. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  87633. }
  87634. this._skybox.parent = this._rootMesh;
  87635. };
  87636. /**
  87637. * Setup the skybox material according to the specified options.
  87638. */
  87639. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  87640. if (!this._skybox) {
  87641. return;
  87642. }
  87643. if (!this._skyboxMaterial) {
  87644. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  87645. }
  87646. this._skyboxMaterial.useRGBColor = false;
  87647. this._skyboxMaterial.primaryLevel = 1;
  87648. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  87649. this._skyboxMaterial.secondaryLevel = 0;
  87650. this._skyboxMaterial.tertiaryLevel = 0;
  87651. this._skyboxMaterial.enableNoise = true;
  87652. this._skybox.material = this._skyboxMaterial;
  87653. };
  87654. /**
  87655. * Setup the skybox reflection texture according to the specified options.
  87656. */
  87657. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  87658. if (!this._skyboxMaterial) {
  87659. return;
  87660. }
  87661. if (this._skyboxTexture) {
  87662. return;
  87663. }
  87664. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  87665. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  87666. return;
  87667. }
  87668. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene);
  87669. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  87670. this._skyboxTexture.gammaSpace = false;
  87671. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  87672. };
  87673. /**
  87674. * Dispose all the elements created by the Helper.
  87675. */
  87676. EnvironmentHelper.prototype.dispose = function () {
  87677. if (this._groundMaterial) {
  87678. this._groundMaterial.dispose(true, true);
  87679. }
  87680. if (this._skyboxMaterial) {
  87681. this._skyboxMaterial.dispose(true, true);
  87682. }
  87683. this._rootMesh.dispose(false);
  87684. };
  87685. /**
  87686. * Default ground texture URL.
  87687. */
  87688. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  87689. /**
  87690. * Default skybox texture URL.
  87691. */
  87692. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  87693. /**
  87694. * Default environment texture URL.
  87695. */
  87696. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.dds";
  87697. return EnvironmentHelper;
  87698. }());
  87699. BABYLON.EnvironmentHelper = EnvironmentHelper;
  87700. })(BABYLON || (BABYLON = {}));
  87701. //# sourceMappingURL=babylon.environmentHelper.js.map
  87702. BABYLON.Effect.ShadersStore={"defaultVertexShader":"#include<__decl__defaultVertex>\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 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>\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#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}","defaultPixelShader":"#include<__decl__defaultFragment>\n#if defined(BUMP) || !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\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\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>\nvoid main(void) {\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<0.4)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\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)\n{\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb*vRefractionInfos.x;\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*vRefractionInfos.x;\n#endif\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*vReflectionInfos.x;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb*vReflectionInfos.x;\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*vReflectionInfos.x;\n#endif\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#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\ngl_FragColor=color;\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)\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#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\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\n#ifdef REFRACTION\nvec3 environmentRefraction=vec3(0.,0.,0.);\nvec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);\n#ifdef REFRACTIONMAP_OPPOSITEZ\nrefractionVector.z*=-1.0;\n#endif\n\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nvec3 refractionCoords=refractionVector;\nrefractionCoords=vec3(refractionMatrix*vec4(refractionCoords,0));\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\n#endif\n#ifdef LODINREFRACTIONALPHA\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,1.0);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nrefractionLOD=refractionLOD*vRefractionMicrosurfaceInfos.y+vRefractionMicrosurfaceInfos.z;\n#ifdef LODINREFRACTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticRefractionLOD=UNPACK_LOD(sampleRefraction(refractionSampler,refractionCoords).a);\nfloat requestedRefractionLOD=max(automaticRefractionLOD,refractionLOD);\n#else\nfloat requestedRefractionLOD=refractionLOD;\n#endif\nenvironmentRefraction=sampleRefractionLod(refractionSampler,refractionCoords,requestedRefractionLOD).rgb;\n#else\nfloat lodRefractionNormalized=clamp(refractionLOD/log2(vRefractionMicrosurfaceInfos.x),0.,1.);\nfloat lodRefractionNormalizedDoubled=lodRefractionNormalized*2.0;\nvec3 environmentRefractionMid=sampleRefraction(refractionSampler,refractionCoords).rgb;\nif(lodRefractionNormalizedDoubled<1.0){\nenvironmentRefraction=mix(\nsampleRefraction(refractionSamplerHigh,refractionCoords).rgb,\nenvironmentRefractionMid,\nlodRefractionNormalizedDoubled\n);\n}else{\nenvironmentRefraction=mix(\nenvironmentRefractionMid,\nsampleRefraction(refractionSamplerLow,refractionCoords).rgb,\nlodRefractionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFRACTION\nenvironmentRefraction=toLinearSpace(environmentRefraction.rgb);\n#endif\n\nenvironmentRefraction*=vRefractionInfos.x;\n#endif\n\n#ifdef REFLECTION\nvec3 environmentRadiance=vec3(0.,0.,0.);\nvec3 environmentIrradiance=vec3(0.,0.,0.);\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,1.);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nreflectionLOD=reflectionLOD*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\n#ifdef LODINREFLECTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticReflectionLOD=UNPACK_LOD(sampleReflection(reflectionSampler,reflectionCoords).a);\nfloat requestedReflectionLOD=max(automaticReflectionLOD,reflectionLOD);\n#else\nfloat requestedReflectionLOD=reflectionLOD;\n#endif\nenvironmentRadiance=sampleReflectionLod(reflectionSampler,reflectionCoords,requestedReflectionLOD).rgb;\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x),0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec3 environmentSpecularMid=sampleReflection(reflectionSampler,reflectionCoords).rgb;\nif(lodReflectionNormalizedDoubled<1.0){\nenvironmentRadiance=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nenvironmentSpecularMid,\nlodReflectionNormalizedDoubled\n);\n}else{\nenvironmentRadiance=mix(\nenvironmentSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFLECTION\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\n#endif\n\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#if defined(NORMAL) && defined(USESPHERICALINVERTEX)\nenvironmentIrradiance=vEnvironmentIrradiance;\n#else\nvec3 irradianceVector=vec3(reflectionMatrix*vec4(normalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nirradianceVector.z*=-1.0;\n#endif\nenvironmentIrradiance=environmentIrradianceJones(irradianceVector);\n#endif\n#endif\n\nenvironmentRadiance*=vReflectionInfos.x;\nenvironmentRadiance*=vReflectionColor.rgb;\nenvironmentIrradiance*=vReflectionColor.rgb;\n#endif\n\n\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\nfloat reflectance90=fresnelGrazingReflectance(reflectance);\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0)*reflectance90;\n\nvec3 diffuseBase=vec3(0.,0.,0.);\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*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(reflectionCoords,normalW);\nspecularEnvironmentReflectance*=eho;\n#endif\n#endif\n#endif\n#else\n\nvec3 specularEnvironmentReflectance=fresnelSchlickEnvironmentGGX(NdotV,specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n#endif\n\n#ifdef REFRACTION\nvec3 refractance=vec3(0.0,0.0,0.0);\nvec3 transmission=vec3(1.0,1.0,1.0);\n#ifdef LINKREFRACTIONTOTRANSPARENCY\n\ntransmission*=(1.0-alpha);\n\n\nvec3 mixedAlbedo=surfaceAlbedo;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedo*=alpha;\n\nenvironmentIrradiance*=alpha;\n\nenvironmentRefraction*=tint;\n\nalpha=1.0;\n#endif\n\nvec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);\nspecularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,alpha);\n\ntransmission*=1.0-specularEnvironmentReflectance;\n\nrefractance=transmission;\n#endif\n\n\n\n\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\n\nvec3 finalDiffuse=diffuseBase;\nfinalDiffuse.rgb+=vAmbientColor;\nfinalDiffuse*=surfaceAlbedo.rgb;\nfinalDiffuse=max(finalDiffuse,0.0);\n\n#ifdef REFLECTION\nvec3 finalIrradiance=environmentIrradiance;\nfinalIrradiance*=surfaceAlbedo.rgb;\n#endif\n\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase;\nfinalSpecular=max(finalSpecular,0.0);\n\nvec3 finalSpecularScaled=finalSpecular*vLightingIntensity.x*vLightingIntensity.w;\n#endif\n\n#ifdef REFLECTION\nvec3 finalRadiance=environmentRadiance;\nfinalRadiance*=specularEnvironmentReflectance;\n\nvec3 finalRadianceScaled=finalRadiance*vLightingIntensity.z;\n#endif\n\n#ifdef REFRACTION\nvec3 finalRefraction=environmentRefraction;\nfinalRefraction*=refractance;\n#endif\n\nvec3 finalEmissive=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;\nfinalEmissive*=toLinearSpace(emissiveColorTex.rgb);\nfinalEmissive*=vEmissiveInfos.y;\n#endif\n\n#ifdef 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\n\n\nvec4 finalColor=vec4(finalDiffuse*ambientOcclusionColor*vLightingIntensity.x +\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\nfinalEmissive*vLightingIntensity.y,\nalpha);\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n\nfinalColor=max(finalColor,0.0);\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\nfinalColor.rgb=clamp(finalColor.rgb,0.,30.0);\n#else\n\nfinalColor=applyImageProcessing(finalColor);\n#endif\n#ifdef PREMULTIPLYALPHA\n\nfinalColor.rgb*=finalColor.a;\n#endif\ngl_FragColor=finalColor;\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n}","spritesVertexShader":"\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include<fogVertexDeclaration>\nvoid main(void) { \nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;\nfloat angle=position.w;\nvec2 size=vec2(options.x,options.y);\nvec2 offset=options.zw;\nvec2 uvScale=textureInfos.xy;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \n\nvColor=color;\n\nvec2 uvOffset=vec2(abs(offset.x-cellInfo.x),1.0-abs(offset.y-cellInfo.y));\nvUV=(uvOffset+cellInfo.zw)*uvScale;\n\n#ifdef FOG\nvFogDistance=viewPos;\n#endif\n}","spritesPixelShader":"uniform bool alphaTest;\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest) \n{\nif (color.a<0.95)\ndiscard;\n}\ncolor*=vColor;\n#include<fogFragment>\ngl_FragColor=color;\n}","particlesVertexShader":"\nattribute vec3 position;\nattribute vec4 color;\nattribute vec4 options;\nattribute float cellIndex;\n\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec3 particlesInfos; \n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nvarying float fClipDistance;\n#endif\nvoid main(void) { \nvec3 viewPos=(view*vec4(position,1.0)).xyz; \nvec3 cornerPos;\nfloat size=options.y;\nfloat angle=options.x;\nvec2 offset=options.zw;\ncornerPos=vec3(offset.x-0.5,offset.y-0.5,0.)*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}","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#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 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{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 worldPos=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*worldPos;\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 vec2 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.y*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;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,vUV);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\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);\nif (chromatic_aberration>0.0) {\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*radius*17.0/screen_width;\nfloat ref_shiftY=chromatic_aberration*radius*17.0/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;\n}\ngl_FragColor=original;\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);\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\nreturn;\n}\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}\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n}","circleOfConfusionPixelShader":"\nuniform sampler2D depthSampler;\n\nvarying vec2 vUV;\n\nuniform vec2 cameraMinMaxZ;\n\nuniform float focusDistance;\nuniform float cocPrecalculation;\nfloat sampleDistance(const in vec2 offset) {\nfloat depth=texture2D(depthSampler,offset).r; \nreturn (cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth)*1000.0; \n}\nvoid main(void)\n{\nfloat pixelDistance=sampleDistance(vUV);\nfloat coc=abs(cocPrecalculation* ((focusDistance-pixelDistance)/pixelDistance));\ncoc=clamp(coc,0.0,1.0);\ngl_FragColor=vec4(coc,texture2D(depthSampler,vUV).r,coc,1.0);\n}\n","depthOfFieldMergePixelShader":"\nuniform sampler2D textureSampler;\nuniform sampler2D originalSampler;\nuniform sampler2D circleOfConfusionSampler;\n#if BLUR_LEVEL>0\nuniform sampler2D blurStep1;\n#endif\n#if BLUR_LEVEL>1\nuniform sampler2D blurStep2;\n#endif\n\nvarying vec2 vUV;\nvoid main(void)\n{\nfloat coc=texture2D(circleOfConfusionSampler,vUV).r;\nvec4 original=texture2D(originalSampler,vUV);\n#if BLUR_LEVEL == 0\nvec4 blurred1=texture2D(textureSampler,vUV);\ngl_FragColor=mix(original,blurred1,coc);\n#endif\n#if BLUR_LEVEL == 1\nvec4 blurred1=texture2D(blurStep1,vUV);\nvec4 blurred2=texture2D(textureSampler,vUV); \nif(coc<0.5){\ngl_FragColor=mix(original,blurred1,coc/0.5);\n}else{\ngl_FragColor=mix(blurred1,blurred2,(coc-0.5)/0.5);\n}\n#endif\n#if BLUR_LEVEL == 2\nvec4 blurred1=texture2D(blurStep1,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\nvec4 blurred3=texture2D(textureSampler,vUV);\nif(coc<0.33){\ngl_FragColor=mix(original,blurred1,coc/0.33);\n}else if(coc<0.66){\ngl_FragColor=mix(blurred1,blurred2,(coc-0.33)/0.33);\n}else{\ngl_FragColor=mix(blurred2,blurred3,(coc-0.66)/0.34);\n}\n#endif\n}\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}","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}\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{\n#ifdef DOF\nfloat sumOfWeights=0.0; \nfloat sampleDepth=0.0;\nfloat factor=0.0;\nfloat centerSampleDepth=sampleDistance(sampleCenter);\n#endif\nfloat computedWeight=0.0;\n#ifdef PACKEDFLOAT \nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\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\n\nif(sumOfWeights == 0.0){\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor/=sumOfWeights;\n#endif\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\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{\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(position,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef DIFFUSEUV1\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef DIFFUSEUV2\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvUVEmissive=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef EMISSIVEUV2\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","glowMapMergePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#ifdef EMISSIVE\nuniform sampler2D textureSampler2;\n#endif\n\nuniform float offset;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef EMISSIVE\nbaseColor+=texture2D(textureSampler2,vUV);\nbaseColor*=offset;\n#else\nbaseColor.a=abs(offset-baseColor.a);\n#ifdef STROKE\nfloat alpha=smoothstep(.0,.1,baseColor.a);\nbaseColor.a=alpha;\nbaseColor.rgb=baseColor.rgb*alpha;\n#endif\n#endif\ngl_FragColor=baseColor;\n}","glowMapMergeVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) {\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","lineVertexShader":"\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}","linePixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","outlineVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#include<bonesDeclaration>\n\nuniform float offset;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#include<logDepthDeclaration>\nvoid main(void)\n{\nvec3 offsetPosition=position+normal*offset;\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include<logDepthVertex>\n}\n","outlinePixelShader":"#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#include<logDepthFragment>\ngl_FragColor=color;\n}","layerVertexShader":"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}","layerPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}","backgroundVertexShader":"precision highp float;\n#include<__decl__backgroundVertex>\n#include<helperFunctions>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normal);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#ifdef EQUIRECTANGULAR_RELFECTION_FOV\nmat3 screenToWorld=inverseMat3(mat3(finalWorld*viewProjection));\nvec3 segment=mix(vDirectionW,screenToWorld*vec3(0.0,0.0,1.0),abs(fFovMultiplier-1.0));\nif (fFovMultiplier<=1.0) {\nvDirectionW=normalize(segment);\n} else {\nvDirectionW=normalize(vDirectionW+(vDirectionW-segment));\n}\n#endif\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0 \nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n}\n","backgroundPixelShader":"#ifdef TEXTURELODSUPPORT\n#extension GL_EXT_shader_texture_lod : enable\n#endif\nprecision highp float;\n#include<__decl__backgroundFragment>\n#define RECIPROCAL_PI2 0.15915494\n\nuniform vec3 vEyePosition;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2; \n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n\n#ifndef SHADOWONLY\n#define SHADOWONLY;\n#endif\n#include<imageProcessingDeclaration>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<helperFunctions>\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n#include<imageProcessingFunctions>\n#include<clipPlaneFragmentDeclaration>\n\n#include<fogFragmentDeclaration>\n#ifdef REFLECTIONFRESNEL\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n#endif\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(0.0,1.0,0.0);\n#endif\n\nfloat shadow=1.;\nfloat globalShadow=0.;\nfloat shadowLightCount=0.;\n#include<lightFragment>[0..maxSimultaneousLights]\n#ifdef SHADOWINUSE\nglobalShadow/=shadowLightCount;\n#else\nglobalShadow=1.0;\n#endif\n\nvec3 reflectionColor=vec3(1.,1.,1.);\n#ifdef REFLECTION\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#ifdef REFLECTIONBLUR\nfloat reflectionLOD=vReflectionInfos.y;\n#ifdef TEXTURELODSUPPORT\n\nreflectionLOD=reflectionLOD*log2(vReflectionMicrosurfaceInfos.x)*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\nreflectionColor=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD).rgb;\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD,0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec3 reflectionSpecularMid=sampleReflection(reflectionSampler,reflectionCoords).rgb;\nif(lodReflectionNormalizedDoubled<1.0){\nreflectionColor=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nreflectionSpecularMid,\nlodReflectionNormalizedDoubled\n);\n} else {\nreflectionColor=mix(\nreflectionSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#else\nvec4 reflectionSample=sampleReflection(reflectionSampler,reflectionCoords);\nreflectionColor=reflectionSample.rgb;\n#endif\n#ifdef GAMMAREFLECTION\nreflectionColor=toLinearSpace(reflectionColor.rgb);\n#endif\n\nreflectionColor*=vReflectionInfos.x;\n#endif\n\nvec3 diffuseColor=vec3(1.,1.,1.);\nfloat finalAlpha=alpha;\n#ifdef DIFFUSE\nvec4 diffuseMap=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef GAMMADIFFUSE\ndiffuseMap.rgb=toLinearSpace(diffuseMap.rgb);\n#endif\n\ndiffuseMap.rgb*=vDiffuseInfos.y;\n#ifdef DIFFUSEHASALPHA\nfinalAlpha*=diffuseMap.a;\n#endif\ndiffuseColor=diffuseMap.rgb;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 colorBase=diffuseColor;\n#else\nvec3 colorBase=reflectionColor*diffuseColor;\n#endif\ncolorBase=max(colorBase,0.0);\n\n#ifdef USERGBCOLOR\nvec3 finalColor=colorBase;\n#else\nvec3 finalColor=colorBase.r*vPrimaryColor.rgb*vPrimaryColor.a;\nfinalColor+=colorBase.g*vSecondaryColor.rgb*vSecondaryColor.a;\nfinalColor+=colorBase.b*vTertiaryColor.rgb*vTertiaryColor.a;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 reflectionAmount=vReflectionControl.xxx;\nvec3 reflectionReflectance0=vReflectionControl.yyy;\nvec3 reflectionReflectance90=vReflectionControl.zzz;\nfloat VdotN=dot(normalize(vEyePosition),normalW);\nvec3 planarReflectionFresnel=fresnelSchlickEnvironmentGGX(clamp(VdotN,0.0,1.0),reflectionReflectance0,reflectionReflectance90,1.0);\nreflectionAmount*=planarReflectionFresnel;\n#ifdef REFLECTIONFALLOFF\nfloat reflectionDistanceFalloff=1.0-clamp(length(vPositionW.xyz-vBackgroundCenter)*vReflectionControl.w,0.0,1.0);\nreflectionDistanceFalloff*=reflectionDistanceFalloff;\nreflectionAmount*=reflectionDistanceFalloff;\n#endif\nfinalColor=mix(finalColor,reflectionColor,clamp(reflectionAmount,0.,1.));\n#endif\n#ifdef OPACITYFRESNEL\nfloat viewAngleToFloor=dot(normalW,normalize(vEyePosition-vBackgroundCenter));\n\nconst float startAngle=0.1;\nfloat fadeFactor=clamp(viewAngleToFloor/startAngle,0.0,1.0);\nfinalAlpha*=fadeFactor*fadeFactor;\n#endif\n\n#ifdef SHADOWINUSE\nfinalColor=mix(finalColor*shadowLevel,finalColor,globalShadow);\n#endif\n\nvec4 color=vec4(finalColor,finalAlpha);\n#include<fogFragment>\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\ncolor.rgb=clamp(color.rgb,0.,30.0);\n#else\n\ncolor=applyImageProcessing(color);\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#ifdef NOISE\ncolor.rgb=dither(vPositionW.xy,color.rgb);\n#endif\ngl_FragColor=color;\n}\n"};
  87703. 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}\nvec3 dither(vec2 seed,vec3 color) {\nfloat rand=getRand(seed);\ncolor+=mix(-0.5/255.0,0.5/255.0,rand);\ncolor=max(color,0.0);\nreturn color;\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};\nuniform sampler2D shadowSampler{X};\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;\n#ifdef PBR\ntextureColor=toLinearSpace(textureColor);\n#endif\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};\nuniform sampler2D shadowSampler{X};\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 computeShadowWithPCFCube(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 computeShadowWithPCF(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#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=worldPos.xyz-vEyePosition.xyz;\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef INVERTCUBICMAP\ncoords.y=1.0-coords.y;\n#endif\n#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\ncoords=parallaxCorrectNormal(worldPos.xyz,coords,vReflectionSize,vReflectionPosition );\n#endif\nreturn vec3(reflectionMatrix*vec4(coords,0));\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\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\nnormalW=perturbNormal(TBN,vBumpUV+uvOffset);\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,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,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,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#else\n#ifdef 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#else \n#ifdef SHADOWPCF{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithPCFCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadowWithPCF(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.y,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#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)\n{\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 reflection,vec3 normal) {\n\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflection.z*=-1.0;\n#endif\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,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);\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,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);\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,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);\nresult.specular=specTerm*diffuseColor;\n#endif\nreturn result;\n}","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","kernelBlurFragment":"#ifdef DOF\nsampleDepth=sampleDistance(sampleCoord{X});\nfactor=clamp(1.0-((centerSampleDepth-sampleDepth)/centerSampleDepth),0.0,1.0);\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\nsampleDepth=sampleDistance(sampleCoord{X});\nfactor=clamp(1.0-((centerSampleDepth-sampleDepth)/centerSampleDepth),0.0,1.0);\ncomputedWeight=KERNEL_DEP_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_DEP_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*computedWeight;\n#endif","kernelBlurVaryingDeclaration":"varying vec2 sampleCoord{X};","kernelBlurVertex":"sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};","backgroundVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\nuniform float shadowLevel;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif","backgroundFragmentDeclaration":" uniform vec4 vPrimaryColor;\nuniform vec4 vSecondaryColor;\nuniform vec4 vTertiaryColor;\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 vSecondaryColor;\nuniform vec4 vTertiaryColor;\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};"};
  87704. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  87705. var BABYLON;
  87706. (function (BABYLON) {
  87707. var GridMaterialDefines = /** @class */ (function (_super) {
  87708. __extends(GridMaterialDefines, _super);
  87709. function GridMaterialDefines() {
  87710. var _this = _super.call(this) || this;
  87711. _this.TRANSPARENT = false;
  87712. _this.FOG = false;
  87713. _this.PREMULTIPLYALPHA = false;
  87714. _this.rebuild();
  87715. return _this;
  87716. }
  87717. return GridMaterialDefines;
  87718. }(BABYLON.MaterialDefines));
  87719. /**
  87720. * The grid materials allows you to wrap any shape with a grid.
  87721. * Colors are customizable.
  87722. */
  87723. var GridMaterial = /** @class */ (function (_super) {
  87724. __extends(GridMaterial, _super);
  87725. /**
  87726. * constructor
  87727. * @param name The name given to the material in order to identify it afterwards.
  87728. * @param scene The scene the material is used in.
  87729. */
  87730. function GridMaterial(name, scene) {
  87731. var _this = _super.call(this, name, scene) || this;
  87732. /**
  87733. * Main color of the grid (e.g. between lines)
  87734. */
  87735. _this.mainColor = BABYLON.Color3.Black();
  87736. /**
  87737. * Color of the grid lines.
  87738. */
  87739. _this.lineColor = BABYLON.Color3.Teal();
  87740. /**
  87741. * The scale of the grid compared to unit.
  87742. */
  87743. _this.gridRatio = 1.0;
  87744. /**
  87745. * Allows setting an offset for the grid lines.
  87746. */
  87747. _this.gridOffset = BABYLON.Vector3.Zero();
  87748. /**
  87749. * The frequency of thicker lines.
  87750. */
  87751. _this.majorUnitFrequency = 10;
  87752. /**
  87753. * The visibility of minor units in the grid.
  87754. */
  87755. _this.minorUnitVisibility = 0.33;
  87756. /**
  87757. * The grid opacity outside of the lines.
  87758. */
  87759. _this.opacity = 1.0;
  87760. /**
  87761. * Determine RBG output is premultiplied by alpha value.
  87762. */
  87763. _this.preMultiplyAlpha = false;
  87764. _this._gridControl = new BABYLON.Vector4(_this.gridRatio, _this.majorUnitFrequency, _this.minorUnitVisibility, _this.opacity);
  87765. return _this;
  87766. }
  87767. /**
  87768. * Returns wehter or not the grid requires alpha blending.
  87769. */
  87770. GridMaterial.prototype.needAlphaBlending = function () {
  87771. return this.opacity < 1.0;
  87772. };
  87773. GridMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  87774. return this.needAlphaBlending();
  87775. };
  87776. GridMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  87777. if (this.isFrozen) {
  87778. if (this._wasPreviouslyReady && subMesh.effect) {
  87779. return true;
  87780. }
  87781. }
  87782. if (!subMesh._materialDefines) {
  87783. subMesh._materialDefines = new GridMaterialDefines();
  87784. }
  87785. var defines = subMesh._materialDefines;
  87786. var scene = this.getScene();
  87787. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  87788. if (this._renderId === scene.getRenderId()) {
  87789. return true;
  87790. }
  87791. }
  87792. if (defines.TRANSPARENT !== (this.opacity < 1.0)) {
  87793. defines.TRANSPARENT = !defines.TRANSPARENT;
  87794. defines.markAsUnprocessed();
  87795. }
  87796. if (defines.PREMULTIPLYALPHA != this.preMultiplyAlpha) {
  87797. defines.PREMULTIPLYALPHA = !defines.PREMULTIPLYALPHA;
  87798. defines.markAsUnprocessed();
  87799. }
  87800. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, false, this.fogEnabled, false, defines);
  87801. // Get correct effect
  87802. if (defines.isDirty) {
  87803. defines.markAsProcessed();
  87804. scene.resetCachedMaterial();
  87805. // Attributes
  87806. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  87807. // Defines
  87808. var join = defines.toString();
  87809. subMesh.setEffect(scene.getEngine().createEffect("grid", attribs, ["projection", "worldView", "mainColor", "lineColor", "gridControl", "gridOffset", "vFogInfos", "vFogColor", "world", "view"], [], join, undefined, this.onCompiled, this.onError), defines);
  87810. }
  87811. if (!subMesh.effect || !subMesh.effect.isReady()) {
  87812. return false;
  87813. }
  87814. this._renderId = scene.getRenderId();
  87815. this._wasPreviouslyReady = true;
  87816. return true;
  87817. };
  87818. GridMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  87819. var scene = this.getScene();
  87820. var defines = subMesh._materialDefines;
  87821. if (!defines) {
  87822. return;
  87823. }
  87824. var effect = subMesh.effect;
  87825. if (!effect) {
  87826. return;
  87827. }
  87828. this._activeEffect = effect;
  87829. // Matrices
  87830. this.bindOnlyWorldMatrix(world);
  87831. this._activeEffect.setMatrix("worldView", world.multiply(scene.getViewMatrix()));
  87832. this._activeEffect.setMatrix("view", scene.getViewMatrix());
  87833. this._activeEffect.setMatrix("projection", scene.getProjectionMatrix());
  87834. // Uniforms
  87835. if (this._mustRebind(scene, effect)) {
  87836. this._activeEffect.setColor3("mainColor", this.mainColor);
  87837. this._activeEffect.setColor3("lineColor", this.lineColor);
  87838. this._activeEffect.setVector3("gridOffset", this.gridOffset);
  87839. this._gridControl.x = this.gridRatio;
  87840. this._gridControl.y = Math.round(this.majorUnitFrequency);
  87841. this._gridControl.z = this.minorUnitVisibility;
  87842. this._gridControl.w = this.opacity;
  87843. this._activeEffect.setVector4("gridControl", this._gridControl);
  87844. }
  87845. // Fog
  87846. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  87847. this._afterBind(mesh, this._activeEffect);
  87848. };
  87849. GridMaterial.prototype.dispose = function (forceDisposeEffect) {
  87850. _super.prototype.dispose.call(this, forceDisposeEffect);
  87851. };
  87852. GridMaterial.prototype.clone = function (name) {
  87853. var _this = this;
  87854. return BABYLON.SerializationHelper.Clone(function () { return new GridMaterial(name, _this.getScene()); }, this);
  87855. };
  87856. GridMaterial.prototype.serialize = function () {
  87857. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  87858. serializationObject.customType = "BABYLON.GridMaterial";
  87859. return serializationObject;
  87860. };
  87861. GridMaterial.prototype.getClassName = function () {
  87862. return "GridMaterial";
  87863. };
  87864. GridMaterial.Parse = function (source, scene, rootUrl) {
  87865. return BABYLON.SerializationHelper.Parse(function () { return new GridMaterial(source.name, scene); }, source, scene, rootUrl);
  87866. };
  87867. __decorate([
  87868. BABYLON.serializeAsColor3()
  87869. ], GridMaterial.prototype, "mainColor", void 0);
  87870. __decorate([
  87871. BABYLON.serializeAsColor3()
  87872. ], GridMaterial.prototype, "lineColor", void 0);
  87873. __decorate([
  87874. BABYLON.serialize()
  87875. ], GridMaterial.prototype, "gridRatio", void 0);
  87876. __decorate([
  87877. BABYLON.serializeAsColor3()
  87878. ], GridMaterial.prototype, "gridOffset", void 0);
  87879. __decorate([
  87880. BABYLON.serialize()
  87881. ], GridMaterial.prototype, "majorUnitFrequency", void 0);
  87882. __decorate([
  87883. BABYLON.serialize()
  87884. ], GridMaterial.prototype, "minorUnitVisibility", void 0);
  87885. __decorate([
  87886. BABYLON.serialize()
  87887. ], GridMaterial.prototype, "opacity", void 0);
  87888. __decorate([
  87889. BABYLON.serialize()
  87890. ], GridMaterial.prototype, "preMultiplyAlpha", void 0);
  87891. return GridMaterial;
  87892. }(BABYLON.PushMaterial));
  87893. BABYLON.GridMaterial = GridMaterial;
  87894. })(BABYLON || (BABYLON = {}));
  87895. //# sourceMappingURL=babylon.gridmaterial.js.map
  87896. BABYLON.Effect.ShadersStore['gridVertexShader'] = "precision highp float;\n\nattribute vec3 position;\nattribute vec3 normal;\n\nuniform mat4 projection;\nuniform mat4 world;\nuniform mat4 view;\nuniform mat4 worldView;\n\n#ifdef TRANSPARENT\nvarying vec4 vCameraSpacePosition;\n#endif\nvarying vec3 vPosition;\nvarying vec3 vNormal;\n#include<fogVertexDeclaration>\nvoid main(void) {\n#ifdef FOG\nvec4 worldPos=world*vec4(position,1.0);\n#endif\n#include<fogVertex>\nvec4 cameraSpacePosition=worldView*vec4(position,1.0);\ngl_Position=projection*cameraSpacePosition;\n#ifdef TRANSPARENT\nvCameraSpacePosition=cameraSpacePosition;\n#endif\nvPosition=position;\nvNormal=normal;\n}";
  87897. BABYLON.Effect.ShadersStore['gridPixelShader'] = "#extension GL_OES_standard_derivatives : enable\n#define SQRT2 1.41421356\n#define PI 3.14159\nprecision highp float;\nuniform vec3 mainColor;\nuniform vec3 lineColor;\nuniform vec4 gridControl;\nuniform vec3 gridOffset;\n\n#ifdef TRANSPARENT\nvarying vec4 vCameraSpacePosition;\n#endif\nvarying vec3 vPosition;\nvarying vec3 vNormal;\n#include<fogFragmentDeclaration>\nfloat getVisibility(float position) {\n\nfloat majorGridFrequency=gridControl.y;\nif (floor(position+0.5) == floor(position/majorGridFrequency+0.5)*majorGridFrequency)\n{\nreturn 1.0;\n} \nreturn gridControl.z;\n}\nfloat getAnisotropicAttenuation(float differentialLength) {\nconst float maxNumberOfLines=10.0;\nreturn clamp(1.0/(differentialLength+1.0)-1.0/maxNumberOfLines,0.0,1.0);\n}\nfloat isPointOnLine(float position,float differentialLength) {\nfloat fractionPartOfPosition=position-floor(position+0.5); \nfractionPartOfPosition/=differentialLength; \nfractionPartOfPosition=clamp(fractionPartOfPosition,-1.,1.);\nfloat result=0.5+0.5*cos(fractionPartOfPosition*PI); \nreturn result; \n}\nfloat contributionOnAxis(float position) {\nfloat differentialLength=length(vec2(dFdx(position),dFdy(position)));\ndifferentialLength*=SQRT2; \n\nfloat result=isPointOnLine(position,differentialLength);\n\nfloat visibility=getVisibility(position);\nresult*=visibility;\n\nfloat anisotropicAttenuation=getAnisotropicAttenuation(differentialLength);\nresult*=anisotropicAttenuation;\nreturn result;\n}\nfloat normalImpactOnAxis(float x) {\nfloat normalImpact=clamp(1.0-3.0*abs(x*x*x),0.0,1.0);\nreturn normalImpact;\n}\nvoid main(void) {\n\nfloat gridRatio=gridControl.x;\nvec3 gridPos=(vPosition+gridOffset)/gridRatio;\n\nfloat x=contributionOnAxis(gridPos.x);\nfloat y=contributionOnAxis(gridPos.y);\nfloat z=contributionOnAxis(gridPos.z);\n\nvec3 normal=normalize(vNormal);\nx*=normalImpactOnAxis(normal.x);\ny*=normalImpactOnAxis(normal.y);\nz*=normalImpactOnAxis(normal.z);\n\nfloat grid=clamp(x+y+z,0.,1.);\n\nvec3 color=mix(mainColor,lineColor,grid);\n#ifdef FOG\n#include<fogFragment>\n#endif\n#ifdef TRANSPARENT\nfloat distanceToFragment=length(vCameraSpacePosition.xyz);\nfloat cameraPassThrough=clamp(distanceToFragment-0.25,0.0,1.0);\nfloat opacity=clamp(grid,0.08,cameraPassThrough*gridControl.w*grid);\ngl_FragColor=vec4(color.rgb,opacity);\n#ifdef PREMULTIPLYALPHA\ngl_FragColor.rgb*=opacity;\n#endif\n#else\n\ngl_FragColor=vec4(color.rgb,1.0);\n#endif\n}";
  87898. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  87899. var BABYLON;
  87900. (function (BABYLON) {
  87901. var GLTFLoaderCoordinateSystemMode;
  87902. (function (GLTFLoaderCoordinateSystemMode) {
  87903. /**
  87904. * Automatically convert the glTF right-handed data to the appropriate system based on the current coordinate system mode of the scene.
  87905. */
  87906. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["AUTO"] = 0] = "AUTO";
  87907. /**
  87908. * Sets the useRightHandedSystem flag on the scene.
  87909. */
  87910. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["FORCE_RIGHT_HANDED"] = 1] = "FORCE_RIGHT_HANDED";
  87911. })(GLTFLoaderCoordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode || (BABYLON.GLTFLoaderCoordinateSystemMode = {}));
  87912. var GLTFLoaderAnimationStartMode;
  87913. (function (GLTFLoaderAnimationStartMode) {
  87914. /**
  87915. * No animation will start.
  87916. */
  87917. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["NONE"] = 0] = "NONE";
  87918. /**
  87919. * The first animation will start.
  87920. */
  87921. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["FIRST"] = 1] = "FIRST";
  87922. /**
  87923. * All animations will start.
  87924. */
  87925. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["ALL"] = 2] = "ALL";
  87926. })(GLTFLoaderAnimationStartMode = BABYLON.GLTFLoaderAnimationStartMode || (BABYLON.GLTFLoaderAnimationStartMode = {}));
  87927. var GLTFLoaderState;
  87928. (function (GLTFLoaderState) {
  87929. GLTFLoaderState[GLTFLoaderState["Loading"] = 0] = "Loading";
  87930. GLTFLoaderState[GLTFLoaderState["Ready"] = 1] = "Ready";
  87931. GLTFLoaderState[GLTFLoaderState["Complete"] = 2] = "Complete";
  87932. })(GLTFLoaderState = BABYLON.GLTFLoaderState || (BABYLON.GLTFLoaderState = {}));
  87933. var GLTFFileLoader = /** @class */ (function () {
  87934. function GLTFFileLoader() {
  87935. // #region Common options
  87936. /**
  87937. * Raised when the asset has been parsed.
  87938. * The data.json property stores the glTF JSON.
  87939. * The data.bin property stores the BIN chunk from a glTF binary or null if the input is not a glTF binary.
  87940. */
  87941. this.onParsedObservable = new BABYLON.Observable();
  87942. // #endregion
  87943. // #region V2 options
  87944. /**
  87945. * The coordinate system mode (AUTO, FORCE_RIGHT_HANDED).
  87946. */
  87947. this.coordinateSystemMode = GLTFLoaderCoordinateSystemMode.AUTO;
  87948. /**
  87949. * The animation start mode (NONE, FIRST, ALL).
  87950. */
  87951. this.animationStartMode = GLTFLoaderAnimationStartMode.FIRST;
  87952. /**
  87953. * Set to true to compile materials before raising the success callback.
  87954. */
  87955. this.compileMaterials = false;
  87956. /**
  87957. * Set to true to also compile materials with clip planes.
  87958. */
  87959. this.useClipPlane = false;
  87960. /**
  87961. * Set to true to compile shadow generators before raising the success callback.
  87962. */
  87963. this.compileShadowGenerators = false;
  87964. /**
  87965. * Raised when the loader creates a mesh after parsing the glTF properties of the mesh.
  87966. */
  87967. this.onMeshLoadedObservable = new BABYLON.Observable();
  87968. /**
  87969. * Raised when the loader creates a texture after parsing the glTF properties of the texture.
  87970. */
  87971. this.onTextureLoadedObservable = new BABYLON.Observable();
  87972. /**
  87973. * Raised when the loader creates a material after parsing the glTF properties of the material.
  87974. */
  87975. this.onMaterialLoadedObservable = new BABYLON.Observable();
  87976. /**
  87977. * Raised when the asset is completely loaded, immediately before the loader is disposed.
  87978. * For assets with LODs, raised when all of the LODs are complete.
  87979. * For assets without LODs, raised when the model is complete, immediately after onSuccess.
  87980. */
  87981. this.onCompleteObservable = new BABYLON.Observable();
  87982. /**
  87983. * Raised when the loader is disposed.
  87984. */
  87985. this.onDisposeObservable = new BABYLON.Observable();
  87986. /**
  87987. * Raised after a loader extension is created.
  87988. * Set additional options for a loader extension in this event.
  87989. */
  87990. this.onExtensionLoadedObservable = new BABYLON.Observable();
  87991. // #endregion
  87992. this._loader = null;
  87993. this.name = "gltf";
  87994. this.extensions = {
  87995. ".gltf": { isBinary: false },
  87996. ".glb": { isBinary: true }
  87997. };
  87998. }
  87999. Object.defineProperty(GLTFFileLoader.prototype, "onParsed", {
  88000. set: function (callback) {
  88001. if (this._onParsedObserver) {
  88002. this.onParsedObservable.remove(this._onParsedObserver);
  88003. }
  88004. this._onParsedObserver = this.onParsedObservable.add(callback);
  88005. },
  88006. enumerable: true,
  88007. configurable: true
  88008. });
  88009. Object.defineProperty(GLTFFileLoader.prototype, "onMeshLoaded", {
  88010. set: function (callback) {
  88011. if (this._onMeshLoadedObserver) {
  88012. this.onMeshLoadedObservable.remove(this._onMeshLoadedObserver);
  88013. }
  88014. this._onMeshLoadedObserver = this.onMeshLoadedObservable.add(callback);
  88015. },
  88016. enumerable: true,
  88017. configurable: true
  88018. });
  88019. Object.defineProperty(GLTFFileLoader.prototype, "onTextureLoaded", {
  88020. set: function (callback) {
  88021. if (this._onTextureLoadedObserver) {
  88022. this.onTextureLoadedObservable.remove(this._onTextureLoadedObserver);
  88023. }
  88024. this._onTextureLoadedObserver = this.onTextureLoadedObservable.add(callback);
  88025. },
  88026. enumerable: true,
  88027. configurable: true
  88028. });
  88029. Object.defineProperty(GLTFFileLoader.prototype, "onMaterialLoaded", {
  88030. set: function (callback) {
  88031. if (this._onMaterialLoadedObserver) {
  88032. this.onMaterialLoadedObservable.remove(this._onMaterialLoadedObserver);
  88033. }
  88034. this._onMaterialLoadedObserver = this.onMaterialLoadedObservable.add(callback);
  88035. },
  88036. enumerable: true,
  88037. configurable: true
  88038. });
  88039. Object.defineProperty(GLTFFileLoader.prototype, "onComplete", {
  88040. set: function (callback) {
  88041. if (this._onCompleteObserver) {
  88042. this.onCompleteObservable.remove(this._onCompleteObserver);
  88043. }
  88044. this._onCompleteObserver = this.onCompleteObservable.add(callback);
  88045. },
  88046. enumerable: true,
  88047. configurable: true
  88048. });
  88049. Object.defineProperty(GLTFFileLoader.prototype, "onDispose", {
  88050. set: function (callback) {
  88051. if (this._onDisposeObserver) {
  88052. this.onDisposeObservable.remove(this._onDisposeObserver);
  88053. }
  88054. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  88055. },
  88056. enumerable: true,
  88057. configurable: true
  88058. });
  88059. Object.defineProperty(GLTFFileLoader.prototype, "onExtensionLoaded", {
  88060. set: function (callback) {
  88061. if (this._onExtensionLoadedObserver) {
  88062. this.onExtensionLoadedObservable.remove(this._onExtensionLoadedObserver);
  88063. }
  88064. this._onExtensionLoadedObserver = this.onExtensionLoadedObservable.add(callback);
  88065. },
  88066. enumerable: true,
  88067. configurable: true
  88068. });
  88069. Object.defineProperty(GLTFFileLoader.prototype, "loaderState", {
  88070. /**
  88071. * The loader state or null if not active.
  88072. */
  88073. get: function () {
  88074. return this._loader ? this._loader.state : null;
  88075. },
  88076. enumerable: true,
  88077. configurable: true
  88078. });
  88079. /**
  88080. * Disposes the loader, releases resources during load, and cancels any outstanding requests.
  88081. */
  88082. GLTFFileLoader.prototype.dispose = function () {
  88083. if (this._loader) {
  88084. this._loader.dispose();
  88085. this._loader = null;
  88086. }
  88087. this.onParsedObservable.clear();
  88088. this.onMeshLoadedObservable.clear();
  88089. this.onTextureLoadedObservable.clear();
  88090. this.onMaterialLoadedObservable.clear();
  88091. this.onCompleteObservable.clear();
  88092. this.onDisposeObservable.notifyObservers(this);
  88093. this.onDisposeObservable.clear();
  88094. };
  88095. GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  88096. var _this = this;
  88097. return Promise.resolve().then(function () {
  88098. var loaderData = _this._parse(data);
  88099. _this._loader = _this._getLoader(loaderData);
  88100. return _this._loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onProgress);
  88101. });
  88102. };
  88103. GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  88104. var _this = this;
  88105. return Promise.resolve().then(function () {
  88106. var loaderData = _this._parse(data);
  88107. _this._loader = _this._getLoader(loaderData);
  88108. return _this._loader.loadAsync(scene, loaderData, rootUrl, onProgress);
  88109. });
  88110. };
  88111. GLTFFileLoader.prototype.loadAssetContainerAsync = function (scene, data, rootUrl, onProgress) {
  88112. var _this = this;
  88113. return Promise.resolve().then(function () {
  88114. var loaderData = _this._parse(data);
  88115. _this._loader = _this._getLoader(loaderData);
  88116. return _this._loader.importMeshAsync(null, scene, loaderData, rootUrl, onProgress).then(function (result) {
  88117. var container = new BABYLON.AssetContainer(scene);
  88118. Array.prototype.push.apply(container.meshes, result.meshes);
  88119. Array.prototype.push.apply(container.particleSystems, result.particleSystems);
  88120. Array.prototype.push.apply(container.skeletons, result.skeletons);
  88121. container.removeAllFromScene();
  88122. return container;
  88123. });
  88124. });
  88125. };
  88126. GLTFFileLoader.prototype.canDirectLoad = function (data) {
  88127. return ((data.indexOf("scene") !== -1) && (data.indexOf("node") !== -1));
  88128. };
  88129. GLTFFileLoader.prototype.createPlugin = function () {
  88130. return new GLTFFileLoader();
  88131. };
  88132. GLTFFileLoader.prototype._parse = function (data) {
  88133. var parsedData;
  88134. if (data instanceof ArrayBuffer) {
  88135. parsedData = GLTFFileLoader._parseBinary(data);
  88136. }
  88137. else {
  88138. parsedData = {
  88139. json: JSON.parse(data),
  88140. bin: null
  88141. };
  88142. }
  88143. this.onParsedObservable.notifyObservers(parsedData);
  88144. return parsedData;
  88145. };
  88146. GLTFFileLoader.prototype._getLoader = function (loaderData) {
  88147. var _this = this;
  88148. var loaderVersion = { major: 2, minor: 0 };
  88149. var asset = loaderData.json.asset || {};
  88150. var version = GLTFFileLoader._parseVersion(asset.version);
  88151. if (!version) {
  88152. throw new Error("Invalid version: " + asset.version);
  88153. }
  88154. if (asset.minVersion !== undefined) {
  88155. var minVersion = GLTFFileLoader._parseVersion(asset.minVersion);
  88156. if (!minVersion) {
  88157. throw new Error("Invalid minimum version: " + asset.minVersion);
  88158. }
  88159. if (GLTFFileLoader._compareVersion(minVersion, loaderVersion) > 0) {
  88160. throw new Error("Incompatible minimum version: " + asset.minVersion);
  88161. }
  88162. }
  88163. var createLoaders = {
  88164. 1: GLTFFileLoader.CreateGLTFLoaderV1,
  88165. 2: GLTFFileLoader.CreateGLTFLoaderV2
  88166. };
  88167. var createLoader = createLoaders[version.major];
  88168. if (!createLoader) {
  88169. throw new Error("Unsupported version: " + asset.version);
  88170. }
  88171. var loader = createLoader();
  88172. loader.coordinateSystemMode = this.coordinateSystemMode;
  88173. loader.animationStartMode = this.animationStartMode;
  88174. loader.compileMaterials = this.compileMaterials;
  88175. loader.useClipPlane = this.useClipPlane;
  88176. loader.compileShadowGenerators = this.compileShadowGenerators;
  88177. loader.onMeshLoadedObservable.add(function (mesh) { return _this.onMeshLoadedObservable.notifyObservers(mesh); });
  88178. loader.onTextureLoadedObservable.add(function (texture) { return _this.onTextureLoadedObservable.notifyObservers(texture); });
  88179. loader.onMaterialLoadedObservable.add(function (material) { return _this.onMaterialLoadedObservable.notifyObservers(material); });
  88180. loader.onCompleteObservable.add(function () { return _this.onCompleteObservable.notifyObservers(_this); });
  88181. loader.onExtensionLoadedObservable.add(function (extension) { return _this.onExtensionLoadedObservable.notifyObservers(extension); });
  88182. return loader;
  88183. };
  88184. GLTFFileLoader._parseBinary = function (data) {
  88185. var Binary = {
  88186. Magic: 0x46546C67
  88187. };
  88188. var binaryReader = new BinaryReader(data);
  88189. var magic = binaryReader.readUint32();
  88190. if (magic !== Binary.Magic) {
  88191. throw new Error("Unexpected magic: " + magic);
  88192. }
  88193. var version = binaryReader.readUint32();
  88194. switch (version) {
  88195. case 1: return GLTFFileLoader._parseV1(binaryReader);
  88196. case 2: return GLTFFileLoader._parseV2(binaryReader);
  88197. }
  88198. throw new Error("Unsupported version: " + version);
  88199. };
  88200. GLTFFileLoader._parseV1 = function (binaryReader) {
  88201. var ContentFormat = {
  88202. JSON: 0
  88203. };
  88204. var length = binaryReader.readUint32();
  88205. if (length != binaryReader.getLength()) {
  88206. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  88207. }
  88208. var contentLength = binaryReader.readUint32();
  88209. var contentFormat = binaryReader.readUint32();
  88210. var content;
  88211. switch (contentFormat) {
  88212. case ContentFormat.JSON: {
  88213. content = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(contentLength)));
  88214. break;
  88215. }
  88216. default: {
  88217. throw new Error("Unexpected content format: " + contentFormat);
  88218. }
  88219. }
  88220. var bytesRemaining = binaryReader.getLength() - binaryReader.getPosition();
  88221. var body = binaryReader.readUint8Array(bytesRemaining);
  88222. return {
  88223. json: content,
  88224. bin: body
  88225. };
  88226. };
  88227. GLTFFileLoader._parseV2 = function (binaryReader) {
  88228. var ChunkFormat = {
  88229. JSON: 0x4E4F534A,
  88230. BIN: 0x004E4942
  88231. };
  88232. var length = binaryReader.readUint32();
  88233. if (length !== binaryReader.getLength()) {
  88234. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  88235. }
  88236. // JSON chunk
  88237. var chunkLength = binaryReader.readUint32();
  88238. var chunkFormat = binaryReader.readUint32();
  88239. if (chunkFormat !== ChunkFormat.JSON) {
  88240. throw new Error("First chunk format is not JSON");
  88241. }
  88242. var json = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(chunkLength)));
  88243. // Look for BIN chunk
  88244. var bin = null;
  88245. while (binaryReader.getPosition() < binaryReader.getLength()) {
  88246. var chunkLength_1 = binaryReader.readUint32();
  88247. var chunkFormat_1 = binaryReader.readUint32();
  88248. switch (chunkFormat_1) {
  88249. case ChunkFormat.JSON: {
  88250. throw new Error("Unexpected JSON chunk");
  88251. }
  88252. case ChunkFormat.BIN: {
  88253. bin = binaryReader.readUint8Array(chunkLength_1);
  88254. break;
  88255. }
  88256. default: {
  88257. // ignore unrecognized chunkFormat
  88258. binaryReader.skipBytes(chunkLength_1);
  88259. break;
  88260. }
  88261. }
  88262. }
  88263. return {
  88264. json: json,
  88265. bin: bin
  88266. };
  88267. };
  88268. GLTFFileLoader._parseVersion = function (version) {
  88269. if (version === "1.0" || version === "1.0.1") {
  88270. return {
  88271. major: 1,
  88272. minor: 0
  88273. };
  88274. }
  88275. var match = (version + "").match(/^(\d+)\.(\d+)/);
  88276. if (!match) {
  88277. return null;
  88278. }
  88279. return {
  88280. major: parseInt(match[1]),
  88281. minor: parseInt(match[2])
  88282. };
  88283. };
  88284. GLTFFileLoader._compareVersion = function (a, b) {
  88285. if (a.major > b.major)
  88286. return 1;
  88287. if (a.major < b.major)
  88288. return -1;
  88289. if (a.minor > b.minor)
  88290. return 1;
  88291. if (a.minor < b.minor)
  88292. return -1;
  88293. return 0;
  88294. };
  88295. GLTFFileLoader._decodeBufferToText = function (buffer) {
  88296. var result = "";
  88297. var length = buffer.byteLength;
  88298. for (var i = 0; i < length; i++) {
  88299. result += String.fromCharCode(buffer[i]);
  88300. }
  88301. return result;
  88302. };
  88303. // #endregion
  88304. // #region V1 options
  88305. GLTFFileLoader.IncrementalLoading = true;
  88306. GLTFFileLoader.HomogeneousCoordinates = false;
  88307. return GLTFFileLoader;
  88308. }());
  88309. BABYLON.GLTFFileLoader = GLTFFileLoader;
  88310. var BinaryReader = /** @class */ (function () {
  88311. function BinaryReader(arrayBuffer) {
  88312. this._arrayBuffer = arrayBuffer;
  88313. this._dataView = new DataView(arrayBuffer);
  88314. this._byteOffset = 0;
  88315. }
  88316. BinaryReader.prototype.getPosition = function () {
  88317. return this._byteOffset;
  88318. };
  88319. BinaryReader.prototype.getLength = function () {
  88320. return this._arrayBuffer.byteLength;
  88321. };
  88322. BinaryReader.prototype.readUint32 = function () {
  88323. var value = this._dataView.getUint32(this._byteOffset, true);
  88324. this._byteOffset += 4;
  88325. return value;
  88326. };
  88327. BinaryReader.prototype.readUint8Array = function (length) {
  88328. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  88329. this._byteOffset += length;
  88330. return value;
  88331. };
  88332. BinaryReader.prototype.skipBytes = function (length) {
  88333. this._byteOffset += length;
  88334. };
  88335. return BinaryReader;
  88336. }());
  88337. if (BABYLON.SceneLoader) {
  88338. BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  88339. }
  88340. })(BABYLON || (BABYLON = {}));
  88341. //# sourceMappingURL=babylon.glTFFileLoader.js.map
  88342. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  88343. var BABYLON;
  88344. (function (BABYLON) {
  88345. var GLTF1;
  88346. (function (GLTF1) {
  88347. /**
  88348. * Enums
  88349. */
  88350. var EComponentType;
  88351. (function (EComponentType) {
  88352. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  88353. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  88354. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  88355. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  88356. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  88357. })(EComponentType = GLTF1.EComponentType || (GLTF1.EComponentType = {}));
  88358. var EShaderType;
  88359. (function (EShaderType) {
  88360. EShaderType[EShaderType["FRAGMENT"] = 35632] = "FRAGMENT";
  88361. EShaderType[EShaderType["VERTEX"] = 35633] = "VERTEX";
  88362. })(EShaderType = GLTF1.EShaderType || (GLTF1.EShaderType = {}));
  88363. var EParameterType;
  88364. (function (EParameterType) {
  88365. EParameterType[EParameterType["BYTE"] = 5120] = "BYTE";
  88366. EParameterType[EParameterType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  88367. EParameterType[EParameterType["SHORT"] = 5122] = "SHORT";
  88368. EParameterType[EParameterType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  88369. EParameterType[EParameterType["INT"] = 5124] = "INT";
  88370. EParameterType[EParameterType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  88371. EParameterType[EParameterType["FLOAT"] = 5126] = "FLOAT";
  88372. EParameterType[EParameterType["FLOAT_VEC2"] = 35664] = "FLOAT_VEC2";
  88373. EParameterType[EParameterType["FLOAT_VEC3"] = 35665] = "FLOAT_VEC3";
  88374. EParameterType[EParameterType["FLOAT_VEC4"] = 35666] = "FLOAT_VEC4";
  88375. EParameterType[EParameterType["INT_VEC2"] = 35667] = "INT_VEC2";
  88376. EParameterType[EParameterType["INT_VEC3"] = 35668] = "INT_VEC3";
  88377. EParameterType[EParameterType["INT_VEC4"] = 35669] = "INT_VEC4";
  88378. EParameterType[EParameterType["BOOL"] = 35670] = "BOOL";
  88379. EParameterType[EParameterType["BOOL_VEC2"] = 35671] = "BOOL_VEC2";
  88380. EParameterType[EParameterType["BOOL_VEC3"] = 35672] = "BOOL_VEC3";
  88381. EParameterType[EParameterType["BOOL_VEC4"] = 35673] = "BOOL_VEC4";
  88382. EParameterType[EParameterType["FLOAT_MAT2"] = 35674] = "FLOAT_MAT2";
  88383. EParameterType[EParameterType["FLOAT_MAT3"] = 35675] = "FLOAT_MAT3";
  88384. EParameterType[EParameterType["FLOAT_MAT4"] = 35676] = "FLOAT_MAT4";
  88385. EParameterType[EParameterType["SAMPLER_2D"] = 35678] = "SAMPLER_2D";
  88386. })(EParameterType = GLTF1.EParameterType || (GLTF1.EParameterType = {}));
  88387. var ETextureWrapMode;
  88388. (function (ETextureWrapMode) {
  88389. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  88390. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  88391. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  88392. })(ETextureWrapMode = GLTF1.ETextureWrapMode || (GLTF1.ETextureWrapMode = {}));
  88393. var ETextureFilterType;
  88394. (function (ETextureFilterType) {
  88395. ETextureFilterType[ETextureFilterType["NEAREST"] = 9728] = "NEAREST";
  88396. ETextureFilterType[ETextureFilterType["LINEAR"] = 9728] = "LINEAR";
  88397. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  88398. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  88399. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  88400. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  88401. })(ETextureFilterType = GLTF1.ETextureFilterType || (GLTF1.ETextureFilterType = {}));
  88402. var ETextureFormat;
  88403. (function (ETextureFormat) {
  88404. ETextureFormat[ETextureFormat["ALPHA"] = 6406] = "ALPHA";
  88405. ETextureFormat[ETextureFormat["RGB"] = 6407] = "RGB";
  88406. ETextureFormat[ETextureFormat["RGBA"] = 6408] = "RGBA";
  88407. ETextureFormat[ETextureFormat["LUMINANCE"] = 6409] = "LUMINANCE";
  88408. ETextureFormat[ETextureFormat["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA";
  88409. })(ETextureFormat = GLTF1.ETextureFormat || (GLTF1.ETextureFormat = {}));
  88410. var ECullingType;
  88411. (function (ECullingType) {
  88412. ECullingType[ECullingType["FRONT"] = 1028] = "FRONT";
  88413. ECullingType[ECullingType["BACK"] = 1029] = "BACK";
  88414. ECullingType[ECullingType["FRONT_AND_BACK"] = 1032] = "FRONT_AND_BACK";
  88415. })(ECullingType = GLTF1.ECullingType || (GLTF1.ECullingType = {}));
  88416. var EBlendingFunction;
  88417. (function (EBlendingFunction) {
  88418. EBlendingFunction[EBlendingFunction["ZERO"] = 0] = "ZERO";
  88419. EBlendingFunction[EBlendingFunction["ONE"] = 1] = "ONE";
  88420. EBlendingFunction[EBlendingFunction["SRC_COLOR"] = 768] = "SRC_COLOR";
  88421. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_COLOR"] = 769] = "ONE_MINUS_SRC_COLOR";
  88422. EBlendingFunction[EBlendingFunction["DST_COLOR"] = 774] = "DST_COLOR";
  88423. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_COLOR"] = 775] = "ONE_MINUS_DST_COLOR";
  88424. EBlendingFunction[EBlendingFunction["SRC_ALPHA"] = 770] = "SRC_ALPHA";
  88425. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_ALPHA"] = 771] = "ONE_MINUS_SRC_ALPHA";
  88426. EBlendingFunction[EBlendingFunction["DST_ALPHA"] = 772] = "DST_ALPHA";
  88427. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_ALPHA"] = 773] = "ONE_MINUS_DST_ALPHA";
  88428. EBlendingFunction[EBlendingFunction["CONSTANT_COLOR"] = 32769] = "CONSTANT_COLOR";
  88429. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_COLOR"] = 32770] = "ONE_MINUS_CONSTANT_COLOR";
  88430. EBlendingFunction[EBlendingFunction["CONSTANT_ALPHA"] = 32771] = "CONSTANT_ALPHA";
  88431. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_ALPHA"] = 32772] = "ONE_MINUS_CONSTANT_ALPHA";
  88432. EBlendingFunction[EBlendingFunction["SRC_ALPHA_SATURATE"] = 776] = "SRC_ALPHA_SATURATE";
  88433. })(EBlendingFunction = GLTF1.EBlendingFunction || (GLTF1.EBlendingFunction = {}));
  88434. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  88435. })(BABYLON || (BABYLON = {}));
  88436. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  88437. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  88438. var BABYLON;
  88439. (function (BABYLON) {
  88440. var GLTF1;
  88441. (function (GLTF1) {
  88442. /**
  88443. * Tokenizer. Used for shaders compatibility
  88444. * Automatically map world, view, projection, worldViewProjection, attributes and so on
  88445. */
  88446. var ETokenType;
  88447. (function (ETokenType) {
  88448. ETokenType[ETokenType["IDENTIFIER"] = 1] = "IDENTIFIER";
  88449. ETokenType[ETokenType["UNKNOWN"] = 2] = "UNKNOWN";
  88450. ETokenType[ETokenType["END_OF_INPUT"] = 3] = "END_OF_INPUT";
  88451. })(ETokenType || (ETokenType = {}));
  88452. var Tokenizer = /** @class */ (function () {
  88453. function Tokenizer(toParse) {
  88454. this._pos = 0;
  88455. this.isLetterOrDigitPattern = /^[a-zA-Z0-9]+$/;
  88456. this._toParse = toParse;
  88457. this._maxPos = toParse.length;
  88458. }
  88459. Tokenizer.prototype.getNextToken = function () {
  88460. if (this.isEnd())
  88461. return ETokenType.END_OF_INPUT;
  88462. this.currentString = this.read();
  88463. this.currentToken = ETokenType.UNKNOWN;
  88464. if (this.currentString === "_" || this.isLetterOrDigitPattern.test(this.currentString)) {
  88465. this.currentToken = ETokenType.IDENTIFIER;
  88466. this.currentIdentifier = this.currentString;
  88467. while (!this.isEnd() && (this.isLetterOrDigitPattern.test(this.currentString = this.peek()) || this.currentString === "_")) {
  88468. this.currentIdentifier += this.currentString;
  88469. this.forward();
  88470. }
  88471. }
  88472. return this.currentToken;
  88473. };
  88474. Tokenizer.prototype.peek = function () {
  88475. return this._toParse[this._pos];
  88476. };
  88477. Tokenizer.prototype.read = function () {
  88478. return this._toParse[this._pos++];
  88479. };
  88480. Tokenizer.prototype.forward = function () {
  88481. this._pos++;
  88482. };
  88483. Tokenizer.prototype.isEnd = function () {
  88484. return this._pos >= this._maxPos;
  88485. };
  88486. return Tokenizer;
  88487. }());
  88488. /**
  88489. * Values
  88490. */
  88491. var glTFTransforms = ["MODEL", "VIEW", "PROJECTION", "MODELVIEW", "MODELVIEWPROJECTION", "JOINTMATRIX"];
  88492. var babylonTransforms = ["world", "view", "projection", "worldView", "worldViewProjection", "mBones"];
  88493. var glTFAnimationPaths = ["translation", "rotation", "scale"];
  88494. var babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"];
  88495. /**
  88496. * Parse
  88497. */
  88498. var parseBuffers = function (parsedBuffers, gltfRuntime) {
  88499. for (var buf in parsedBuffers) {
  88500. var parsedBuffer = parsedBuffers[buf];
  88501. gltfRuntime.buffers[buf] = parsedBuffer;
  88502. gltfRuntime.buffersCount++;
  88503. }
  88504. };
  88505. var parseShaders = function (parsedShaders, gltfRuntime) {
  88506. for (var sha in parsedShaders) {
  88507. var parsedShader = parsedShaders[sha];
  88508. gltfRuntime.shaders[sha] = parsedShader;
  88509. gltfRuntime.shaderscount++;
  88510. }
  88511. };
  88512. var parseObject = function (parsedObjects, runtimeProperty, gltfRuntime) {
  88513. for (var object in parsedObjects) {
  88514. var parsedObject = parsedObjects[object];
  88515. gltfRuntime[runtimeProperty][object] = parsedObject;
  88516. }
  88517. };
  88518. /**
  88519. * Utils
  88520. */
  88521. var normalizeUVs = function (buffer) {
  88522. if (!buffer) {
  88523. return;
  88524. }
  88525. for (var i = 0; i < buffer.length / 2; i++) {
  88526. buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1];
  88527. }
  88528. };
  88529. var getAttribute = function (attributeParameter) {
  88530. if (attributeParameter.semantic === "NORMAL") {
  88531. return "normal";
  88532. }
  88533. else if (attributeParameter.semantic === "POSITION") {
  88534. return "position";
  88535. }
  88536. else if (attributeParameter.semantic === "JOINT") {
  88537. return "matricesIndices";
  88538. }
  88539. else if (attributeParameter.semantic === "WEIGHT") {
  88540. return "matricesWeights";
  88541. }
  88542. else if (attributeParameter.semantic === "COLOR") {
  88543. return "color";
  88544. }
  88545. else if (attributeParameter.semantic && attributeParameter.semantic.indexOf("TEXCOORD_") !== -1) {
  88546. var channel = Number(attributeParameter.semantic.split("_")[1]);
  88547. return "uv" + (channel === 0 ? "" : channel + 1);
  88548. }
  88549. return null;
  88550. };
  88551. /**
  88552. * Loads and creates animations
  88553. */
  88554. var loadAnimations = function (gltfRuntime) {
  88555. for (var anim in gltfRuntime.animations) {
  88556. var animation = gltfRuntime.animations[anim];
  88557. if (!animation.channels || !animation.samplers) {
  88558. continue;
  88559. }
  88560. var lastAnimation = null;
  88561. for (var i = 0; i < animation.channels.length; i++) {
  88562. // Get parameters and load buffers
  88563. var channel = animation.channels[i];
  88564. var sampler = animation.samplers[channel.sampler];
  88565. if (!sampler) {
  88566. continue;
  88567. }
  88568. var inputData = null;
  88569. var outputData = null;
  88570. if (animation.parameters) {
  88571. inputData = animation.parameters[sampler.input];
  88572. outputData = animation.parameters[sampler.output];
  88573. }
  88574. else {
  88575. inputData = sampler.input;
  88576. outputData = sampler.output;
  88577. }
  88578. var bufferInput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]);
  88579. var bufferOutput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]);
  88580. var targetID = channel.target.id;
  88581. var targetNode = gltfRuntime.scene.getNodeByID(targetID);
  88582. if (targetNode === null) {
  88583. targetNode = gltfRuntime.scene.getNodeByName(targetID);
  88584. }
  88585. if (targetNode === null) {
  88586. BABYLON.Tools.Warn("Creating animation named " + anim + ". But cannot find node named " + targetID + " to attach to");
  88587. continue;
  88588. }
  88589. var isBone = targetNode instanceof BABYLON.Bone;
  88590. // Get target path (position, rotation or scaling)
  88591. var targetPath = channel.target.path;
  88592. var targetPathIndex = glTFAnimationPaths.indexOf(targetPath);
  88593. if (targetPathIndex !== -1) {
  88594. targetPath = babylonAnimationPaths[targetPathIndex];
  88595. }
  88596. // Determine animation type
  88597. var animationType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  88598. if (!isBone) {
  88599. if (targetPath === "rotationQuaternion") {
  88600. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  88601. targetNode.rotationQuaternion = new BABYLON.Quaternion();
  88602. }
  88603. else {
  88604. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  88605. }
  88606. }
  88607. // Create animation and key frames
  88608. var babylonAnimation = null;
  88609. var keys = [];
  88610. var arrayOffset = 0;
  88611. var modifyKey = false;
  88612. if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) {
  88613. babylonAnimation = lastAnimation;
  88614. modifyKey = true;
  88615. }
  88616. if (!modifyKey) {
  88617. babylonAnimation = new BABYLON.Animation(anim, isBone ? "_matrix" : targetPath, 1, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  88618. }
  88619. // For each frame
  88620. for (var j = 0; j < bufferInput.length; j++) {
  88621. var value = null;
  88622. if (targetPath === "rotationQuaternion") {
  88623. value = BABYLON.Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);
  88624. arrayOffset += 4;
  88625. }
  88626. else {
  88627. value = BABYLON.Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);
  88628. arrayOffset += 3;
  88629. }
  88630. if (isBone) {
  88631. var bone = targetNode;
  88632. var translation = BABYLON.Vector3.Zero();
  88633. var rotationQuaternion = new BABYLON.Quaternion();
  88634. var scaling = BABYLON.Vector3.Zero();
  88635. // Warning on decompose
  88636. var mat = bone.getBaseMatrix();
  88637. if (modifyKey && lastAnimation) {
  88638. mat = lastAnimation.getKeys()[j].value;
  88639. }
  88640. mat.decompose(scaling, rotationQuaternion, translation);
  88641. if (targetPath === "position") {
  88642. translation = value;
  88643. }
  88644. else if (targetPath === "rotationQuaternion") {
  88645. rotationQuaternion = value;
  88646. }
  88647. else {
  88648. scaling = value;
  88649. }
  88650. value = BABYLON.Matrix.Compose(scaling, rotationQuaternion, translation);
  88651. }
  88652. if (!modifyKey) {
  88653. keys.push({
  88654. frame: bufferInput[j],
  88655. value: value
  88656. });
  88657. }
  88658. else if (lastAnimation) {
  88659. lastAnimation.getKeys()[j].value = value;
  88660. }
  88661. }
  88662. // Finish
  88663. if (!modifyKey && babylonAnimation) {
  88664. babylonAnimation.setKeys(keys);
  88665. targetNode.animations.push(babylonAnimation);
  88666. }
  88667. lastAnimation = babylonAnimation;
  88668. gltfRuntime.scene.stopAnimation(targetNode);
  88669. gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);
  88670. }
  88671. }
  88672. };
  88673. /**
  88674. * Returns the bones transformation matrix
  88675. */
  88676. var configureBoneTransformation = function (node) {
  88677. var mat = null;
  88678. if (node.translation || node.rotation || node.scale) {
  88679. var scale = BABYLON.Vector3.FromArray(node.scale || [1, 1, 1]);
  88680. var rotation = BABYLON.Quaternion.FromArray(node.rotation || [0, 0, 0, 1]);
  88681. var position = BABYLON.Vector3.FromArray(node.translation || [0, 0, 0]);
  88682. mat = BABYLON.Matrix.Compose(scale, rotation, position);
  88683. }
  88684. else {
  88685. mat = BABYLON.Matrix.FromArray(node.matrix);
  88686. }
  88687. return mat;
  88688. };
  88689. /**
  88690. * Returns the parent bone
  88691. */
  88692. var getParentBone = function (gltfRuntime, skins, jointName, newSkeleton) {
  88693. // Try to find
  88694. for (var i = 0; i < newSkeleton.bones.length; i++) {
  88695. if (newSkeleton.bones[i].name === jointName) {
  88696. return newSkeleton.bones[i];
  88697. }
  88698. }
  88699. // Not found, search in gltf nodes
  88700. var nodes = gltfRuntime.nodes;
  88701. for (var nde in nodes) {
  88702. var node = nodes[nde];
  88703. if (!node.jointName) {
  88704. continue;
  88705. }
  88706. var children = node.children;
  88707. for (var i = 0; i < children.length; i++) {
  88708. var child = gltfRuntime.nodes[children[i]];
  88709. if (!child.jointName) {
  88710. continue;
  88711. }
  88712. if (child.jointName === jointName) {
  88713. var mat = configureBoneTransformation(node);
  88714. var bone = new BABYLON.Bone(node.name || "", newSkeleton, getParentBone(gltfRuntime, skins, node.jointName, newSkeleton), mat);
  88715. bone.id = nde;
  88716. return bone;
  88717. }
  88718. }
  88719. }
  88720. return null;
  88721. };
  88722. /**
  88723. * Returns the appropriate root node
  88724. */
  88725. var getNodeToRoot = function (nodesToRoot, id) {
  88726. for (var i = 0; i < nodesToRoot.length; i++) {
  88727. var nodeToRoot = nodesToRoot[i];
  88728. for (var j = 0; j < nodeToRoot.node.children.length; j++) {
  88729. var child = nodeToRoot.node.children[j];
  88730. if (child === id) {
  88731. return nodeToRoot.bone;
  88732. }
  88733. }
  88734. }
  88735. return null;
  88736. };
  88737. /**
  88738. * Returns the node with the joint name
  88739. */
  88740. var getJointNode = function (gltfRuntime, jointName) {
  88741. var nodes = gltfRuntime.nodes;
  88742. var node = nodes[jointName];
  88743. if (node) {
  88744. return {
  88745. node: node,
  88746. id: jointName
  88747. };
  88748. }
  88749. for (var nde in nodes) {
  88750. node = nodes[nde];
  88751. if (node.jointName === jointName) {
  88752. return {
  88753. node: node,
  88754. id: nde
  88755. };
  88756. }
  88757. }
  88758. return null;
  88759. };
  88760. /**
  88761. * Checks if a nodes is in joints
  88762. */
  88763. var nodeIsInJoints = function (skins, id) {
  88764. for (var i = 0; i < skins.jointNames.length; i++) {
  88765. if (skins.jointNames[i] === id) {
  88766. return true;
  88767. }
  88768. }
  88769. return false;
  88770. };
  88771. /**
  88772. * Fills the nodes to root for bones and builds hierarchy
  88773. */
  88774. var getNodesToRoot = function (gltfRuntime, newSkeleton, skins, nodesToRoot) {
  88775. // Creates nodes for root
  88776. for (var nde in gltfRuntime.nodes) {
  88777. var node = gltfRuntime.nodes[nde];
  88778. var id = nde;
  88779. if (!node.jointName || nodeIsInJoints(skins, node.jointName)) {
  88780. continue;
  88781. }
  88782. // Create node to root bone
  88783. var mat = configureBoneTransformation(node);
  88784. var bone = new BABYLON.Bone(node.name || "", newSkeleton, null, mat);
  88785. bone.id = id;
  88786. nodesToRoot.push({ bone: bone, node: node, id: id });
  88787. }
  88788. // Parenting
  88789. for (var i = 0; i < nodesToRoot.length; i++) {
  88790. var nodeToRoot = nodesToRoot[i];
  88791. var children = nodeToRoot.node.children;
  88792. for (var j = 0; j < children.length; j++) {
  88793. var child = null;
  88794. for (var k = 0; k < nodesToRoot.length; k++) {
  88795. if (nodesToRoot[k].id === children[j]) {
  88796. child = nodesToRoot[k];
  88797. break;
  88798. }
  88799. }
  88800. if (child) {
  88801. child.bone._parent = nodeToRoot.bone;
  88802. nodeToRoot.bone.children.push(child.bone);
  88803. }
  88804. }
  88805. }
  88806. };
  88807. /**
  88808. * Imports a skeleton
  88809. */
  88810. var importSkeleton = function (gltfRuntime, skins, mesh, newSkeleton, id) {
  88811. if (!newSkeleton) {
  88812. newSkeleton = new BABYLON.Skeleton(skins.name || "", "", gltfRuntime.scene);
  88813. }
  88814. if (!skins.babylonSkeleton) {
  88815. return newSkeleton;
  88816. }
  88817. // Find the root bones
  88818. var nodesToRoot = [];
  88819. var nodesToRootToAdd = [];
  88820. getNodesToRoot(gltfRuntime, newSkeleton, skins, nodesToRoot);
  88821. newSkeleton.bones = [];
  88822. // Joints
  88823. for (var i = 0; i < skins.jointNames.length; i++) {
  88824. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  88825. if (!jointNode) {
  88826. continue;
  88827. }
  88828. var node = jointNode.node;
  88829. if (!node) {
  88830. BABYLON.Tools.Warn("Joint named " + skins.jointNames[i] + " does not exist");
  88831. continue;
  88832. }
  88833. var id = jointNode.id;
  88834. // Optimize, if the bone already exists...
  88835. var existingBone = gltfRuntime.scene.getBoneByID(id);
  88836. if (existingBone) {
  88837. newSkeleton.bones.push(existingBone);
  88838. continue;
  88839. }
  88840. // Search for parent bone
  88841. var foundBone = false;
  88842. var parentBone = null;
  88843. for (var j = 0; j < i; j++) {
  88844. var jointNode_1 = getJointNode(gltfRuntime, skins.jointNames[j]);
  88845. if (!jointNode_1) {
  88846. continue;
  88847. }
  88848. var joint = jointNode_1.node;
  88849. if (!joint) {
  88850. BABYLON.Tools.Warn("Joint named " + skins.jointNames[j] + " does not exist when looking for parent");
  88851. continue;
  88852. }
  88853. var children = joint.children;
  88854. if (!children) {
  88855. continue;
  88856. }
  88857. foundBone = false;
  88858. for (var k = 0; k < children.length; k++) {
  88859. if (children[k] === id) {
  88860. parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton);
  88861. foundBone = true;
  88862. break;
  88863. }
  88864. }
  88865. if (foundBone) {
  88866. break;
  88867. }
  88868. }
  88869. // Create bone
  88870. var mat = configureBoneTransformation(node);
  88871. if (!parentBone && nodesToRoot.length > 0) {
  88872. parentBone = getNodeToRoot(nodesToRoot, id);
  88873. if (parentBone) {
  88874. if (nodesToRootToAdd.indexOf(parentBone) === -1) {
  88875. nodesToRootToAdd.push(parentBone);
  88876. }
  88877. }
  88878. }
  88879. var bone = new BABYLON.Bone(node.jointName || "", newSkeleton, parentBone, mat);
  88880. bone.id = id;
  88881. }
  88882. // Polish
  88883. var bones = newSkeleton.bones;
  88884. newSkeleton.bones = [];
  88885. for (var i = 0; i < skins.jointNames.length; i++) {
  88886. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  88887. if (!jointNode) {
  88888. continue;
  88889. }
  88890. for (var j = 0; j < bones.length; j++) {
  88891. if (bones[j].id === jointNode.id) {
  88892. newSkeleton.bones.push(bones[j]);
  88893. break;
  88894. }
  88895. }
  88896. }
  88897. newSkeleton.prepare();
  88898. // Finish
  88899. for (var i = 0; i < nodesToRootToAdd.length; i++) {
  88900. newSkeleton.bones.push(nodesToRootToAdd[i]);
  88901. }
  88902. return newSkeleton;
  88903. };
  88904. /**
  88905. * Imports a mesh and its geometries
  88906. */
  88907. var importMesh = function (gltfRuntime, node, meshes, id, newMesh) {
  88908. if (!newMesh) {
  88909. newMesh = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  88910. newMesh.id = id;
  88911. }
  88912. if (!node.babylonNode) {
  88913. return newMesh;
  88914. }
  88915. var subMaterials = [];
  88916. var vertexData = null;
  88917. var verticesStarts = new Array();
  88918. var verticesCounts = new Array();
  88919. var indexStarts = new Array();
  88920. var indexCounts = new Array();
  88921. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  88922. var meshID = meshes[meshIndex];
  88923. var mesh = gltfRuntime.meshes[meshID];
  88924. if (!mesh) {
  88925. continue;
  88926. }
  88927. // Positions, normals and UVs
  88928. for (var i = 0; i < mesh.primitives.length; i++) {
  88929. // Temporary vertex data
  88930. var tempVertexData = new BABYLON.VertexData();
  88931. var primitive = mesh.primitives[i];
  88932. if (primitive.mode !== 4) {
  88933. // continue;
  88934. }
  88935. var attributes = primitive.attributes;
  88936. var accessor = null;
  88937. var buffer = null;
  88938. // Set positions, normal and uvs
  88939. for (var semantic in attributes) {
  88940. // Link accessor and buffer view
  88941. accessor = gltfRuntime.accessors[attributes[semantic]];
  88942. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  88943. if (semantic === "NORMAL") {
  88944. tempVertexData.normals = new Float32Array(buffer.length);
  88945. tempVertexData.normals.set(buffer);
  88946. }
  88947. else if (semantic === "POSITION") {
  88948. if (BABYLON.GLTFFileLoader.HomogeneousCoordinates) {
  88949. tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4);
  88950. for (var j = 0; j < buffer.length; j += 4) {
  88951. tempVertexData.positions[j] = buffer[j];
  88952. tempVertexData.positions[j + 1] = buffer[j + 1];
  88953. tempVertexData.positions[j + 2] = buffer[j + 2];
  88954. }
  88955. }
  88956. else {
  88957. tempVertexData.positions = new Float32Array(buffer.length);
  88958. tempVertexData.positions.set(buffer);
  88959. }
  88960. verticesCounts.push(tempVertexData.positions.length);
  88961. }
  88962. else if (semantic.indexOf("TEXCOORD_") !== -1) {
  88963. var channel = Number(semantic.split("_")[1]);
  88964. var uvKind = BABYLON.VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
  88965. var uvs = new Float32Array(buffer.length);
  88966. uvs.set(buffer);
  88967. normalizeUVs(uvs);
  88968. tempVertexData.set(uvs, uvKind);
  88969. }
  88970. else if (semantic === "JOINT") {
  88971. tempVertexData.matricesIndices = new Float32Array(buffer.length);
  88972. tempVertexData.matricesIndices.set(buffer);
  88973. }
  88974. else if (semantic === "WEIGHT") {
  88975. tempVertexData.matricesWeights = new Float32Array(buffer.length);
  88976. tempVertexData.matricesWeights.set(buffer);
  88977. }
  88978. else if (semantic === "COLOR") {
  88979. tempVertexData.colors = new Float32Array(buffer.length);
  88980. tempVertexData.colors.set(buffer);
  88981. }
  88982. }
  88983. // Indices
  88984. accessor = gltfRuntime.accessors[primitive.indices];
  88985. if (accessor) {
  88986. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  88987. tempVertexData.indices = new Int32Array(buffer.length);
  88988. tempVertexData.indices.set(buffer);
  88989. indexCounts.push(tempVertexData.indices.length);
  88990. }
  88991. else {
  88992. // Set indices on the fly
  88993. var indices = [];
  88994. for (var j = 0; j < tempVertexData.positions.length / 3; j++) {
  88995. indices.push(j);
  88996. }
  88997. tempVertexData.indices = new Int32Array(indices);
  88998. indexCounts.push(tempVertexData.indices.length);
  88999. }
  89000. if (!vertexData) {
  89001. vertexData = tempVertexData;
  89002. }
  89003. else {
  89004. vertexData.merge(tempVertexData);
  89005. }
  89006. // Sub material
  89007. var material_1 = gltfRuntime.scene.getMaterialByID(primitive.material);
  89008. subMaterials.push(material_1 === null ? GLTF1.GLTFUtils.GetDefaultMaterial(gltfRuntime.scene) : material_1);
  89009. // Update vertices start and index start
  89010. verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
  89011. indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
  89012. }
  89013. }
  89014. var material;
  89015. if (subMaterials.length > 1) {
  89016. material = new BABYLON.MultiMaterial("multimat" + id, gltfRuntime.scene);
  89017. material.subMaterials = subMaterials;
  89018. }
  89019. else {
  89020. material = new BABYLON.StandardMaterial("multimat" + id, gltfRuntime.scene);
  89021. }
  89022. if (subMaterials.length === 1) {
  89023. material = subMaterials[0];
  89024. }
  89025. if (!newMesh.material) {
  89026. newMesh.material = material;
  89027. }
  89028. // Apply geometry
  89029. new BABYLON.Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);
  89030. newMesh.computeWorldMatrix(true);
  89031. // Apply submeshes
  89032. newMesh.subMeshes = [];
  89033. var index = 0;
  89034. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  89035. var meshID = meshes[meshIndex];
  89036. var mesh = gltfRuntime.meshes[meshID];
  89037. if (!mesh) {
  89038. continue;
  89039. }
  89040. for (var i = 0; i < mesh.primitives.length; i++) {
  89041. if (mesh.primitives[i].mode !== 4) {
  89042. //continue;
  89043. }
  89044. BABYLON.SubMesh.AddToMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);
  89045. index++;
  89046. }
  89047. }
  89048. // Finish
  89049. return newMesh;
  89050. };
  89051. /**
  89052. * Configure node transformation from position, rotation and scaling
  89053. */
  89054. var configureNode = function (newNode, position, rotation, scaling) {
  89055. if (newNode.position) {
  89056. newNode.position = position;
  89057. }
  89058. if (newNode.rotationQuaternion || newNode.rotation) {
  89059. newNode.rotationQuaternion = rotation;
  89060. }
  89061. if (newNode.scaling) {
  89062. newNode.scaling = scaling;
  89063. }
  89064. };
  89065. /**
  89066. * Configures node from transformation matrix
  89067. */
  89068. var configureNodeFromMatrix = function (newNode, node, parent) {
  89069. if (node.matrix) {
  89070. var position = new BABYLON.Vector3(0, 0, 0);
  89071. var rotation = new BABYLON.Quaternion();
  89072. var scaling = new BABYLON.Vector3(0, 0, 0);
  89073. var mat = BABYLON.Matrix.FromArray(node.matrix);
  89074. mat.decompose(scaling, rotation, position);
  89075. configureNode(newNode, position, rotation, scaling);
  89076. }
  89077. else if (node.translation && node.rotation && node.scale) {
  89078. configureNode(newNode, BABYLON.Vector3.FromArray(node.translation), BABYLON.Quaternion.FromArray(node.rotation), BABYLON.Vector3.FromArray(node.scale));
  89079. }
  89080. newNode.computeWorldMatrix(true);
  89081. };
  89082. /**
  89083. * Imports a node
  89084. */
  89085. var importNode = function (gltfRuntime, node, id, parent) {
  89086. var lastNode = null;
  89087. if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {
  89088. if (gltfRuntime.importMeshesNames && gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name || "") === -1) {
  89089. return null;
  89090. }
  89091. }
  89092. // Meshes
  89093. if (node.skin) {
  89094. if (node.meshes) {
  89095. var skin = gltfRuntime.skins[node.skin];
  89096. var newMesh = importMesh(gltfRuntime, node, node.meshes, id, node.babylonNode);
  89097. newMesh.skeleton = gltfRuntime.scene.getLastSkeletonByID(node.skin);
  89098. if (newMesh.skeleton === null) {
  89099. newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton, node.skin);
  89100. if (!skin.babylonSkeleton) {
  89101. skin.babylonSkeleton = newMesh.skeleton;
  89102. }
  89103. }
  89104. lastNode = newMesh;
  89105. }
  89106. }
  89107. else if (node.meshes) {
  89108. /**
  89109. * Improve meshes property
  89110. */
  89111. var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, node.babylonNode);
  89112. lastNode = newMesh;
  89113. }
  89114. else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  89115. var light = gltfRuntime.lights[node.light];
  89116. if (light) {
  89117. if (light.type === "ambient") {
  89118. var ambienLight = light[light.type];
  89119. var hemiLight = new BABYLON.HemisphericLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  89120. hemiLight.name = node.name || "";
  89121. if (ambienLight.color) {
  89122. hemiLight.diffuse = BABYLON.Color3.FromArray(ambienLight.color);
  89123. }
  89124. lastNode = hemiLight;
  89125. }
  89126. else if (light.type === "directional") {
  89127. var directionalLight = light[light.type];
  89128. var dirLight = new BABYLON.DirectionalLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  89129. dirLight.name = node.name || "";
  89130. if (directionalLight.color) {
  89131. dirLight.diffuse = BABYLON.Color3.FromArray(directionalLight.color);
  89132. }
  89133. lastNode = dirLight;
  89134. }
  89135. else if (light.type === "point") {
  89136. var pointLight = light[light.type];
  89137. var ptLight = new BABYLON.PointLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  89138. ptLight.name = node.name || "";
  89139. if (pointLight.color) {
  89140. ptLight.diffuse = BABYLON.Color3.FromArray(pointLight.color);
  89141. }
  89142. lastNode = ptLight;
  89143. }
  89144. else if (light.type === "spot") {
  89145. var spotLight = light[light.type];
  89146. var spLight = new BABYLON.SpotLight(node.light, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, gltfRuntime.scene);
  89147. spLight.name = node.name || "";
  89148. if (spotLight.color) {
  89149. spLight.diffuse = BABYLON.Color3.FromArray(spotLight.color);
  89150. }
  89151. if (spotLight.fallOfAngle) {
  89152. spLight.angle = spotLight.fallOfAngle;
  89153. }
  89154. if (spotLight.fallOffExponent) {
  89155. spLight.exponent = spotLight.fallOffExponent;
  89156. }
  89157. lastNode = spLight;
  89158. }
  89159. }
  89160. }
  89161. else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  89162. var camera = gltfRuntime.cameras[node.camera];
  89163. if (camera) {
  89164. if (camera.type === "orthographic") {
  89165. var orthoCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  89166. orthoCamera.name = node.name || "";
  89167. orthoCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  89168. orthoCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  89169. lastNode = orthoCamera;
  89170. }
  89171. else if (camera.type === "perspective") {
  89172. var perspectiveCamera = camera[camera.type];
  89173. var persCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  89174. persCamera.name = node.name || "";
  89175. persCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  89176. if (!perspectiveCamera.aspectRatio) {
  89177. perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();
  89178. }
  89179. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  89180. persCamera.maxZ = perspectiveCamera.zfar;
  89181. persCamera.minZ = perspectiveCamera.znear;
  89182. }
  89183. lastNode = persCamera;
  89184. }
  89185. }
  89186. }
  89187. // Empty node
  89188. if (!node.jointName) {
  89189. if (node.babylonNode) {
  89190. return node.babylonNode;
  89191. }
  89192. else if (lastNode === null) {
  89193. var dummy = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  89194. node.babylonNode = dummy;
  89195. lastNode = dummy;
  89196. }
  89197. }
  89198. if (lastNode !== null) {
  89199. if (node.matrix && lastNode instanceof BABYLON.Mesh) {
  89200. configureNodeFromMatrix(lastNode, node, parent);
  89201. }
  89202. else {
  89203. var translation = node.translation || [0, 0, 0];
  89204. var rotation = node.rotation || [0, 0, 0, 1];
  89205. var scale = node.scale || [1, 1, 1];
  89206. configureNode(lastNode, BABYLON.Vector3.FromArray(translation), BABYLON.Quaternion.FromArray(rotation), BABYLON.Vector3.FromArray(scale));
  89207. }
  89208. lastNode.updateCache(true);
  89209. node.babylonNode = lastNode;
  89210. }
  89211. return lastNode;
  89212. };
  89213. /**
  89214. * Traverses nodes and creates them
  89215. */
  89216. var traverseNodes = function (gltfRuntime, id, parent, meshIncluded) {
  89217. if (meshIncluded === void 0) { meshIncluded = false; }
  89218. var node = gltfRuntime.nodes[id];
  89219. var newNode = null;
  89220. if (gltfRuntime.importOnlyMeshes && !meshIncluded && gltfRuntime.importMeshesNames) {
  89221. if (gltfRuntime.importMeshesNames.indexOf(node.name || "") !== -1 || gltfRuntime.importMeshesNames.length === 0) {
  89222. meshIncluded = true;
  89223. }
  89224. else {
  89225. meshIncluded = false;
  89226. }
  89227. }
  89228. else {
  89229. meshIncluded = true;
  89230. }
  89231. if (!node.jointName && meshIncluded) {
  89232. newNode = importNode(gltfRuntime, node, id, parent);
  89233. if (newNode !== null) {
  89234. newNode.id = id;
  89235. newNode.parent = parent;
  89236. }
  89237. }
  89238. if (node.children) {
  89239. for (var i = 0; i < node.children.length; i++) {
  89240. traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);
  89241. }
  89242. }
  89243. };
  89244. /**
  89245. * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.)
  89246. */
  89247. var postLoad = function (gltfRuntime) {
  89248. // Nodes
  89249. var currentScene = gltfRuntime.currentScene;
  89250. if (currentScene) {
  89251. for (var i = 0; i < currentScene.nodes.length; i++) {
  89252. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  89253. }
  89254. }
  89255. else {
  89256. for (var thing in gltfRuntime.scenes) {
  89257. currentScene = gltfRuntime.scenes[thing];
  89258. for (var i = 0; i < currentScene.nodes.length; i++) {
  89259. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  89260. }
  89261. }
  89262. }
  89263. // Set animations
  89264. loadAnimations(gltfRuntime);
  89265. for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) {
  89266. var skeleton = gltfRuntime.scene.skeletons[i];
  89267. gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  89268. }
  89269. };
  89270. /**
  89271. * onBind shaderrs callback to set uniforms and matrices
  89272. */
  89273. var onBindShaderMaterial = function (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess) {
  89274. var materialValues = material.values || technique.parameters;
  89275. for (var unif in unTreatedUniforms) {
  89276. var uniform = unTreatedUniforms[unif];
  89277. var type = uniform.type;
  89278. if (type === GLTF1.EParameterType.FLOAT_MAT2 || type === GLTF1.EParameterType.FLOAT_MAT3 || type === GLTF1.EParameterType.FLOAT_MAT4) {
  89279. if (uniform.semantic && !uniform.source && !uniform.node) {
  89280. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());
  89281. }
  89282. else if (uniform.semantic && (uniform.source || uniform.node)) {
  89283. var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node || "");
  89284. if (source === null) {
  89285. source = gltfRuntime.scene.getNodeByID(uniform.source || uniform.node || "");
  89286. }
  89287. if (source === null) {
  89288. continue;
  89289. }
  89290. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());
  89291. }
  89292. }
  89293. else {
  89294. var value = materialValues[technique.uniforms[unif]];
  89295. if (!value) {
  89296. continue;
  89297. }
  89298. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  89299. var texture = gltfRuntime.textures[material.values ? value : uniform.value].babylonTexture;
  89300. if (texture === null || texture === undefined) {
  89301. continue;
  89302. }
  89303. shaderMaterial.getEffect().setTexture(unif, texture);
  89304. }
  89305. else {
  89306. GLTF1.GLTFUtils.SetUniform((shaderMaterial.getEffect()), unif, value, type);
  89307. }
  89308. }
  89309. }
  89310. onSuccess(shaderMaterial);
  89311. };
  89312. /**
  89313. * Prepare uniforms to send the only one time
  89314. * Loads the appropriate textures
  89315. */
  89316. var prepareShaderMaterialUniforms = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) {
  89317. var materialValues = material.values || technique.parameters;
  89318. var techniqueUniforms = technique.uniforms;
  89319. /**
  89320. * Prepare values here (not matrices)
  89321. */
  89322. for (var unif in unTreatedUniforms) {
  89323. var uniform = unTreatedUniforms[unif];
  89324. var type = uniform.type;
  89325. var value = materialValues[techniqueUniforms[unif]];
  89326. if (value === undefined) {
  89327. // In case the value is the same for all materials
  89328. value = uniform.value;
  89329. }
  89330. if (!value) {
  89331. continue;
  89332. }
  89333. var onLoadTexture = function (uniformName) {
  89334. return function (texture) {
  89335. if (uniform.value && uniformName) {
  89336. // Static uniform
  89337. shaderMaterial.setTexture(uniformName, texture);
  89338. delete unTreatedUniforms[uniformName];
  89339. }
  89340. };
  89341. };
  89342. // Texture (sampler2D)
  89343. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  89344. GLTF1.GLTFLoaderExtension.LoadTextureAsync(gltfRuntime, material.values ? value : uniform.value, onLoadTexture(unif), function () { return onLoadTexture(null); });
  89345. }
  89346. else {
  89347. if (uniform.value && GLTF1.GLTFUtils.SetUniform(shaderMaterial, unif, material.values ? value : uniform.value, type)) {
  89348. // Static uniform
  89349. delete unTreatedUniforms[unif];
  89350. }
  89351. }
  89352. }
  89353. };
  89354. /**
  89355. * Shader compilation failed
  89356. */
  89357. var onShaderCompileError = function (program, shaderMaterial, onError) {
  89358. return function (effect, error) {
  89359. shaderMaterial.dispose(true);
  89360. onError("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied");
  89361. };
  89362. };
  89363. /**
  89364. * Shader compilation success
  89365. */
  89366. var onShaderCompileSuccess = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess) {
  89367. return function (_) {
  89368. prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
  89369. shaderMaterial.onBind = function (mesh) {
  89370. onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess);
  89371. };
  89372. };
  89373. };
  89374. /**
  89375. * Returns the appropriate uniform if already handled by babylon
  89376. */
  89377. var parseShaderUniforms = function (tokenizer, technique, unTreatedUniforms) {
  89378. for (var unif in technique.uniforms) {
  89379. var uniform = technique.uniforms[unif];
  89380. var uniformParameter = technique.parameters[uniform];
  89381. if (tokenizer.currentIdentifier === unif) {
  89382. if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {
  89383. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  89384. if (transformIndex !== -1) {
  89385. delete unTreatedUniforms[unif];
  89386. return babylonTransforms[transformIndex];
  89387. }
  89388. }
  89389. }
  89390. }
  89391. return tokenizer.currentIdentifier;
  89392. };
  89393. /**
  89394. * All shaders loaded. Create materials one by one
  89395. */
  89396. var importMaterials = function (gltfRuntime) {
  89397. // Create materials
  89398. for (var mat in gltfRuntime.materials) {
  89399. GLTF1.GLTFLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, function (material) { }, function () { });
  89400. }
  89401. };
  89402. /**
  89403. * Implementation of the base glTF spec
  89404. */
  89405. var GLTFLoaderBase = /** @class */ (function () {
  89406. function GLTFLoaderBase() {
  89407. }
  89408. GLTFLoaderBase.CreateRuntime = function (parsedData, scene, rootUrl) {
  89409. var gltfRuntime = {
  89410. extensions: {},
  89411. accessors: {},
  89412. buffers: {},
  89413. bufferViews: {},
  89414. meshes: {},
  89415. lights: {},
  89416. cameras: {},
  89417. nodes: {},
  89418. images: {},
  89419. textures: {},
  89420. shaders: {},
  89421. programs: {},
  89422. samplers: {},
  89423. techniques: {},
  89424. materials: {},
  89425. animations: {},
  89426. skins: {},
  89427. extensionsUsed: [],
  89428. scenes: {},
  89429. buffersCount: 0,
  89430. shaderscount: 0,
  89431. scene: scene,
  89432. rootUrl: rootUrl,
  89433. loadedBufferCount: 0,
  89434. loadedBufferViews: {},
  89435. loadedShaderCount: 0,
  89436. importOnlyMeshes: false,
  89437. dummyNodes: []
  89438. };
  89439. // Parse
  89440. if (parsedData.extensions) {
  89441. parseObject(parsedData.extensions, "extensions", gltfRuntime);
  89442. }
  89443. if (parsedData.extensionsUsed) {
  89444. parseObject(parsedData.extensionsUsed, "extensionsUsed", gltfRuntime);
  89445. }
  89446. if (parsedData.buffers) {
  89447. parseBuffers(parsedData.buffers, gltfRuntime);
  89448. }
  89449. if (parsedData.bufferViews) {
  89450. parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime);
  89451. }
  89452. if (parsedData.accessors) {
  89453. parseObject(parsedData.accessors, "accessors", gltfRuntime);
  89454. }
  89455. if (parsedData.meshes) {
  89456. parseObject(parsedData.meshes, "meshes", gltfRuntime);
  89457. }
  89458. if (parsedData.lights) {
  89459. parseObject(parsedData.lights, "lights", gltfRuntime);
  89460. }
  89461. if (parsedData.cameras) {
  89462. parseObject(parsedData.cameras, "cameras", gltfRuntime);
  89463. }
  89464. if (parsedData.nodes) {
  89465. parseObject(parsedData.nodes, "nodes", gltfRuntime);
  89466. }
  89467. if (parsedData.images) {
  89468. parseObject(parsedData.images, "images", gltfRuntime);
  89469. }
  89470. if (parsedData.textures) {
  89471. parseObject(parsedData.textures, "textures", gltfRuntime);
  89472. }
  89473. if (parsedData.shaders) {
  89474. parseShaders(parsedData.shaders, gltfRuntime);
  89475. }
  89476. if (parsedData.programs) {
  89477. parseObject(parsedData.programs, "programs", gltfRuntime);
  89478. }
  89479. if (parsedData.samplers) {
  89480. parseObject(parsedData.samplers, "samplers", gltfRuntime);
  89481. }
  89482. if (parsedData.techniques) {
  89483. parseObject(parsedData.techniques, "techniques", gltfRuntime);
  89484. }
  89485. if (parsedData.materials) {
  89486. parseObject(parsedData.materials, "materials", gltfRuntime);
  89487. }
  89488. if (parsedData.animations) {
  89489. parseObject(parsedData.animations, "animations", gltfRuntime);
  89490. }
  89491. if (parsedData.skins) {
  89492. parseObject(parsedData.skins, "skins", gltfRuntime);
  89493. }
  89494. if (parsedData.scenes) {
  89495. gltfRuntime.scenes = parsedData.scenes;
  89496. }
  89497. if (parsedData.scene && parsedData.scenes) {
  89498. gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];
  89499. }
  89500. return gltfRuntime;
  89501. };
  89502. GLTFLoaderBase.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  89503. var buffer = gltfRuntime.buffers[id];
  89504. if (BABYLON.Tools.IsBase64(buffer.uri)) {
  89505. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(buffer.uri))); });
  89506. }
  89507. else {
  89508. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, function (data) { return onSuccess(new Uint8Array(data)); }, onProgress, undefined, true, function (request) {
  89509. if (request) {
  89510. onError(request.status + " " + request.statusText);
  89511. }
  89512. });
  89513. }
  89514. };
  89515. GLTFLoaderBase.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  89516. var texture = gltfRuntime.textures[id];
  89517. if (!texture || !texture.source) {
  89518. onError("");
  89519. return;
  89520. }
  89521. if (texture.babylonTexture) {
  89522. onSuccess(null);
  89523. return;
  89524. }
  89525. var source = gltfRuntime.images[texture.source];
  89526. if (BABYLON.Tools.IsBase64(source.uri)) {
  89527. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(source.uri))); });
  89528. }
  89529. else {
  89530. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + source.uri, function (data) { return onSuccess(new Uint8Array(data)); }, undefined, undefined, true, function (request) {
  89531. if (request) {
  89532. onError(request.status + " " + request.statusText);
  89533. }
  89534. });
  89535. }
  89536. };
  89537. GLTFLoaderBase.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  89538. var texture = gltfRuntime.textures[id];
  89539. if (texture.babylonTexture) {
  89540. onSuccess(texture.babylonTexture);
  89541. return;
  89542. }
  89543. var sampler = gltfRuntime.samplers[texture.sampler];
  89544. var createMipMaps = (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST) ||
  89545. (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_LINEAR) ||
  89546. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST) ||
  89547. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR);
  89548. var samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  89549. var blob = new Blob([buffer]);
  89550. var blobURL = URL.createObjectURL(blob);
  89551. var revokeBlobURL = function () { return URL.revokeObjectURL(blobURL); };
  89552. var newTexture = new BABYLON.Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL);
  89553. if (sampler.wrapS !== undefined) {
  89554. newTexture.wrapU = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapS);
  89555. }
  89556. if (sampler.wrapT !== undefined) {
  89557. newTexture.wrapV = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapT);
  89558. }
  89559. newTexture.name = id;
  89560. texture.babylonTexture = newTexture;
  89561. onSuccess(newTexture);
  89562. };
  89563. GLTFLoaderBase.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  89564. var shader = gltfRuntime.shaders[id];
  89565. if (BABYLON.Tools.IsBase64(shader.uri)) {
  89566. var shaderString = atob(shader.uri.split(",")[1]);
  89567. onSuccess(shaderString);
  89568. }
  89569. else {
  89570. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, undefined, undefined, false, function (request) {
  89571. if (request) {
  89572. onError(request.status + " " + request.statusText);
  89573. }
  89574. });
  89575. }
  89576. };
  89577. GLTFLoaderBase.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  89578. var material = gltfRuntime.materials[id];
  89579. if (!material.technique) {
  89580. if (onError) {
  89581. onError("No technique found.");
  89582. }
  89583. return;
  89584. }
  89585. var technique = gltfRuntime.techniques[material.technique];
  89586. if (!technique) {
  89587. var defaultMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  89588. defaultMaterial.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  89589. defaultMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  89590. onSuccess(defaultMaterial);
  89591. return;
  89592. }
  89593. var program = gltfRuntime.programs[technique.program];
  89594. var states = technique.states;
  89595. var vertexShader = BABYLON.Effect.ShadersStore[program.vertexShader + "VertexShader"];
  89596. var pixelShader = BABYLON.Effect.ShadersStore[program.fragmentShader + "PixelShader"];
  89597. var newVertexShader = "";
  89598. var newPixelShader = "";
  89599. var vertexTokenizer = new Tokenizer(vertexShader);
  89600. var pixelTokenizer = new Tokenizer(pixelShader);
  89601. var unTreatedUniforms = {};
  89602. var uniforms = [];
  89603. var attributes = [];
  89604. var samplers = [];
  89605. // Fill uniform, sampler2D and attributes
  89606. for (var unif in technique.uniforms) {
  89607. var uniform = technique.uniforms[unif];
  89608. var uniformParameter = technique.parameters[uniform];
  89609. unTreatedUniforms[unif] = uniformParameter;
  89610. if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {
  89611. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  89612. if (transformIndex !== -1) {
  89613. uniforms.push(babylonTransforms[transformIndex]);
  89614. delete unTreatedUniforms[unif];
  89615. }
  89616. else {
  89617. uniforms.push(unif);
  89618. }
  89619. }
  89620. else if (uniformParameter.type === GLTF1.EParameterType.SAMPLER_2D) {
  89621. samplers.push(unif);
  89622. }
  89623. else {
  89624. uniforms.push(unif);
  89625. }
  89626. }
  89627. for (var attr in technique.attributes) {
  89628. var attribute = technique.attributes[attr];
  89629. var attributeParameter = technique.parameters[attribute];
  89630. if (attributeParameter.semantic) {
  89631. attributes.push(getAttribute(attributeParameter));
  89632. }
  89633. }
  89634. // Configure vertex shader
  89635. while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
  89636. var tokenType = vertexTokenizer.currentToken;
  89637. if (tokenType !== ETokenType.IDENTIFIER) {
  89638. newVertexShader += vertexTokenizer.currentString;
  89639. continue;
  89640. }
  89641. var foundAttribute = false;
  89642. for (var attr in technique.attributes) {
  89643. var attribute = technique.attributes[attr];
  89644. var attributeParameter = technique.parameters[attribute];
  89645. if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
  89646. newVertexShader += getAttribute(attributeParameter);
  89647. foundAttribute = true;
  89648. break;
  89649. }
  89650. }
  89651. if (foundAttribute) {
  89652. continue;
  89653. }
  89654. newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);
  89655. }
  89656. // Configure pixel shader
  89657. while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
  89658. var tokenType = pixelTokenizer.currentToken;
  89659. if (tokenType !== ETokenType.IDENTIFIER) {
  89660. newPixelShader += pixelTokenizer.currentString;
  89661. continue;
  89662. }
  89663. newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);
  89664. }
  89665. // Create shader material
  89666. var shaderPath = {
  89667. vertex: program.vertexShader + id,
  89668. fragment: program.fragmentShader + id
  89669. };
  89670. var options = {
  89671. attributes: attributes,
  89672. uniforms: uniforms,
  89673. samplers: samplers,
  89674. needAlphaBlending: states && states.enable && states.enable.indexOf(3042) !== -1
  89675. };
  89676. BABYLON.Effect.ShadersStore[program.vertexShader + id + "VertexShader"] = newVertexShader;
  89677. BABYLON.Effect.ShadersStore[program.fragmentShader + id + "PixelShader"] = newPixelShader;
  89678. var shaderMaterial = new BABYLON.ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);
  89679. shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);
  89680. shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);
  89681. shaderMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  89682. if (states && states.functions) {
  89683. var functions = states.functions;
  89684. if (functions.cullFace && functions.cullFace[0] !== GLTF1.ECullingType.BACK) {
  89685. shaderMaterial.backFaceCulling = false;
  89686. }
  89687. var blendFunc = functions.blendFuncSeparate;
  89688. if (blendFunc) {
  89689. if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE_MINUS_SRC_ALPHA && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  89690. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  89691. }
  89692. else if (blendFunc[0] === GLTF1.EBlendingFunction.ONE && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  89693. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  89694. }
  89695. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  89696. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ADD;
  89697. }
  89698. else if (blendFunc[0] === GLTF1.EBlendingFunction.ZERO && blendFunc[1] === GLTF1.EBlendingFunction.ONE_MINUS_SRC_COLOR && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  89699. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_SUBTRACT;
  89700. }
  89701. else if (blendFunc[0] === GLTF1.EBlendingFunction.DST_COLOR && blendFunc[1] === GLTF1.EBlendingFunction.ZERO && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  89702. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MULTIPLY;
  89703. }
  89704. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE_MINUS_SRC_COLOR && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  89705. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MAXIMIZED;
  89706. }
  89707. }
  89708. }
  89709. };
  89710. return GLTFLoaderBase;
  89711. }());
  89712. GLTF1.GLTFLoaderBase = GLTFLoaderBase;
  89713. /**
  89714. * glTF V1 Loader
  89715. */
  89716. var GLTFLoader = /** @class */ (function () {
  89717. function GLTFLoader() {
  89718. // #region Stubs for IGLTFLoader interface
  89719. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  89720. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  89721. this.compileMaterials = false;
  89722. this.useClipPlane = false;
  89723. this.compileShadowGenerators = false;
  89724. this.onDisposeObservable = new BABYLON.Observable();
  89725. this.onMeshLoadedObservable = new BABYLON.Observable();
  89726. this.onTextureLoadedObservable = new BABYLON.Observable();
  89727. this.onMaterialLoadedObservable = new BABYLON.Observable();
  89728. this.onCompleteObservable = new BABYLON.Observable();
  89729. this.onExtensionLoadedObservable = new BABYLON.Observable();
  89730. this.state = null;
  89731. }
  89732. GLTFLoader.RegisterExtension = function (extension) {
  89733. if (GLTFLoader.Extensions[extension.name]) {
  89734. BABYLON.Tools.Error("Tool with the same name \"" + extension.name + "\" already exists");
  89735. return;
  89736. }
  89737. GLTFLoader.Extensions[extension.name] = extension;
  89738. };
  89739. GLTFLoader.prototype.dispose = function () { };
  89740. // #endregion
  89741. GLTFLoader.prototype._importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  89742. var _this = this;
  89743. scene.useRightHandedSystem = true;
  89744. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  89745. gltfRuntime.importOnlyMeshes = true;
  89746. if (meshesNames === "") {
  89747. gltfRuntime.importMeshesNames = [];
  89748. }
  89749. else if (typeof meshesNames === "string") {
  89750. gltfRuntime.importMeshesNames = [meshesNames];
  89751. }
  89752. else if (meshesNames && !(meshesNames instanceof Array)) {
  89753. gltfRuntime.importMeshesNames = [meshesNames];
  89754. }
  89755. else {
  89756. gltfRuntime.importMeshesNames = [];
  89757. BABYLON.Tools.Warn("Argument meshesNames must be of type string or string[]");
  89758. }
  89759. // Create nodes
  89760. _this._createNodes(gltfRuntime);
  89761. var meshes = new Array();
  89762. var skeletons = new Array();
  89763. // Fill arrays of meshes and skeletons
  89764. for (var nde in gltfRuntime.nodes) {
  89765. var node = gltfRuntime.nodes[nde];
  89766. if (node.babylonNode instanceof BABYLON.AbstractMesh) {
  89767. meshes.push(node.babylonNode);
  89768. }
  89769. }
  89770. for (var skl in gltfRuntime.skins) {
  89771. var skin = gltfRuntime.skins[skl];
  89772. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  89773. skeletons.push(skin.babylonSkeleton);
  89774. }
  89775. }
  89776. // Load buffers, shaders, materials, etc.
  89777. _this._loadBuffersAsync(gltfRuntime, function () {
  89778. _this._loadShadersAsync(gltfRuntime, function () {
  89779. importMaterials(gltfRuntime);
  89780. postLoad(gltfRuntime);
  89781. if (!BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  89782. onSuccess(meshes, [], skeletons);
  89783. }
  89784. });
  89785. }, onProgress);
  89786. if (BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  89787. onSuccess(meshes, [], skeletons);
  89788. }
  89789. }, onError);
  89790. return true;
  89791. };
  89792. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  89793. var _this = this;
  89794. return new Promise(function (resolve, reject) {
  89795. _this._importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  89796. resolve({
  89797. meshes: meshes,
  89798. particleSystems: particleSystems,
  89799. skeletons: skeletons
  89800. });
  89801. }, onProgress, function (message) {
  89802. reject(new Error(message));
  89803. });
  89804. });
  89805. };
  89806. GLTFLoader.prototype._loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  89807. var _this = this;
  89808. scene.useRightHandedSystem = true;
  89809. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  89810. // Load runtime extensios
  89811. GLTF1.GLTFLoaderExtension.LoadRuntimeExtensionsAsync(gltfRuntime, function () {
  89812. // Create nodes
  89813. _this._createNodes(gltfRuntime);
  89814. // Load buffers, shaders, materials, etc.
  89815. _this._loadBuffersAsync(gltfRuntime, function () {
  89816. _this._loadShadersAsync(gltfRuntime, function () {
  89817. importMaterials(gltfRuntime);
  89818. postLoad(gltfRuntime);
  89819. if (!BABYLON.GLTFFileLoader.IncrementalLoading) {
  89820. onSuccess();
  89821. }
  89822. });
  89823. });
  89824. if (BABYLON.GLTFFileLoader.IncrementalLoading) {
  89825. onSuccess();
  89826. }
  89827. }, onError);
  89828. }, onError);
  89829. };
  89830. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  89831. var _this = this;
  89832. return new Promise(function (resolve, reject) {
  89833. _this._loadAsync(scene, data, rootUrl, function () {
  89834. resolve();
  89835. }, onProgress, function (message) {
  89836. reject(new Error(message));
  89837. });
  89838. });
  89839. };
  89840. GLTFLoader.prototype._loadShadersAsync = function (gltfRuntime, onload) {
  89841. var hasShaders = false;
  89842. var processShader = function (sha, shader) {
  89843. GLTF1.GLTFLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, function (shaderString) {
  89844. gltfRuntime.loadedShaderCount++;
  89845. if (shaderString) {
  89846. BABYLON.Effect.ShadersStore[sha + (shader.type === GLTF1.EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = shaderString;
  89847. }
  89848. if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {
  89849. onload();
  89850. }
  89851. }, function () {
  89852. BABYLON.Tools.Error("Error when loading shader program named " + sha + " located at " + shader.uri);
  89853. });
  89854. };
  89855. for (var sha in gltfRuntime.shaders) {
  89856. hasShaders = true;
  89857. var shader = gltfRuntime.shaders[sha];
  89858. if (shader) {
  89859. processShader.bind(this, sha, shader)();
  89860. }
  89861. else {
  89862. BABYLON.Tools.Error("No shader named: " + sha);
  89863. }
  89864. }
  89865. if (!hasShaders) {
  89866. onload();
  89867. }
  89868. };
  89869. ;
  89870. GLTFLoader.prototype._loadBuffersAsync = function (gltfRuntime, onLoad, onProgress) {
  89871. var hasBuffers = false;
  89872. var processBuffer = function (buf, buffer) {
  89873. GLTF1.GLTFLoaderExtension.LoadBufferAsync(gltfRuntime, buf, function (bufferView) {
  89874. gltfRuntime.loadedBufferCount++;
  89875. if (bufferView) {
  89876. if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {
  89877. BABYLON.Tools.Error("Buffer named " + buf + " is length " + bufferView.byteLength + ". Expected: " + buffer.byteLength); // Improve error message
  89878. }
  89879. gltfRuntime.loadedBufferViews[buf] = bufferView;
  89880. }
  89881. if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {
  89882. onLoad();
  89883. }
  89884. }, function () {
  89885. BABYLON.Tools.Error("Error when loading buffer named " + buf + " located at " + buffer.uri);
  89886. });
  89887. };
  89888. for (var buf in gltfRuntime.buffers) {
  89889. hasBuffers = true;
  89890. var buffer = gltfRuntime.buffers[buf];
  89891. if (buffer) {
  89892. processBuffer.bind(this, buf, buffer)();
  89893. }
  89894. else {
  89895. BABYLON.Tools.Error("No buffer named: " + buf);
  89896. }
  89897. }
  89898. if (!hasBuffers) {
  89899. onLoad();
  89900. }
  89901. };
  89902. GLTFLoader.prototype._createNodes = function (gltfRuntime) {
  89903. var currentScene = gltfRuntime.currentScene;
  89904. if (currentScene) {
  89905. // Only one scene even if multiple scenes are defined
  89906. for (var i = 0; i < currentScene.nodes.length; i++) {
  89907. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  89908. }
  89909. }
  89910. else {
  89911. // Load all scenes
  89912. for (var thing in gltfRuntime.scenes) {
  89913. currentScene = gltfRuntime.scenes[thing];
  89914. for (var i = 0; i < currentScene.nodes.length; i++) {
  89915. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  89916. }
  89917. }
  89918. }
  89919. };
  89920. GLTFLoader.Extensions = {};
  89921. return GLTFLoader;
  89922. }());
  89923. GLTF1.GLTFLoader = GLTFLoader;
  89924. ;
  89925. BABYLON.GLTFFileLoader.CreateGLTFLoaderV1 = function () { return new GLTFLoader(); };
  89926. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  89927. })(BABYLON || (BABYLON = {}));
  89928. //# sourceMappingURL=babylon.glTFLoader.js.map
  89929. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  89930. var BABYLON;
  89931. (function (BABYLON) {
  89932. var GLTF1;
  89933. (function (GLTF1) {
  89934. /**
  89935. * Utils functions for GLTF
  89936. */
  89937. var GLTFUtils = /** @class */ (function () {
  89938. function GLTFUtils() {
  89939. }
  89940. /**
  89941. * Sets the given "parameter" matrix
  89942. * @param scene: the {BABYLON.Scene} object
  89943. * @param source: the source node where to pick the matrix
  89944. * @param parameter: the GLTF technique parameter
  89945. * @param uniformName: the name of the shader's uniform
  89946. * @param shaderMaterial: the shader material
  89947. */
  89948. GLTFUtils.SetMatrix = function (scene, source, parameter, uniformName, shaderMaterial) {
  89949. var mat = null;
  89950. if (parameter.semantic === "MODEL") {
  89951. mat = source.getWorldMatrix();
  89952. }
  89953. else if (parameter.semantic === "PROJECTION") {
  89954. mat = scene.getProjectionMatrix();
  89955. }
  89956. else if (parameter.semantic === "VIEW") {
  89957. mat = scene.getViewMatrix();
  89958. }
  89959. else if (parameter.semantic === "MODELVIEWINVERSETRANSPOSE") {
  89960. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().multiply(scene.getViewMatrix()).invert());
  89961. }
  89962. else if (parameter.semantic === "MODELVIEW") {
  89963. mat = source.getWorldMatrix().multiply(scene.getViewMatrix());
  89964. }
  89965. else if (parameter.semantic === "MODELVIEWPROJECTION") {
  89966. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix());
  89967. }
  89968. else if (parameter.semantic === "MODELINVERSE") {
  89969. mat = source.getWorldMatrix().invert();
  89970. }
  89971. else if (parameter.semantic === "VIEWINVERSE") {
  89972. mat = scene.getViewMatrix().invert();
  89973. }
  89974. else if (parameter.semantic === "PROJECTIONINVERSE") {
  89975. mat = scene.getProjectionMatrix().invert();
  89976. }
  89977. else if (parameter.semantic === "MODELVIEWINVERSE") {
  89978. mat = source.getWorldMatrix().multiply(scene.getViewMatrix()).invert();
  89979. }
  89980. else if (parameter.semantic === "MODELVIEWPROJECTIONINVERSE") {
  89981. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()).invert();
  89982. }
  89983. else if (parameter.semantic === "MODELINVERSETRANSPOSE") {
  89984. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().invert());
  89985. }
  89986. else {
  89987. debugger;
  89988. }
  89989. if (mat) {
  89990. switch (parameter.type) {
  89991. case GLTF1.EParameterType.FLOAT_MAT2:
  89992. shaderMaterial.setMatrix2x2(uniformName, BABYLON.Matrix.GetAsMatrix2x2(mat));
  89993. break;
  89994. case GLTF1.EParameterType.FLOAT_MAT3:
  89995. shaderMaterial.setMatrix3x3(uniformName, BABYLON.Matrix.GetAsMatrix3x3(mat));
  89996. break;
  89997. case GLTF1.EParameterType.FLOAT_MAT4:
  89998. shaderMaterial.setMatrix(uniformName, mat);
  89999. break;
  90000. default: break;
  90001. }
  90002. }
  90003. };
  90004. /**
  90005. * Sets the given "parameter" matrix
  90006. * @param shaderMaterial: the shader material
  90007. * @param uniform: the name of the shader's uniform
  90008. * @param value: the value of the uniform
  90009. * @param type: the uniform's type (EParameterType FLOAT, VEC2, VEC3 or VEC4)
  90010. */
  90011. GLTFUtils.SetUniform = function (shaderMaterial, uniform, value, type) {
  90012. switch (type) {
  90013. case GLTF1.EParameterType.FLOAT:
  90014. shaderMaterial.setFloat(uniform, value);
  90015. return true;
  90016. case GLTF1.EParameterType.FLOAT_VEC2:
  90017. shaderMaterial.setVector2(uniform, BABYLON.Vector2.FromArray(value));
  90018. return true;
  90019. case GLTF1.EParameterType.FLOAT_VEC3:
  90020. shaderMaterial.setVector3(uniform, BABYLON.Vector3.FromArray(value));
  90021. return true;
  90022. case GLTF1.EParameterType.FLOAT_VEC4:
  90023. shaderMaterial.setVector4(uniform, BABYLON.Vector4.FromArray(value));
  90024. return true;
  90025. default: return false;
  90026. }
  90027. };
  90028. /**
  90029. * Returns the wrap mode of the texture
  90030. * @param mode: the mode value
  90031. */
  90032. GLTFUtils.GetWrapMode = function (mode) {
  90033. switch (mode) {
  90034. case GLTF1.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  90035. case GLTF1.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  90036. case GLTF1.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  90037. default: return BABYLON.Texture.WRAP_ADDRESSMODE;
  90038. }
  90039. };
  90040. /**
  90041. * Returns the byte stride giving an accessor
  90042. * @param accessor: the GLTF accessor objet
  90043. */
  90044. GLTFUtils.GetByteStrideFromType = function (accessor) {
  90045. // Needs this function since "byteStride" isn't requiered in glTF format
  90046. var type = accessor.type;
  90047. switch (type) {
  90048. case "VEC2": return 2;
  90049. case "VEC3": return 3;
  90050. case "VEC4": return 4;
  90051. case "MAT2": return 4;
  90052. case "MAT3": return 9;
  90053. case "MAT4": return 16;
  90054. default: return 1;
  90055. }
  90056. };
  90057. /**
  90058. * Returns the texture filter mode giving a mode value
  90059. * @param mode: the filter mode value
  90060. */
  90061. GLTFUtils.GetTextureFilterMode = function (mode) {
  90062. switch (mode) {
  90063. case GLTF1.ETextureFilterType.LINEAR:
  90064. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST:
  90065. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  90066. case GLTF1.ETextureFilterType.NEAREST:
  90067. case GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_SAMPLINGMODE;
  90068. default: return BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  90069. }
  90070. };
  90071. GLTFUtils.GetBufferFromBufferView = function (gltfRuntime, bufferView, byteOffset, byteLength, componentType) {
  90072. var byteOffset = bufferView.byteOffset + byteOffset;
  90073. var loadedBufferView = gltfRuntime.loadedBufferViews[bufferView.buffer];
  90074. if (byteOffset + byteLength > loadedBufferView.byteLength) {
  90075. throw new Error("Buffer access is out of range");
  90076. }
  90077. var buffer = loadedBufferView.buffer;
  90078. byteOffset += loadedBufferView.byteOffset;
  90079. switch (componentType) {
  90080. case GLTF1.EComponentType.BYTE: return new Int8Array(buffer, byteOffset, byteLength);
  90081. case GLTF1.EComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, byteLength);
  90082. case GLTF1.EComponentType.SHORT: return new Int16Array(buffer, byteOffset, byteLength);
  90083. case GLTF1.EComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, byteLength);
  90084. default: return new Float32Array(buffer, byteOffset, byteLength);
  90085. }
  90086. };
  90087. /**
  90088. * Returns a buffer from its accessor
  90089. * @param gltfRuntime: the GLTF runtime
  90090. * @param accessor: the GLTF accessor
  90091. */
  90092. GLTFUtils.GetBufferFromAccessor = function (gltfRuntime, accessor) {
  90093. var bufferView = gltfRuntime.bufferViews[accessor.bufferView];
  90094. var byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor);
  90095. return GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, accessor.byteOffset, byteLength, accessor.componentType);
  90096. };
  90097. /**
  90098. * Decodes a buffer view into a string
  90099. * @param view: the buffer view
  90100. */
  90101. GLTFUtils.DecodeBufferToText = function (view) {
  90102. var result = "";
  90103. var length = view.byteLength;
  90104. for (var i = 0; i < length; ++i) {
  90105. result += String.fromCharCode(view[i]);
  90106. }
  90107. return result;
  90108. };
  90109. /**
  90110. * Returns the default material of gltf. Related to
  90111. * https://github.com/KhronosGroup/glTF/tree/master/specification/1.0#appendix-a-default-material
  90112. * @param scene: the Babylon.js scene
  90113. */
  90114. GLTFUtils.GetDefaultMaterial = function (scene) {
  90115. if (!GLTFUtils._DefaultMaterial) {
  90116. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialVertexShader"] = [
  90117. "precision highp float;",
  90118. "",
  90119. "uniform mat4 worldView;",
  90120. "uniform mat4 projection;",
  90121. "",
  90122. "attribute vec3 position;",
  90123. "",
  90124. "void main(void)",
  90125. "{",
  90126. " gl_Position = projection * worldView * vec4(position, 1.0);",
  90127. "}"
  90128. ].join("\n");
  90129. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialPixelShader"] = [
  90130. "precision highp float;",
  90131. "",
  90132. "uniform vec4 u_emission;",
  90133. "",
  90134. "void main(void)",
  90135. "{",
  90136. " gl_FragColor = u_emission;",
  90137. "}"
  90138. ].join("\n");
  90139. var shaderPath = {
  90140. vertex: "GLTFDefaultMaterial",
  90141. fragment: "GLTFDefaultMaterial"
  90142. };
  90143. var options = {
  90144. attributes: ["position"],
  90145. uniforms: ["worldView", "projection", "u_emission"],
  90146. samplers: new Array(),
  90147. needAlphaBlending: false
  90148. };
  90149. GLTFUtils._DefaultMaterial = new BABYLON.ShaderMaterial("GLTFDefaultMaterial", scene, shaderPath, options);
  90150. GLTFUtils._DefaultMaterial.setColor4("u_emission", new BABYLON.Color4(0.5, 0.5, 0.5, 1.0));
  90151. }
  90152. return GLTFUtils._DefaultMaterial;
  90153. };
  90154. // The GLTF default material
  90155. GLTFUtils._DefaultMaterial = null;
  90156. return GLTFUtils;
  90157. }());
  90158. GLTF1.GLTFUtils = GLTFUtils;
  90159. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  90160. })(BABYLON || (BABYLON = {}));
  90161. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  90162. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  90163. var BABYLON;
  90164. (function (BABYLON) {
  90165. var GLTF1;
  90166. (function (GLTF1) {
  90167. var GLTFLoaderExtension = /** @class */ (function () {
  90168. function GLTFLoaderExtension(name) {
  90169. this._name = name;
  90170. }
  90171. Object.defineProperty(GLTFLoaderExtension.prototype, "name", {
  90172. get: function () {
  90173. return this._name;
  90174. },
  90175. enumerable: true,
  90176. configurable: true
  90177. });
  90178. /**
  90179. * Defines an override for loading the runtime
  90180. * Return true to stop further extensions from loading the runtime
  90181. */
  90182. GLTFLoaderExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  90183. return false;
  90184. };
  90185. /**
  90186. * Defines an onverride for creating gltf runtime
  90187. * Return true to stop further extensions from creating the runtime
  90188. */
  90189. GLTFLoaderExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  90190. return false;
  90191. };
  90192. /**
  90193. * Defines an override for loading buffers
  90194. * Return true to stop further extensions from loading this buffer
  90195. */
  90196. GLTFLoaderExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  90197. return false;
  90198. };
  90199. /**
  90200. * Defines an override for loading texture buffers
  90201. * Return true to stop further extensions from loading this texture data
  90202. */
  90203. GLTFLoaderExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  90204. return false;
  90205. };
  90206. /**
  90207. * Defines an override for creating textures
  90208. * Return true to stop further extensions from loading this texture
  90209. */
  90210. GLTFLoaderExtension.prototype.createTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  90211. return false;
  90212. };
  90213. /**
  90214. * Defines an override for loading shader strings
  90215. * Return true to stop further extensions from loading this shader data
  90216. */
  90217. GLTFLoaderExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  90218. return false;
  90219. };
  90220. /**
  90221. * Defines an override for loading materials
  90222. * Return true to stop further extensions from loading this material
  90223. */
  90224. GLTFLoaderExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  90225. return false;
  90226. };
  90227. // ---------
  90228. // Utilities
  90229. // ---------
  90230. GLTFLoaderExtension.LoadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  90231. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  90232. return loaderExtension.loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError);
  90233. }, function () {
  90234. setTimeout(function () {
  90235. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  90236. });
  90237. });
  90238. };
  90239. GLTFLoaderExtension.LoadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  90240. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  90241. return loaderExtension.loadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError);
  90242. }, function () {
  90243. setTimeout(function () {
  90244. onSuccess();
  90245. });
  90246. });
  90247. };
  90248. GLTFLoaderExtension.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  90249. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  90250. return loaderExtension.loadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  90251. }, function () {
  90252. GLTF1.GLTFLoaderBase.LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  90253. });
  90254. };
  90255. GLTFLoaderExtension.LoadTextureAsync = function (gltfRuntime, id, onSuccess, onError) {
  90256. GLTFLoaderExtension.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) { return GLTFLoaderExtension.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError); }, onError);
  90257. };
  90258. GLTFLoaderExtension.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  90259. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  90260. return loaderExtension.loadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  90261. }, function () {
  90262. GLTF1.GLTFLoaderBase.LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  90263. });
  90264. };
  90265. GLTFLoaderExtension.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  90266. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  90267. return loaderExtension.loadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  90268. }, function () {
  90269. GLTF1.GLTFLoaderBase.LoadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  90270. });
  90271. };
  90272. GLTFLoaderExtension.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  90273. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  90274. return loaderExtension.loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  90275. }, function () {
  90276. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  90277. });
  90278. };
  90279. GLTFLoaderExtension.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  90280. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  90281. return loaderExtension.createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  90282. }, function () {
  90283. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  90284. });
  90285. };
  90286. GLTFLoaderExtension.ApplyExtensions = function (func, defaultFunc) {
  90287. for (var extensionName in GLTF1.GLTFLoader.Extensions) {
  90288. var loaderExtension = GLTF1.GLTFLoader.Extensions[extensionName];
  90289. if (func(loaderExtension)) {
  90290. return;
  90291. }
  90292. }
  90293. defaultFunc();
  90294. };
  90295. return GLTFLoaderExtension;
  90296. }());
  90297. GLTF1.GLTFLoaderExtension = GLTFLoaderExtension;
  90298. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  90299. })(BABYLON || (BABYLON = {}));
  90300. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  90301. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  90302. var BABYLON;
  90303. (function (BABYLON) {
  90304. var GLTF1;
  90305. (function (GLTF1) {
  90306. var BinaryExtensionBufferName = "binary_glTF";
  90307. ;
  90308. ;
  90309. var GLTFBinaryExtension = /** @class */ (function (_super) {
  90310. __extends(GLTFBinaryExtension, _super);
  90311. function GLTFBinaryExtension() {
  90312. return _super.call(this, "KHR_binary_glTF") || this;
  90313. }
  90314. GLTFBinaryExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  90315. var extensionsUsed = data.json.extensionsUsed;
  90316. if (!extensionsUsed || extensionsUsed.indexOf(this.name) === -1 || !data.bin) {
  90317. return false;
  90318. }
  90319. this._bin = data.bin;
  90320. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  90321. return true;
  90322. };
  90323. GLTFBinaryExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  90324. if (gltfRuntime.extensionsUsed.indexOf(this.name) === -1) {
  90325. return false;
  90326. }
  90327. if (id !== BinaryExtensionBufferName) {
  90328. return false;
  90329. }
  90330. onSuccess(this._bin);
  90331. return true;
  90332. };
  90333. GLTFBinaryExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  90334. var texture = gltfRuntime.textures[id];
  90335. var source = gltfRuntime.images[texture.source];
  90336. if (!source.extensions || !(this.name in source.extensions)) {
  90337. return false;
  90338. }
  90339. var sourceExt = source.extensions[this.name];
  90340. var bufferView = gltfRuntime.bufferViews[sourceExt.bufferView];
  90341. var buffer = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  90342. onSuccess(buffer);
  90343. return true;
  90344. };
  90345. GLTFBinaryExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  90346. var shader = gltfRuntime.shaders[id];
  90347. if (!shader.extensions || !(this.name in shader.extensions)) {
  90348. return false;
  90349. }
  90350. var binaryExtensionShader = shader.extensions[this.name];
  90351. var bufferView = gltfRuntime.bufferViews[binaryExtensionShader.bufferView];
  90352. var shaderBytes = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  90353. setTimeout(function () {
  90354. var shaderString = GLTF1.GLTFUtils.DecodeBufferToText(shaderBytes);
  90355. onSuccess(shaderString);
  90356. });
  90357. return true;
  90358. };
  90359. return GLTFBinaryExtension;
  90360. }(GLTF1.GLTFLoaderExtension));
  90361. GLTF1.GLTFBinaryExtension = GLTFBinaryExtension;
  90362. GLTF1.GLTFLoader.RegisterExtension(new GLTFBinaryExtension());
  90363. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  90364. })(BABYLON || (BABYLON = {}));
  90365. //# sourceMappingURL=babylon.glTFBinaryExtension.js.map
  90366. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  90367. var BABYLON;
  90368. (function (BABYLON) {
  90369. var GLTF1;
  90370. (function (GLTF1) {
  90371. ;
  90372. ;
  90373. ;
  90374. var GLTFMaterialsCommonExtension = /** @class */ (function (_super) {
  90375. __extends(GLTFMaterialsCommonExtension, _super);
  90376. function GLTFMaterialsCommonExtension() {
  90377. return _super.call(this, "KHR_materials_common") || this;
  90378. }
  90379. GLTFMaterialsCommonExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  90380. if (!gltfRuntime.extensions)
  90381. return false;
  90382. var extension = gltfRuntime.extensions[this.name];
  90383. if (!extension)
  90384. return false;
  90385. // Create lights
  90386. var lights = extension.lights;
  90387. if (lights) {
  90388. for (var thing in lights) {
  90389. var light = lights[thing];
  90390. switch (light.type) {
  90391. case "ambient":
  90392. var ambientLight = new BABYLON.HemisphericLight(light.name, new BABYLON.Vector3(0, 1, 0), gltfRuntime.scene);
  90393. var ambient = light.ambient;
  90394. if (ambient) {
  90395. ambientLight.diffuse = BABYLON.Color3.FromArray(ambient.color || [1, 1, 1]);
  90396. }
  90397. break;
  90398. case "point":
  90399. var pointLight = new BABYLON.PointLight(light.name, new BABYLON.Vector3(10, 10, 10), gltfRuntime.scene);
  90400. var point = light.point;
  90401. if (point) {
  90402. pointLight.diffuse = BABYLON.Color3.FromArray(point.color || [1, 1, 1]);
  90403. }
  90404. break;
  90405. case "directional":
  90406. var dirLight = new BABYLON.DirectionalLight(light.name, new BABYLON.Vector3(0, -1, 0), gltfRuntime.scene);
  90407. var directional = light.directional;
  90408. if (directional) {
  90409. dirLight.diffuse = BABYLON.Color3.FromArray(directional.color || [1, 1, 1]);
  90410. }
  90411. break;
  90412. case "spot":
  90413. var spot = light.spot;
  90414. if (spot) {
  90415. var spotLight = new BABYLON.SpotLight(light.name, new BABYLON.Vector3(0, 10, 0), new BABYLON.Vector3(0, -1, 0), spot.fallOffAngle || Math.PI, spot.fallOffExponent || 0.0, gltfRuntime.scene);
  90416. spotLight.diffuse = BABYLON.Color3.FromArray(spot.color || [1, 1, 1]);
  90417. }
  90418. break;
  90419. default:
  90420. BABYLON.Tools.Warn("GLTF Material Common extension: light type \"" + light.type + "\” not supported");
  90421. break;
  90422. }
  90423. }
  90424. }
  90425. return false;
  90426. };
  90427. GLTFMaterialsCommonExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  90428. var material = gltfRuntime.materials[id];
  90429. if (!material || !material.extensions)
  90430. return false;
  90431. var extension = material.extensions[this.name];
  90432. if (!extension)
  90433. return false;
  90434. var standardMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  90435. standardMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  90436. if (extension.technique === "CONSTANT") {
  90437. standardMaterial.disableLighting = true;
  90438. }
  90439. standardMaterial.backFaceCulling = extension.doubleSided === undefined ? false : !extension.doubleSided;
  90440. standardMaterial.alpha = extension.values.transparency === undefined ? 1.0 : extension.values.transparency;
  90441. standardMaterial.specularPower = extension.values.shininess === undefined ? 0.0 : extension.values.shininess;
  90442. // Ambient
  90443. if (typeof extension.values.ambient === "string") {
  90444. this._loadTexture(gltfRuntime, extension.values.ambient, standardMaterial, "ambientTexture", onError);
  90445. }
  90446. else {
  90447. standardMaterial.ambientColor = BABYLON.Color3.FromArray(extension.values.ambient || [0, 0, 0]);
  90448. }
  90449. // Diffuse
  90450. if (typeof extension.values.diffuse === "string") {
  90451. this._loadTexture(gltfRuntime, extension.values.diffuse, standardMaterial, "diffuseTexture", onError);
  90452. }
  90453. else {
  90454. standardMaterial.diffuseColor = BABYLON.Color3.FromArray(extension.values.diffuse || [0, 0, 0]);
  90455. }
  90456. // Emission
  90457. if (typeof extension.values.emission === "string") {
  90458. this._loadTexture(gltfRuntime, extension.values.emission, standardMaterial, "emissiveTexture", onError);
  90459. }
  90460. else {
  90461. standardMaterial.emissiveColor = BABYLON.Color3.FromArray(extension.values.emission || [0, 0, 0]);
  90462. }
  90463. // Specular
  90464. if (typeof extension.values.specular === "string") {
  90465. this._loadTexture(gltfRuntime, extension.values.specular, standardMaterial, "specularTexture", onError);
  90466. }
  90467. else {
  90468. standardMaterial.specularColor = BABYLON.Color3.FromArray(extension.values.specular || [0, 0, 0]);
  90469. }
  90470. return true;
  90471. };
  90472. GLTFMaterialsCommonExtension.prototype._loadTexture = function (gltfRuntime, id, material, propertyPath, onError) {
  90473. // Create buffer from texture url
  90474. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  90475. // Create texture from buffer
  90476. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, function (texture) { return material[propertyPath] = texture; }, onError);
  90477. }, onError);
  90478. };
  90479. return GLTFMaterialsCommonExtension;
  90480. }(GLTF1.GLTFLoaderExtension));
  90481. GLTF1.GLTFMaterialsCommonExtension = GLTFMaterialsCommonExtension;
  90482. GLTF1.GLTFLoader.RegisterExtension(new GLTFMaterialsCommonExtension());
  90483. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  90484. })(BABYLON || (BABYLON = {}));
  90485. //# sourceMappingURL=babylon.glTFMaterialsCommonExtension.js.map
  90486. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  90487. var BABYLON;
  90488. (function (BABYLON) {
  90489. var GLTF2;
  90490. (function (GLTF2) {
  90491. var ArrayItem = /** @class */ (function () {
  90492. function ArrayItem() {
  90493. }
  90494. ArrayItem.Assign = function (values) {
  90495. if (values) {
  90496. for (var index = 0; index < values.length; index++) {
  90497. values[index]._index = index;
  90498. }
  90499. }
  90500. };
  90501. return ArrayItem;
  90502. }());
  90503. GLTF2.ArrayItem = ArrayItem;
  90504. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  90505. })(BABYLON || (BABYLON = {}));
  90506. //# sourceMappingURL=babylon.glTFLoaderUtilities.js.map
  90507. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  90508. /// <reference path="../../../../dist/babylon.glTF2Interface.d.ts"/>
  90509. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  90510. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  90511. var BABYLON;
  90512. (function (BABYLON) {
  90513. var GLTF2;
  90514. (function (GLTF2) {
  90515. var GLTFLoader = /** @class */ (function () {
  90516. function GLTFLoader() {
  90517. this._completePromises = new Array();
  90518. this._disposed = false;
  90519. this._state = null;
  90520. this._extensions = {};
  90521. this._defaultSampler = {};
  90522. this._requests = new Array();
  90523. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  90524. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  90525. this.compileMaterials = false;
  90526. this.useClipPlane = false;
  90527. this.compileShadowGenerators = false;
  90528. this.onDisposeObservable = new BABYLON.Observable();
  90529. this.onMeshLoadedObservable = new BABYLON.Observable();
  90530. this.onTextureLoadedObservable = new BABYLON.Observable();
  90531. this.onMaterialLoadedObservable = new BABYLON.Observable();
  90532. this.onExtensionLoadedObservable = new BABYLON.Observable();
  90533. this.onCompleteObservable = new BABYLON.Observable();
  90534. }
  90535. GLTFLoader._Register = function (name, factory) {
  90536. if (GLTFLoader._Factories[name]) {
  90537. BABYLON.Tools.Error("Extension with the name '" + name + "' already exists");
  90538. return;
  90539. }
  90540. GLTFLoader._Factories[name] = factory;
  90541. // Keep the order of registration so that extensions registered first are called first.
  90542. GLTFLoader._Names.push(name);
  90543. };
  90544. Object.defineProperty(GLTFLoader.prototype, "state", {
  90545. get: function () {
  90546. return this._state;
  90547. },
  90548. enumerable: true,
  90549. configurable: true
  90550. });
  90551. GLTFLoader.prototype.dispose = function () {
  90552. if (this._disposed) {
  90553. return;
  90554. }
  90555. this._disposed = true;
  90556. this._abortRequests();
  90557. this._releaseResources();
  90558. this.onDisposeObservable.notifyObservers(this);
  90559. };
  90560. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  90561. var _this = this;
  90562. return Promise.resolve().then(function () {
  90563. var nodes = null;
  90564. if (meshesNames) {
  90565. var nodeMap_1 = {};
  90566. if (_this._gltf.nodes) {
  90567. for (var _i = 0, _a = _this._gltf.nodes; _i < _a.length; _i++) {
  90568. var node = _a[_i];
  90569. if (node.name) {
  90570. nodeMap_1[node.name] = node;
  90571. }
  90572. }
  90573. }
  90574. var names = (meshesNames instanceof Array) ? meshesNames : [meshesNames];
  90575. nodes = names.map(function (name) {
  90576. var node = nodeMap_1[name];
  90577. if (!node) {
  90578. throw new Error("Failed to find node " + name);
  90579. }
  90580. return node;
  90581. });
  90582. }
  90583. return _this._loadAsync(nodes, scene, data, rootUrl, onProgress).then(function () {
  90584. return {
  90585. meshes: _this._getMeshes(),
  90586. particleSystems: [],
  90587. skeletons: _this._getSkeletons(),
  90588. };
  90589. });
  90590. });
  90591. };
  90592. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  90593. return this._loadAsync(null, scene, data, rootUrl, onProgress);
  90594. };
  90595. GLTFLoader.prototype._loadAsync = function (nodes, scene, data, rootUrl, onProgress) {
  90596. var _this = this;
  90597. return Promise.resolve().then(function () {
  90598. for (var _i = 0, _a = GLTFLoader._Names; _i < _a.length; _i++) {
  90599. var name_1 = _a[_i];
  90600. var extension = GLTFLoader._Factories[name_1](_this);
  90601. _this._extensions[name_1] = extension;
  90602. _this.onExtensionLoadedObservable.notifyObservers(extension);
  90603. }
  90604. _this._babylonScene = scene;
  90605. _this._rootUrl = rootUrl;
  90606. _this._progressCallback = onProgress;
  90607. _this._state = BABYLON.GLTFLoaderState.Loading;
  90608. _this._loadData(data);
  90609. var promises = new Array();
  90610. if (nodes) {
  90611. promises.push(_this._loadNodesAsync(nodes));
  90612. }
  90613. else {
  90614. var scene_1 = GLTFLoader._GetProperty("#/scene", _this._gltf.scenes, _this._gltf.scene || 0);
  90615. promises.push(_this._loadSceneAsync("#/scenes/" + scene_1._index, scene_1));
  90616. }
  90617. if (_this.compileMaterials) {
  90618. promises.push(_this._compileMaterialsAsync());
  90619. }
  90620. if (_this.compileShadowGenerators) {
  90621. promises.push(_this._compileShadowGeneratorsAsync());
  90622. }
  90623. return Promise.all(promises).then(function () {
  90624. _this._state = BABYLON.GLTFLoaderState.Ready;
  90625. _this._startAnimations();
  90626. BABYLON.Tools.SetImmediate(function () {
  90627. if (!_this._disposed) {
  90628. Promise.all(_this._completePromises).then(function () {
  90629. _this._releaseResources();
  90630. _this._state = BABYLON.GLTFLoaderState.Complete;
  90631. _this.onCompleteObservable.notifyObservers(_this);
  90632. }).catch(function (error) {
  90633. BABYLON.Tools.Error("glTF Loader: " + error.message);
  90634. _this.dispose();
  90635. });
  90636. }
  90637. });
  90638. });
  90639. }).catch(function (error) {
  90640. BABYLON.Tools.Error("glTF Loader: " + error.message);
  90641. _this.dispose();
  90642. throw error;
  90643. });
  90644. };
  90645. GLTFLoader.prototype._loadData = function (data) {
  90646. this._gltf = data.json;
  90647. this._setupData();
  90648. if (data.bin) {
  90649. var buffers = this._gltf.buffers;
  90650. if (buffers && buffers[0] && !buffers[0].uri) {
  90651. var binaryBuffer = buffers[0];
  90652. if (binaryBuffer.byteLength < data.bin.byteLength - 3 || binaryBuffer.byteLength > data.bin.byteLength) {
  90653. BABYLON.Tools.Warn("Binary buffer length (" + binaryBuffer.byteLength + ") from JSON does not match chunk length (" + data.bin.byteLength + ")");
  90654. }
  90655. binaryBuffer._data = Promise.resolve(data.bin);
  90656. }
  90657. else {
  90658. BABYLON.Tools.Warn("Unexpected BIN chunk");
  90659. }
  90660. }
  90661. };
  90662. GLTFLoader.prototype._setupData = function () {
  90663. GLTF2.ArrayItem.Assign(this._gltf.accessors);
  90664. GLTF2.ArrayItem.Assign(this._gltf.animations);
  90665. GLTF2.ArrayItem.Assign(this._gltf.buffers);
  90666. GLTF2.ArrayItem.Assign(this._gltf.bufferViews);
  90667. GLTF2.ArrayItem.Assign(this._gltf.cameras);
  90668. GLTF2.ArrayItem.Assign(this._gltf.images);
  90669. GLTF2.ArrayItem.Assign(this._gltf.materials);
  90670. GLTF2.ArrayItem.Assign(this._gltf.meshes);
  90671. GLTF2.ArrayItem.Assign(this._gltf.nodes);
  90672. GLTF2.ArrayItem.Assign(this._gltf.samplers);
  90673. GLTF2.ArrayItem.Assign(this._gltf.scenes);
  90674. GLTF2.ArrayItem.Assign(this._gltf.skins);
  90675. GLTF2.ArrayItem.Assign(this._gltf.textures);
  90676. if (this._gltf.nodes) {
  90677. var nodeParents = {};
  90678. for (var _i = 0, _a = this._gltf.nodes; _i < _a.length; _i++) {
  90679. var node = _a[_i];
  90680. if (node.children) {
  90681. for (var _b = 0, _c = node.children; _b < _c.length; _b++) {
  90682. var index = _c[_b];
  90683. nodeParents[index] = node._index;
  90684. }
  90685. }
  90686. }
  90687. var rootNode = this._createRootNode();
  90688. for (var _d = 0, _e = this._gltf.nodes; _d < _e.length; _d++) {
  90689. var node = _e[_d];
  90690. var parentIndex = nodeParents[node._index];
  90691. node._parent = parentIndex === undefined ? rootNode : this._gltf.nodes[parentIndex];
  90692. }
  90693. }
  90694. };
  90695. GLTFLoader.prototype._createRootNode = function () {
  90696. this._rootBabylonMesh = new BABYLON.Mesh("__root__", this._babylonScene);
  90697. var rootNode = { _babylonMesh: this._rootBabylonMesh };
  90698. switch (this.coordinateSystemMode) {
  90699. case BABYLON.GLTFLoaderCoordinateSystemMode.AUTO: {
  90700. if (!this._babylonScene.useRightHandedSystem) {
  90701. rootNode.rotation = [0, 1, 0, 0];
  90702. rootNode.scale = [1, 1, -1];
  90703. GLTFLoader._LoadTransform(rootNode, this._rootBabylonMesh);
  90704. }
  90705. break;
  90706. }
  90707. case BABYLON.GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED: {
  90708. this._babylonScene.useRightHandedSystem = true;
  90709. break;
  90710. }
  90711. default: {
  90712. throw new Error("Invalid coordinate system mode " + this.coordinateSystemMode);
  90713. }
  90714. }
  90715. this.onMeshLoadedObservable.notifyObservers(this._rootBabylonMesh);
  90716. return rootNode;
  90717. };
  90718. GLTFLoader.prototype._loadNodesAsync = function (nodes) {
  90719. var promises = new Array();
  90720. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  90721. var node = nodes_1[_i];
  90722. promises.push(this._loadNodeAsync("#/nodes/" + node._index, node));
  90723. }
  90724. promises.push(this._loadAnimationsAsync());
  90725. return Promise.all(promises).then(function () { });
  90726. };
  90727. GLTFLoader.prototype._loadSceneAsync = function (context, scene) {
  90728. var promise = GLTF2.GLTFLoaderExtension._LoadSceneAsync(this, context, scene);
  90729. if (promise) {
  90730. return promise;
  90731. }
  90732. var promises = new Array();
  90733. for (var _i = 0, _a = scene.nodes; _i < _a.length; _i++) {
  90734. var index = _a[_i];
  90735. var node = GLTFLoader._GetProperty(context + "/nodes/" + index, this._gltf.nodes, index);
  90736. promises.push(this._loadNodeAsync("#/nodes/" + node._index, node));
  90737. }
  90738. promises.push(this._loadAnimationsAsync());
  90739. return Promise.all(promises).then(function () { });
  90740. };
  90741. GLTFLoader.prototype._getMeshes = function () {
  90742. var meshes = new Array();
  90743. // Root mesh is always first.
  90744. meshes.push(this._rootBabylonMesh);
  90745. var nodes = this._gltf.nodes;
  90746. if (nodes) {
  90747. for (var _i = 0, nodes_2 = nodes; _i < nodes_2.length; _i++) {
  90748. var node = nodes_2[_i];
  90749. if (node._babylonMesh) {
  90750. meshes.push(node._babylonMesh);
  90751. }
  90752. }
  90753. }
  90754. return meshes;
  90755. };
  90756. GLTFLoader.prototype._getSkeletons = function () {
  90757. var skeletons = new Array();
  90758. var skins = this._gltf.skins;
  90759. if (skins) {
  90760. for (var _i = 0, skins_1 = skins; _i < skins_1.length; _i++) {
  90761. var skin = skins_1[_i];
  90762. if (skin._babylonSkeleton) {
  90763. skeletons.push(skin._babylonSkeleton);
  90764. }
  90765. }
  90766. }
  90767. return skeletons;
  90768. };
  90769. GLTFLoader.prototype._startAnimations = function () {
  90770. var animations = this._gltf.animations;
  90771. if (!animations) {
  90772. return;
  90773. }
  90774. switch (this.animationStartMode) {
  90775. case BABYLON.GLTFLoaderAnimationStartMode.NONE: {
  90776. // do nothing
  90777. break;
  90778. }
  90779. case BABYLON.GLTFLoaderAnimationStartMode.FIRST: {
  90780. var animation = animations[0];
  90781. animation._babylonAnimationGroup.start(true);
  90782. break;
  90783. }
  90784. case BABYLON.GLTFLoaderAnimationStartMode.ALL: {
  90785. for (var _i = 0, animations_1 = animations; _i < animations_1.length; _i++) {
  90786. var animation = animations_1[_i];
  90787. animation._babylonAnimationGroup.start(true);
  90788. }
  90789. break;
  90790. }
  90791. default: {
  90792. BABYLON.Tools.Error("Invalid animation start mode " + this.animationStartMode);
  90793. return;
  90794. }
  90795. }
  90796. };
  90797. GLTFLoader.prototype._loadNodeAsync = function (context, node) {
  90798. var promise = GLTF2.GLTFLoaderExtension._LoadNodeAsync(this, context, node);
  90799. if (promise) {
  90800. return promise;
  90801. }
  90802. if (node._babylonMesh) {
  90803. throw new Error(context + ": Invalid recursive node hierarchy");
  90804. }
  90805. var promises = new Array();
  90806. var babylonMesh = new BABYLON.Mesh(node.name || "node" + node._index, this._babylonScene, node._parent._babylonMesh);
  90807. node._babylonMesh = babylonMesh;
  90808. node._babylonAnimationTargets = node._babylonAnimationTargets || [];
  90809. node._babylonAnimationTargets.push(babylonMesh);
  90810. GLTFLoader._LoadTransform(node, babylonMesh);
  90811. if (node.mesh != undefined) {
  90812. var mesh = GLTFLoader._GetProperty(context + "/mesh", this._gltf.meshes, node.mesh);
  90813. promises.push(this._loadMeshAsync("#/meshes/" + mesh._index, node, mesh));
  90814. }
  90815. if (node.children) {
  90816. for (var _i = 0, _a = node.children; _i < _a.length; _i++) {
  90817. var index = _a[_i];
  90818. var childNode = GLTFLoader._GetProperty(context + "/children/" + index, this._gltf.nodes, index);
  90819. promises.push(this._loadNodeAsync("#/nodes/" + index, childNode));
  90820. }
  90821. }
  90822. this.onMeshLoadedObservable.notifyObservers(babylonMesh);
  90823. return Promise.all(promises).then(function () { });
  90824. };
  90825. GLTFLoader.prototype._loadMeshAsync = function (context, node, mesh) {
  90826. // TODO: instancing
  90827. var promises = new Array();
  90828. var primitives = mesh.primitives;
  90829. if (!primitives || primitives.length === 0) {
  90830. throw new Error(context + ": Primitives are missing");
  90831. }
  90832. GLTF2.ArrayItem.Assign(primitives);
  90833. for (var _i = 0, primitives_1 = primitives; _i < primitives_1.length; _i++) {
  90834. var primitive = primitives_1[_i];
  90835. promises.push(this._loadPrimitiveAsync(context + "/primitives/" + primitive._index, node, mesh, primitive));
  90836. }
  90837. if (node.skin != undefined) {
  90838. var skin = GLTFLoader._GetProperty(context + "/skin", this._gltf.skins, node.skin);
  90839. promises.push(this._loadSkinAsync("#/skins/" + skin._index, node, mesh, skin));
  90840. }
  90841. return Promise.all(promises).then(function () {
  90842. if (node._primitiveBabylonMeshes) {
  90843. for (var _i = 0, _a = node._primitiveBabylonMeshes; _i < _a.length; _i++) {
  90844. var primitiveBabylonMesh = _a[_i];
  90845. primitiveBabylonMesh._refreshBoundingInfo(true);
  90846. }
  90847. }
  90848. });
  90849. };
  90850. GLTFLoader.prototype._loadPrimitiveAsync = function (context, node, mesh, primitive) {
  90851. var _this = this;
  90852. var promises = new Array();
  90853. var babylonMesh = new BABYLON.Mesh((mesh.name || node._babylonMesh.name) + "_" + primitive._index, this._babylonScene, node._babylonMesh);
  90854. babylonMesh.setEnabled(false);
  90855. node._primitiveBabylonMeshes = node._primitiveBabylonMeshes || [];
  90856. node._primitiveBabylonMeshes[primitive._index] = babylonMesh;
  90857. this._createMorphTargets(context, node, mesh, primitive, babylonMesh);
  90858. promises.push(this._loadVertexDataAsync(context, primitive, babylonMesh).then(function (babylonVertexData) {
  90859. new BABYLON.Geometry(babylonMesh.name, _this._babylonScene, babylonVertexData, false, babylonMesh);
  90860. return _this._loadMorphTargetsAsync(context, primitive, babylonMesh, babylonVertexData);
  90861. }));
  90862. if (primitive.material == undefined) {
  90863. babylonMesh.material = this._getDefaultMaterial();
  90864. }
  90865. else {
  90866. var material = GLTFLoader._GetProperty(context + "/material", this._gltf.materials, primitive.material);
  90867. promises.push(this._loadMaterialAsync("#/materials/" + material._index, material, babylonMesh));
  90868. }
  90869. return Promise.all(promises).then(function () {
  90870. babylonMesh.setEnabled(true);
  90871. });
  90872. };
  90873. GLTFLoader.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {
  90874. var _this = this;
  90875. var attributes = primitive.attributes;
  90876. if (!attributes) {
  90877. throw new Error(context + ": Attributes are missing");
  90878. }
  90879. if (primitive.mode && primitive.mode !== 4 /* TRIANGLES */) {
  90880. // TODO: handle other primitive modes
  90881. throw new Error(context + ": Mode " + primitive.mode + " is not currently supported");
  90882. }
  90883. var promises = new Array();
  90884. var babylonVertexData = new BABYLON.VertexData();
  90885. if (primitive.indices == undefined) {
  90886. var positionAccessorIndex = attributes["POSITION"];
  90887. if (positionAccessorIndex != undefined) {
  90888. var accessor = GLTFLoader._GetProperty(context + "/attributes/POSITION", this._gltf.accessors, positionAccessorIndex);
  90889. babylonVertexData.indices = new Uint32Array(accessor.count);
  90890. for (var i = 0; i < babylonVertexData.indices.length; i++) {
  90891. babylonVertexData.indices[i] = i;
  90892. }
  90893. }
  90894. }
  90895. else {
  90896. var indicesAccessor = GLTFLoader._GetProperty(context + "/indices", this._gltf.accessors, primitive.indices);
  90897. promises.push(this._loadAccessorAsync("#/accessors/" + indicesAccessor._index, indicesAccessor).then(function (data) {
  90898. babylonVertexData.indices = data;
  90899. }));
  90900. }
  90901. var loadAttribute = function (attribute, kind) {
  90902. if (attributes[attribute] == undefined) {
  90903. return;
  90904. }
  90905. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  90906. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  90907. babylonMesh._delayInfo.push(kind);
  90908. }
  90909. var accessor = GLTFLoader._GetProperty(context + "/attributes/" + attribute, _this._gltf.accessors, attributes[attribute]);
  90910. promises.push(_this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  90911. var attributeData = GLTFLoader._ConvertToFloat32Array(context, accessor, data);
  90912. if (attribute === "COLOR_0") {
  90913. // Assume vertex color has alpha on the mesh. The alphaMode of the material controls whether the material should use alpha or not.
  90914. babylonMesh.hasVertexAlpha = true;
  90915. if (accessor.type === "VEC3") {
  90916. attributeData = GLTFLoader._ConvertVec3ToVec4(context, attributeData);
  90917. }
  90918. }
  90919. babylonVertexData.set(attributeData, kind);
  90920. }));
  90921. };
  90922. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind);
  90923. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind);
  90924. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind);
  90925. loadAttribute("TEXCOORD_0", BABYLON.VertexBuffer.UVKind);
  90926. loadAttribute("TEXCOORD_1", BABYLON.VertexBuffer.UV2Kind);
  90927. loadAttribute("JOINTS_0", BABYLON.VertexBuffer.MatricesIndicesKind);
  90928. loadAttribute("WEIGHTS_0", BABYLON.VertexBuffer.MatricesWeightsKind);
  90929. loadAttribute("COLOR_0", BABYLON.VertexBuffer.ColorKind);
  90930. return Promise.all(promises).then(function () {
  90931. return babylonVertexData;
  90932. });
  90933. };
  90934. GLTFLoader.prototype._createMorphTargets = function (context, node, mesh, primitive, babylonMesh) {
  90935. if (!primitive.targets) {
  90936. return;
  90937. }
  90938. if (node._numMorphTargets == undefined) {
  90939. node._numMorphTargets = primitive.targets.length;
  90940. }
  90941. else if (primitive.targets.length !== node._numMorphTargets) {
  90942. throw new Error(context + ": Primitives do not have the same number of targets");
  90943. }
  90944. babylonMesh.morphTargetManager = new BABYLON.MorphTargetManager();
  90945. for (var index = 0; index < primitive.targets.length; index++) {
  90946. var weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
  90947. babylonMesh.morphTargetManager.addTarget(new BABYLON.MorphTarget("morphTarget" + index, weight));
  90948. // TODO: tell the target whether it has positions, normals, tangents
  90949. }
  90950. };
  90951. GLTFLoader.prototype._loadMorphTargetsAsync = function (context, primitive, babylonMesh, babylonVertexData) {
  90952. if (!primitive.targets) {
  90953. return Promise.resolve();
  90954. }
  90955. var promises = new Array();
  90956. var morphTargetManager = babylonMesh.morphTargetManager;
  90957. for (var index = 0; index < morphTargetManager.numTargets; index++) {
  90958. var babylonMorphTarget = morphTargetManager.getTarget(index);
  90959. promises.push(this._loadMorphTargetVertexDataAsync(context + "/targets/" + index, babylonVertexData, primitive.targets[index], babylonMorphTarget));
  90960. }
  90961. return Promise.all(promises).then(function () { });
  90962. };
  90963. GLTFLoader.prototype._loadMorphTargetVertexDataAsync = function (context, babylonVertexData, attributes, babylonMorphTarget) {
  90964. var _this = this;
  90965. var promises = new Array();
  90966. var loadAttribute = function (attribute, setData) {
  90967. if (attributes[attribute] == undefined) {
  90968. return;
  90969. }
  90970. var accessor = GLTFLoader._GetProperty(context + "/" + attribute, _this._gltf.accessors, attributes[attribute]);
  90971. promises.push(_this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  90972. setData(data);
  90973. }));
  90974. };
  90975. loadAttribute("POSITION", function (data) {
  90976. if (babylonVertexData.positions) {
  90977. for (var i = 0; i < data.length; i++) {
  90978. data[i] += babylonVertexData.positions[i];
  90979. }
  90980. babylonMorphTarget.setPositions(data);
  90981. }
  90982. });
  90983. loadAttribute("NORMAL", function (data) {
  90984. if (babylonVertexData.normals) {
  90985. for (var i = 0; i < data.length; i++) {
  90986. data[i] += babylonVertexData.normals[i];
  90987. }
  90988. babylonMorphTarget.setNormals(data);
  90989. }
  90990. });
  90991. loadAttribute("TANGENT", function (data) {
  90992. if (babylonVertexData.tangents) {
  90993. // Tangent data for morph targets is stored as xyz delta.
  90994. // The vertexData.tangent is stored as xyzw.
  90995. // So we need to skip every fourth vertexData.tangent.
  90996. for (var i = 0, j = 0; i < data.length; i++) {
  90997. data[i] += babylonVertexData.tangents[j++];
  90998. if ((i + 1) % 3 == 0) {
  90999. j++;
  91000. }
  91001. }
  91002. babylonMorphTarget.setTangents(data);
  91003. }
  91004. });
  91005. return Promise.all(promises).then(function () { });
  91006. };
  91007. GLTFLoader._ConvertToFloat32Array = function (context, accessor, data) {
  91008. if (accessor.componentType == 5126 /* FLOAT */) {
  91009. return data;
  91010. }
  91011. var factor = 1;
  91012. if (accessor.normalized) {
  91013. switch (accessor.componentType) {
  91014. case 5121 /* UNSIGNED_BYTE */: {
  91015. factor = 1 / 255;
  91016. break;
  91017. }
  91018. case 5123 /* UNSIGNED_SHORT */: {
  91019. factor = 1 / 65535;
  91020. break;
  91021. }
  91022. default: {
  91023. throw new Error(context + ": Invalid component type " + accessor.componentType);
  91024. }
  91025. }
  91026. }
  91027. var result = new Float32Array(accessor.count * GLTFLoader._GetNumComponents(context, accessor.type));
  91028. for (var i = 0; i < result.length; i++) {
  91029. result[i] = data[i] * factor;
  91030. }
  91031. return result;
  91032. };
  91033. GLTFLoader._ConvertVec3ToVec4 = function (context, data) {
  91034. var result = new Float32Array(data.length / 3 * 4);
  91035. var offset = 0;
  91036. for (var i = 0; i < result.length; i++) {
  91037. if ((i + 1) % 4 === 0) {
  91038. result[i] = 1;
  91039. }
  91040. else {
  91041. result[i] = data[offset++];
  91042. }
  91043. }
  91044. return result;
  91045. };
  91046. GLTFLoader._LoadTransform = function (node, babylonNode) {
  91047. var position = BABYLON.Vector3.Zero();
  91048. var rotation = BABYLON.Quaternion.Identity();
  91049. var scaling = BABYLON.Vector3.One();
  91050. if (node.matrix) {
  91051. var matrix = BABYLON.Matrix.FromArray(node.matrix);
  91052. matrix.decompose(scaling, rotation, position);
  91053. }
  91054. else {
  91055. if (node.translation)
  91056. position = BABYLON.Vector3.FromArray(node.translation);
  91057. if (node.rotation)
  91058. rotation = BABYLON.Quaternion.FromArray(node.rotation);
  91059. if (node.scale)
  91060. scaling = BABYLON.Vector3.FromArray(node.scale);
  91061. }
  91062. babylonNode.position = position;
  91063. babylonNode.rotationQuaternion = rotation;
  91064. babylonNode.scaling = scaling;
  91065. };
  91066. GLTFLoader.prototype._loadSkinAsync = function (context, node, mesh, skin) {
  91067. var _this = this;
  91068. var assignSkeleton = function () {
  91069. for (var _i = 0, _a = node._primitiveBabylonMeshes; _i < _a.length; _i++) {
  91070. var babylonMesh = _a[_i];
  91071. babylonMesh.skeleton = skin._babylonSkeleton;
  91072. }
  91073. node._babylonMesh.parent = _this._rootBabylonMesh;
  91074. node._babylonMesh.position = BABYLON.Vector3.Zero();
  91075. node._babylonMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  91076. node._babylonMesh.scaling = BABYLON.Vector3.One();
  91077. };
  91078. if (skin._loaded) {
  91079. assignSkeleton();
  91080. return skin._loaded;
  91081. }
  91082. // TODO: split into two parts so that bones are created before inverseBindMatricesData is loaded (for compiling materials).
  91083. return (skin._loaded = this._loadSkinInverseBindMatricesDataAsync(context, skin).then(function (inverseBindMatricesData) {
  91084. var skeletonId = "skeleton" + skin._index;
  91085. var babylonSkeleton = new BABYLON.Skeleton(skin.name || skeletonId, skeletonId, _this._babylonScene);
  91086. skin._babylonSkeleton = babylonSkeleton;
  91087. _this._loadBones(context, skin, inverseBindMatricesData);
  91088. assignSkeleton();
  91089. }));
  91090. };
  91091. GLTFLoader.prototype._loadSkinInverseBindMatricesDataAsync = function (context, skin) {
  91092. if (skin.inverseBindMatrices == undefined) {
  91093. return Promise.resolve(null);
  91094. }
  91095. var accessor = GLTFLoader._GetProperty(context + "/inverseBindMatrices", this._gltf.accessors, skin.inverseBindMatrices);
  91096. return this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  91097. return data;
  91098. });
  91099. };
  91100. GLTFLoader.prototype._createBone = function (node, skin, parent, localMatrix, baseMatrix, index) {
  91101. var babylonBone = new BABYLON.Bone(node.name || "joint" + node._index, skin._babylonSkeleton, parent, localMatrix, null, baseMatrix, index);
  91102. node._babylonAnimationTargets = node._babylonAnimationTargets || [];
  91103. node._babylonAnimationTargets.push(babylonBone);
  91104. return babylonBone;
  91105. };
  91106. GLTFLoader.prototype._loadBones = function (context, skin, inverseBindMatricesData) {
  91107. var babylonBones = {};
  91108. for (var _i = 0, _a = skin.joints; _i < _a.length; _i++) {
  91109. var index = _a[_i];
  91110. var node = GLTFLoader._GetProperty(context + "/joints/" + index, this._gltf.nodes, index);
  91111. this._loadBone(node, skin, inverseBindMatricesData, babylonBones);
  91112. }
  91113. };
  91114. GLTFLoader.prototype._loadBone = function (node, skin, inverseBindMatricesData, babylonBones) {
  91115. var babylonBone = babylonBones[node._index];
  91116. if (babylonBone) {
  91117. return babylonBone;
  91118. }
  91119. var boneIndex = skin.joints.indexOf(node._index);
  91120. var baseMatrix = BABYLON.Matrix.Identity();
  91121. if (inverseBindMatricesData && boneIndex !== -1) {
  91122. baseMatrix = BABYLON.Matrix.FromArray(inverseBindMatricesData, boneIndex * 16);
  91123. baseMatrix.invertToRef(baseMatrix);
  91124. }
  91125. var babylonParentBone = null;
  91126. if (node._parent._babylonMesh !== this._rootBabylonMesh) {
  91127. babylonParentBone = this._loadBone(node._parent, skin, inverseBindMatricesData, babylonBones);
  91128. baseMatrix.multiplyToRef(babylonParentBone.getInvertedAbsoluteTransform(), baseMatrix);
  91129. }
  91130. babylonBone = this._createBone(node, skin, babylonParentBone, this._getNodeMatrix(node), baseMatrix, boneIndex);
  91131. babylonBones[node._index] = babylonBone;
  91132. return babylonBone;
  91133. };
  91134. GLTFLoader.prototype._getNodeMatrix = function (node) {
  91135. return node.matrix ?
  91136. BABYLON.Matrix.FromArray(node.matrix) :
  91137. BABYLON.Matrix.Compose(node.scale ? BABYLON.Vector3.FromArray(node.scale) : BABYLON.Vector3.One(), node.rotation ? BABYLON.Quaternion.FromArray(node.rotation) : BABYLON.Quaternion.Identity(), node.translation ? BABYLON.Vector3.FromArray(node.translation) : BABYLON.Vector3.Zero());
  91138. };
  91139. GLTFLoader.prototype._loadAnimationsAsync = function () {
  91140. var animations = this._gltf.animations;
  91141. if (!animations) {
  91142. return Promise.resolve();
  91143. }
  91144. var promises = new Array();
  91145. for (var index = 0; index < animations.length; index++) {
  91146. var animation = animations[index];
  91147. promises.push(this._loadAnimationAsync("#/animations/" + index, animation));
  91148. }
  91149. return Promise.all(promises).then(function () { });
  91150. };
  91151. GLTFLoader.prototype._loadAnimationAsync = function (context, animation) {
  91152. var babylonAnimationGroup = new BABYLON.AnimationGroup(animation.name || "animation" + animation._index, this._babylonScene);
  91153. animation._babylonAnimationGroup = babylonAnimationGroup;
  91154. var promises = new Array();
  91155. GLTF2.ArrayItem.Assign(animation.channels);
  91156. GLTF2.ArrayItem.Assign(animation.samplers);
  91157. for (var _i = 0, _a = animation.channels; _i < _a.length; _i++) {
  91158. var channel = _a[_i];
  91159. promises.push(this._loadAnimationChannelAsync(context + "/channels/" + channel._index, context, animation, channel, babylonAnimationGroup));
  91160. }
  91161. return Promise.all(promises).then(function () {
  91162. babylonAnimationGroup.normalize();
  91163. });
  91164. };
  91165. GLTFLoader.prototype._loadAnimationChannelAsync = function (context, animationContext, animation, channel, babylonAnimationGroup) {
  91166. var targetNode = GLTFLoader._GetProperty(context + "/target/node", this._gltf.nodes, channel.target.node);
  91167. if (!targetNode._babylonMesh) {
  91168. return Promise.resolve();
  91169. }
  91170. var sampler = GLTFLoader._GetProperty(context + "/sampler", animation.samplers, channel.sampler);
  91171. return this._loadAnimationSamplerAsync(animationContext + "/samplers/" + channel.sampler, sampler).then(function (data) {
  91172. var targetPath;
  91173. var animationType;
  91174. switch (channel.target.path) {
  91175. case "translation" /* TRANSLATION */: {
  91176. targetPath = "position";
  91177. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  91178. break;
  91179. }
  91180. case "rotation" /* ROTATION */: {
  91181. targetPath = "rotationQuaternion";
  91182. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  91183. break;
  91184. }
  91185. case "scale" /* SCALE */: {
  91186. targetPath = "scaling";
  91187. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  91188. break;
  91189. }
  91190. case "weights" /* WEIGHTS */: {
  91191. targetPath = "influence";
  91192. animationType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  91193. break;
  91194. }
  91195. default: {
  91196. throw new Error(context + ": Invalid target path " + channel.target.path);
  91197. }
  91198. }
  91199. var outputBufferOffset = 0;
  91200. var getNextOutputValue;
  91201. switch (targetPath) {
  91202. case "position": {
  91203. getNextOutputValue = function () {
  91204. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  91205. outputBufferOffset += 3;
  91206. return value;
  91207. };
  91208. break;
  91209. }
  91210. case "rotationQuaternion": {
  91211. getNextOutputValue = function () {
  91212. var value = BABYLON.Quaternion.FromArray(data.output, outputBufferOffset);
  91213. outputBufferOffset += 4;
  91214. return value;
  91215. };
  91216. break;
  91217. }
  91218. case "scaling": {
  91219. getNextOutputValue = function () {
  91220. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  91221. outputBufferOffset += 3;
  91222. return value;
  91223. };
  91224. break;
  91225. }
  91226. case "influence": {
  91227. getNextOutputValue = function () {
  91228. var value = new Array(targetNode._numMorphTargets);
  91229. for (var i = 0; i < targetNode._numMorphTargets; i++) {
  91230. value[i] = data.output[outputBufferOffset++];
  91231. }
  91232. return value;
  91233. };
  91234. break;
  91235. }
  91236. }
  91237. var getNextKey;
  91238. switch (data.interpolation) {
  91239. case "STEP" /* STEP */: {
  91240. getNextKey = function (frameIndex) { return ({
  91241. frame: data.input[frameIndex],
  91242. value: getNextOutputValue(),
  91243. interpolation: BABYLON.AnimationKeyInterpolation.STEP
  91244. }); };
  91245. break;
  91246. }
  91247. case "LINEAR" /* LINEAR */: {
  91248. getNextKey = function (frameIndex) { return ({
  91249. frame: data.input[frameIndex],
  91250. value: getNextOutputValue()
  91251. }); };
  91252. break;
  91253. }
  91254. case "CUBICSPLINE" /* CUBICSPLINE */: {
  91255. getNextKey = function (frameIndex) { return ({
  91256. frame: data.input[frameIndex],
  91257. inTangent: getNextOutputValue(),
  91258. value: getNextOutputValue(),
  91259. outTangent: getNextOutputValue()
  91260. }); };
  91261. break;
  91262. }
  91263. }
  91264. var keys;
  91265. if (data.input.length === 1) {
  91266. var key = getNextKey(0);
  91267. keys = [
  91268. { frame: key.frame, value: key.value },
  91269. { frame: key.frame + 1, value: key.value }
  91270. ];
  91271. }
  91272. else {
  91273. keys = new Array(data.input.length);
  91274. for (var frameIndex = 0; frameIndex < data.input.length; frameIndex++) {
  91275. keys[frameIndex] = getNextKey(frameIndex);
  91276. }
  91277. }
  91278. if (targetPath === "influence") {
  91279. var _loop_1 = function (targetIndex) {
  91280. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  91281. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  91282. babylonAnimation.setKeys(keys.map(function (key) { return ({
  91283. frame: key.frame,
  91284. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  91285. value: key.value[targetIndex],
  91286. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  91287. }); }));
  91288. for (var _i = 0, _a = targetNode._primitiveBabylonMeshes; _i < _a.length; _i++) {
  91289. var babylonMesh = _a[_i];
  91290. var morphTarget = babylonMesh.morphTargetManager.getTarget(targetIndex);
  91291. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, morphTarget);
  91292. }
  91293. };
  91294. for (var targetIndex = 0; targetIndex < targetNode._numMorphTargets; targetIndex++) {
  91295. _loop_1(targetIndex);
  91296. }
  91297. }
  91298. else {
  91299. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  91300. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  91301. babylonAnimation.setKeys(keys);
  91302. if (targetNode._babylonAnimationTargets) {
  91303. for (var _i = 0, _a = targetNode._babylonAnimationTargets; _i < _a.length; _i++) {
  91304. var target = _a[_i];
  91305. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, target);
  91306. }
  91307. }
  91308. }
  91309. });
  91310. };
  91311. GLTFLoader.prototype._loadAnimationSamplerAsync = function (context, sampler) {
  91312. if (sampler._data) {
  91313. return sampler._data;
  91314. }
  91315. var interpolation = sampler.interpolation || "LINEAR" /* LINEAR */;
  91316. switch (interpolation) {
  91317. case "STEP" /* STEP */:
  91318. case "LINEAR" /* LINEAR */:
  91319. case "CUBICSPLINE" /* CUBICSPLINE */: {
  91320. break;
  91321. }
  91322. default: {
  91323. throw new Error(context + ": Invalid interpolation " + sampler.interpolation);
  91324. }
  91325. }
  91326. var inputData;
  91327. var outputData;
  91328. var inputAccessor = GLTFLoader._GetProperty(context + "/input", this._gltf.accessors, sampler.input);
  91329. var outputAccessor = GLTFLoader._GetProperty(context + "/output", this._gltf.accessors, sampler.output);
  91330. sampler._data = Promise.all([
  91331. this._loadAccessorAsync("#/accessors/" + inputAccessor._index, inputAccessor).then(function (data) {
  91332. inputData = data;
  91333. }),
  91334. this._loadAccessorAsync("#/accessors/" + outputAccessor._index, outputAccessor).then(function (data) {
  91335. outputData = data;
  91336. })
  91337. ]).then(function () {
  91338. return {
  91339. input: inputData,
  91340. interpolation: interpolation,
  91341. output: outputData,
  91342. };
  91343. });
  91344. return sampler._data;
  91345. };
  91346. GLTFLoader.prototype._loadBufferAsync = function (context, buffer) {
  91347. if (buffer._data) {
  91348. return buffer._data;
  91349. }
  91350. if (!buffer.uri) {
  91351. throw new Error(context + ": Uri is missing");
  91352. }
  91353. buffer._data = this._loadUriAsync(context, buffer.uri);
  91354. return buffer._data;
  91355. };
  91356. GLTFLoader.prototype._loadBufferViewAsync = function (context, bufferView) {
  91357. if (bufferView._data) {
  91358. return bufferView._data;
  91359. }
  91360. var buffer = GLTFLoader._GetProperty(context + "/buffer", this._gltf.buffers, bufferView.buffer);
  91361. bufferView._data = this._loadBufferAsync("#/buffers/" + buffer._index, buffer).then(function (bufferData) {
  91362. try {
  91363. return new Uint8Array(bufferData.buffer, bufferData.byteOffset + (bufferView.byteOffset || 0), bufferView.byteLength);
  91364. }
  91365. catch (e) {
  91366. throw new Error(context + ": " + e.message);
  91367. }
  91368. });
  91369. return bufferView._data;
  91370. };
  91371. GLTFLoader.prototype._loadAccessorAsync = function (context, accessor) {
  91372. var _this = this;
  91373. if (accessor.sparse) {
  91374. throw new Error(context + ": Sparse accessors are not currently supported");
  91375. }
  91376. if (accessor._data) {
  91377. return accessor._data;
  91378. }
  91379. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, accessor.bufferView);
  91380. accessor._data = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (bufferViewData) {
  91381. var numComponents = GLTFLoader._GetNumComponents(context, accessor.type);
  91382. var byteOffset = accessor.byteOffset || 0;
  91383. var byteStride = bufferView.byteStride;
  91384. if (byteStride === 0) {
  91385. BABYLON.Tools.Warn(context + ": Byte stride of 0 is not valid");
  91386. }
  91387. try {
  91388. switch (accessor.componentType) {
  91389. case 5120 /* BYTE */: {
  91390. return _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  91391. }
  91392. case 5121 /* UNSIGNED_BYTE */: {
  91393. return _this._buildArrayBuffer(Uint8Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  91394. }
  91395. case 5122 /* SHORT */: {
  91396. return _this._buildArrayBuffer(Int16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  91397. }
  91398. case 5123 /* UNSIGNED_SHORT */: {
  91399. return _this._buildArrayBuffer(Uint16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  91400. }
  91401. case 5125 /* UNSIGNED_INT */: {
  91402. return _this._buildArrayBuffer(Uint32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  91403. }
  91404. case 5126 /* FLOAT */: {
  91405. return _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  91406. }
  91407. default: {
  91408. throw new Error(context + ": Invalid component type " + accessor.componentType);
  91409. }
  91410. }
  91411. }
  91412. catch (e) {
  91413. throw new Error(context + ": " + e);
  91414. }
  91415. });
  91416. return accessor._data;
  91417. };
  91418. GLTFLoader.prototype._buildArrayBuffer = function (typedArray, data, byteOffset, count, numComponents, byteStride) {
  91419. byteOffset += data.byteOffset;
  91420. var targetLength = count * numComponents;
  91421. if (!byteStride || byteStride === numComponents * typedArray.BYTES_PER_ELEMENT) {
  91422. return new typedArray(data.buffer, byteOffset, targetLength);
  91423. }
  91424. var elementStride = byteStride / typedArray.BYTES_PER_ELEMENT;
  91425. var sourceBuffer = new typedArray(data.buffer, byteOffset, elementStride * count);
  91426. var targetBuffer = new typedArray(targetLength);
  91427. var sourceIndex = 0;
  91428. var targetIndex = 0;
  91429. while (targetIndex < targetLength) {
  91430. for (var componentIndex = 0; componentIndex < numComponents; componentIndex++) {
  91431. targetBuffer[targetIndex] = sourceBuffer[sourceIndex + componentIndex];
  91432. targetIndex++;
  91433. }
  91434. sourceIndex += elementStride;
  91435. }
  91436. return targetBuffer;
  91437. };
  91438. GLTFLoader.prototype._getDefaultMaterial = function () {
  91439. var id = "__gltf_default";
  91440. var babylonMaterial = this._babylonScene.getMaterialByName(id);
  91441. if (!babylonMaterial) {
  91442. babylonMaterial = new BABYLON.PBRMaterial(id, this._babylonScene);
  91443. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  91444. babylonMaterial.sideOrientation = this._babylonScene.useRightHandedSystem ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation;
  91445. babylonMaterial.metallic = 1;
  91446. babylonMaterial.roughness = 1;
  91447. this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  91448. }
  91449. return babylonMaterial;
  91450. };
  91451. GLTFLoader.prototype._loadMaterialMetallicRoughnessPropertiesAsync = function (context, material) {
  91452. var promises = new Array();
  91453. var babylonMaterial = material._babylonMaterial;
  91454. // Ensure metallic workflow
  91455. babylonMaterial.metallic = 1;
  91456. babylonMaterial.roughness = 1;
  91457. var properties = material.pbrMetallicRoughness;
  91458. if (properties) {
  91459. if (properties.baseColorFactor) {
  91460. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.baseColorFactor);
  91461. babylonMaterial.alpha = properties.baseColorFactor[3];
  91462. }
  91463. else {
  91464. babylonMaterial.albedoColor = BABYLON.Color3.White();
  91465. }
  91466. babylonMaterial.metallic = properties.metallicFactor == undefined ? 1 : properties.metallicFactor;
  91467. babylonMaterial.roughness = properties.roughnessFactor == undefined ? 1 : properties.roughnessFactor;
  91468. if (properties.baseColorTexture) {
  91469. promises.push(this._loadTextureAsync(context + "/baseColorTexture", properties.baseColorTexture, function (texture) {
  91470. babylonMaterial.albedoTexture = texture;
  91471. }));
  91472. }
  91473. if (properties.metallicRoughnessTexture) {
  91474. promises.push(this._loadTextureAsync(context + "/metallicRoughnessTexture", properties.metallicRoughnessTexture, function (texture) {
  91475. babylonMaterial.metallicTexture = texture;
  91476. }));
  91477. babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  91478. babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  91479. babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  91480. }
  91481. }
  91482. this._loadMaterialAlphaProperties(context, material);
  91483. return Promise.all(promises).then(function () { });
  91484. };
  91485. GLTFLoader.prototype._loadMaterialAsync = function (context, material, babylonMesh) {
  91486. var promise = GLTF2.GLTFLoaderExtension._LoadMaterialAsync(this, context, material, babylonMesh);
  91487. if (promise) {
  91488. return promise;
  91489. }
  91490. material._babylonMeshes = material._babylonMeshes || [];
  91491. material._babylonMeshes.push(babylonMesh);
  91492. if (material._loaded) {
  91493. babylonMesh.material = material._babylonMaterial;
  91494. return material._loaded;
  91495. }
  91496. var promises = new Array();
  91497. var babylonMaterial = this._createMaterial(material);
  91498. material._babylonMaterial = babylonMaterial;
  91499. promises.push(this._loadMaterialBasePropertiesAsync(context, material));
  91500. promises.push(this._loadMaterialMetallicRoughnessPropertiesAsync(context, material));
  91501. this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  91502. babylonMesh.material = babylonMaterial;
  91503. return (material._loaded = Promise.all(promises).then(function () { }));
  91504. };
  91505. GLTFLoader.prototype._createMaterial = function (material) {
  91506. var babylonMaterial = new BABYLON.PBRMaterial(material.name || "material" + material._index, this._babylonScene);
  91507. babylonMaterial.sideOrientation = this._babylonScene.useRightHandedSystem ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation;
  91508. return babylonMaterial;
  91509. };
  91510. GLTFLoader.prototype._loadMaterialBasePropertiesAsync = function (context, material) {
  91511. var promises = new Array();
  91512. var babylonMaterial = material._babylonMaterial;
  91513. babylonMaterial.emissiveColor = material.emissiveFactor ? BABYLON.Color3.FromArray(material.emissiveFactor) : new BABYLON.Color3(0, 0, 0);
  91514. if (material.doubleSided) {
  91515. babylonMaterial.backFaceCulling = false;
  91516. babylonMaterial.twoSidedLighting = true;
  91517. }
  91518. if (material.normalTexture) {
  91519. promises.push(this._loadTextureAsync(context + "/normalTexture", material.normalTexture, function (texture) {
  91520. babylonMaterial.bumpTexture = texture;
  91521. }));
  91522. babylonMaterial.invertNormalMapX = !this._babylonScene.useRightHandedSystem;
  91523. babylonMaterial.invertNormalMapY = this._babylonScene.useRightHandedSystem;
  91524. if (material.normalTexture.scale != undefined) {
  91525. babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  91526. }
  91527. }
  91528. if (material.occlusionTexture) {
  91529. promises.push(this._loadTextureAsync(context + "/occlusionTexture", material.occlusionTexture, function (texture) {
  91530. babylonMaterial.ambientTexture = texture;
  91531. }));
  91532. babylonMaterial.useAmbientInGrayScale = true;
  91533. if (material.occlusionTexture.strength != undefined) {
  91534. babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  91535. }
  91536. }
  91537. if (material.emissiveTexture) {
  91538. promises.push(this._loadTextureAsync(context + "/emissiveTexture", material.emissiveTexture, function (texture) {
  91539. babylonMaterial.emissiveTexture = texture;
  91540. }));
  91541. }
  91542. return Promise.all(promises).then(function () { });
  91543. };
  91544. GLTFLoader.prototype._loadMaterialAlphaProperties = function (context, material) {
  91545. var babylonMaterial = material._babylonMaterial;
  91546. var alphaMode = material.alphaMode || "OPAQUE" /* OPAQUE */;
  91547. switch (alphaMode) {
  91548. case "OPAQUE" /* OPAQUE */: {
  91549. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  91550. break;
  91551. }
  91552. case "MASK" /* MASK */: {
  91553. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  91554. babylonMaterial.alphaCutOff = (material.alphaCutoff == undefined ? 0.5 : material.alphaCutoff);
  91555. if (babylonMaterial.alpha) {
  91556. if (babylonMaterial.alpha === 0) {
  91557. babylonMaterial.alphaCutOff = 1;
  91558. }
  91559. else {
  91560. babylonMaterial.alphaCutOff /= babylonMaterial.alpha;
  91561. }
  91562. babylonMaterial.alpha = 1;
  91563. }
  91564. if (babylonMaterial.albedoTexture) {
  91565. babylonMaterial.albedoTexture.hasAlpha = true;
  91566. }
  91567. break;
  91568. }
  91569. case "BLEND" /* BLEND */: {
  91570. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND;
  91571. if (babylonMaterial.albedoTexture) {
  91572. babylonMaterial.albedoTexture.hasAlpha = true;
  91573. babylonMaterial.useAlphaFromAlbedoTexture = true;
  91574. }
  91575. break;
  91576. }
  91577. default: {
  91578. throw new Error(context + ": Invalid alpha mode " + material.alphaMode);
  91579. }
  91580. }
  91581. };
  91582. GLTFLoader.prototype._loadTextureAsync = function (context, textureInfo, assign) {
  91583. var _this = this;
  91584. var texture = GLTFLoader._GetProperty(context + "/index", this._gltf.textures, textureInfo.index);
  91585. context = "#/textures/" + textureInfo.index;
  91586. var promises = new Array();
  91587. var sampler = (texture.sampler == undefined ? this._defaultSampler : GLTFLoader._GetProperty(context + "/sampler", this._gltf.samplers, texture.sampler));
  91588. var samplerData = this._loadSampler("#/samplers/" + sampler._index, sampler);
  91589. var deferred = new BABYLON.Deferred();
  91590. var babylonTexture = new BABYLON.Texture(null, this._babylonScene, samplerData.noMipMaps, false, samplerData.samplingMode, function () {
  91591. if (!_this._disposed) {
  91592. deferred.resolve();
  91593. }
  91594. }, function (message, exception) {
  91595. if (!_this._disposed) {
  91596. deferred.reject(new Error(context + ": " + (exception && exception.message) ? exception.message : message || "Failed to load texture"));
  91597. }
  91598. });
  91599. promises.push(deferred.promise);
  91600. babylonTexture.name = texture.name || "texture" + texture._index;
  91601. babylonTexture.wrapU = samplerData.wrapU;
  91602. babylonTexture.wrapV = samplerData.wrapV;
  91603. babylonTexture.coordinatesIndex = textureInfo.texCoord || 0;
  91604. var image = GLTFLoader._GetProperty(context + "/source", this._gltf.images, texture.source);
  91605. promises.push(this._loadImageAsync("#/images/" + image._index, image).then(function (objectURL) {
  91606. babylonTexture.updateURL(objectURL);
  91607. }));
  91608. assign(babylonTexture);
  91609. this.onTextureLoadedObservable.notifyObservers(babylonTexture);
  91610. return Promise.all(promises).then(function () { });
  91611. };
  91612. GLTFLoader.prototype._loadSampler = function (context, sampler) {
  91613. if (!sampler._data) {
  91614. sampler._data = {
  91615. noMipMaps: (sampler.minFilter === 9728 /* NEAREST */ || sampler.minFilter === 9729 /* LINEAR */),
  91616. samplingMode: GLTFLoader._GetTextureSamplingMode(context, sampler.magFilter, sampler.minFilter),
  91617. wrapU: GLTFLoader._GetTextureWrapMode(context, sampler.wrapS),
  91618. wrapV: GLTFLoader._GetTextureWrapMode(context, sampler.wrapT)
  91619. };
  91620. }
  91621. ;
  91622. return sampler._data;
  91623. };
  91624. GLTFLoader.prototype._loadImageAsync = function (context, image) {
  91625. if (image._objectURL) {
  91626. return image._objectURL;
  91627. }
  91628. var promise;
  91629. if (image.uri) {
  91630. promise = this._loadUriAsync(context, image.uri);
  91631. }
  91632. else {
  91633. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, image.bufferView);
  91634. promise = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView);
  91635. }
  91636. image._objectURL = promise.then(function (data) {
  91637. return URL.createObjectURL(new Blob([data], { type: image.mimeType }));
  91638. });
  91639. return image._objectURL;
  91640. };
  91641. GLTFLoader.prototype._loadUriAsync = function (context, uri) {
  91642. var _this = this;
  91643. var promise = GLTF2.GLTFLoaderExtension._LoadUriAsync(this, context, uri);
  91644. if (promise) {
  91645. return promise;
  91646. }
  91647. if (!GLTFLoader._ValidateUri(uri)) {
  91648. throw new Error(context + ": Uri '" + uri + "' is invalid");
  91649. }
  91650. if (BABYLON.Tools.IsBase64(uri)) {
  91651. return Promise.resolve(new Uint8Array(BABYLON.Tools.DecodeBase64(uri)));
  91652. }
  91653. return new Promise(function (resolve, reject) {
  91654. var request = BABYLON.Tools.LoadFile(_this._rootUrl + uri, function (data) {
  91655. if (!_this._disposed) {
  91656. resolve(new Uint8Array(data));
  91657. }
  91658. }, function (event) {
  91659. if (!_this._disposed) {
  91660. try {
  91661. if (request && _this._state === BABYLON.GLTFLoaderState.Loading) {
  91662. request._lengthComputable = event.lengthComputable;
  91663. request._loaded = event.loaded;
  91664. request._total = event.total;
  91665. _this._onProgress();
  91666. }
  91667. }
  91668. catch (e) {
  91669. reject(e);
  91670. }
  91671. }
  91672. }, _this._babylonScene.database, true, function (request, exception) {
  91673. if (!_this._disposed) {
  91674. reject(new BABYLON.LoadFileError(context + ": Failed to load '" + uri + "'" + (request ? ": " + request.status + " " + request.statusText : ""), request));
  91675. }
  91676. });
  91677. _this._requests.push(request);
  91678. });
  91679. };
  91680. GLTFLoader.prototype._onProgress = function () {
  91681. if (!this._progressCallback) {
  91682. return;
  91683. }
  91684. var lengthComputable = true;
  91685. var loaded = 0;
  91686. var total = 0;
  91687. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  91688. var request = _a[_i];
  91689. if (request._lengthComputable === undefined || request._loaded === undefined || request._total === undefined) {
  91690. return;
  91691. }
  91692. lengthComputable = lengthComputable && request._lengthComputable;
  91693. loaded += request._loaded;
  91694. total += request._total;
  91695. }
  91696. this._progressCallback(new BABYLON.SceneLoaderProgressEvent(lengthComputable, loaded, lengthComputable ? total : 0));
  91697. };
  91698. GLTFLoader._GetProperty = function (context, array, index) {
  91699. if (!array || index == undefined || !array[index]) {
  91700. throw new Error(context + ": Failed to find index " + index);
  91701. }
  91702. return array[index];
  91703. };
  91704. GLTFLoader._GetTextureWrapMode = function (context, mode) {
  91705. // Set defaults if undefined
  91706. mode = mode == undefined ? 10497 /* REPEAT */ : mode;
  91707. switch (mode) {
  91708. case 33071 /* CLAMP_TO_EDGE */: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  91709. case 33648 /* MIRRORED_REPEAT */: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  91710. case 10497 /* REPEAT */: return BABYLON.Texture.WRAP_ADDRESSMODE;
  91711. default:
  91712. BABYLON.Tools.Warn(context + ": Invalid texture wrap mode " + mode);
  91713. return BABYLON.Texture.WRAP_ADDRESSMODE;
  91714. }
  91715. };
  91716. GLTFLoader._GetTextureSamplingMode = function (context, magFilter, minFilter) {
  91717. // Set defaults if undefined
  91718. magFilter = magFilter == undefined ? 9729 /* LINEAR */ : magFilter;
  91719. minFilter = minFilter == undefined ? 9987 /* LINEAR_MIPMAP_LINEAR */ : minFilter;
  91720. if (magFilter === 9729 /* LINEAR */) {
  91721. switch (minFilter) {
  91722. case 9728 /* NEAREST */: return BABYLON.Texture.LINEAR_NEAREST;
  91723. case 9729 /* LINEAR */: return BABYLON.Texture.LINEAR_LINEAR;
  91724. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST;
  91725. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST;
  91726. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR;
  91727. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  91728. default:
  91729. BABYLON.Tools.Warn(context + ": Invalid texture minification filter " + minFilter);
  91730. return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  91731. }
  91732. }
  91733. else {
  91734. if (magFilter !== 9728 /* NEAREST */) {
  91735. BABYLON.Tools.Warn(context + ": Invalid texture magnification filter " + magFilter);
  91736. }
  91737. switch (minFilter) {
  91738. case 9728 /* NEAREST */: return BABYLON.Texture.NEAREST_NEAREST;
  91739. case 9729 /* LINEAR */: return BABYLON.Texture.NEAREST_LINEAR;
  91740. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  91741. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST;
  91742. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_NEAREST_MIPLINEAR;
  91743. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR;
  91744. default:
  91745. BABYLON.Tools.Warn(context + ": Invalid texture minification filter " + minFilter);
  91746. return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  91747. }
  91748. }
  91749. };
  91750. GLTFLoader._GetNumComponents = function (context, type) {
  91751. switch (type) {
  91752. case "SCALAR": return 1;
  91753. case "VEC2": return 2;
  91754. case "VEC3": return 3;
  91755. case "VEC4": return 4;
  91756. case "MAT2": return 4;
  91757. case "MAT3": return 9;
  91758. case "MAT4": return 16;
  91759. }
  91760. throw new Error(context + ": Invalid type " + type);
  91761. };
  91762. GLTFLoader._ValidateUri = function (uri) {
  91763. return (BABYLON.Tools.IsBase64(uri) || uri.indexOf("..") === -1);
  91764. };
  91765. GLTFLoader.prototype._compileMaterialsAsync = function () {
  91766. var promises = new Array();
  91767. if (this._gltf.materials) {
  91768. for (var _i = 0, _a = this._gltf.materials; _i < _a.length; _i++) {
  91769. var material = _a[_i];
  91770. var babylonMaterial = material._babylonMaterial;
  91771. var babylonMeshes = material._babylonMeshes;
  91772. if (babylonMaterial && babylonMeshes) {
  91773. for (var _b = 0, babylonMeshes_1 = babylonMeshes; _b < babylonMeshes_1.length; _b++) {
  91774. var babylonMesh = babylonMeshes_1[_b];
  91775. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh));
  91776. if (this.useClipPlane) {
  91777. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh, { clipPlane: true }));
  91778. }
  91779. }
  91780. }
  91781. }
  91782. }
  91783. return Promise.all(promises).then(function () { });
  91784. };
  91785. GLTFLoader.prototype._compileShadowGeneratorsAsync = function () {
  91786. var promises = new Array();
  91787. var lights = this._babylonScene.lights;
  91788. for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) {
  91789. var light = lights_1[_i];
  91790. var generator = light.getShadowGenerator();
  91791. if (generator) {
  91792. promises.push(generator.forceCompilationAsync());
  91793. }
  91794. }
  91795. return Promise.all(promises).then(function () { });
  91796. };
  91797. GLTFLoader.prototype._abortRequests = function () {
  91798. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  91799. var request = _a[_i];
  91800. request.abort();
  91801. }
  91802. this._requests.length = 0;
  91803. };
  91804. GLTFLoader.prototype._releaseResources = function () {
  91805. if (this._gltf.images) {
  91806. for (var _i = 0, _a = this._gltf.images; _i < _a.length; _i++) {
  91807. var image = _a[_i];
  91808. if (image._objectURL) {
  91809. image._objectURL.then(function (value) {
  91810. URL.revokeObjectURL(value);
  91811. });
  91812. image._objectURL = undefined;
  91813. }
  91814. }
  91815. }
  91816. };
  91817. GLTFLoader.prototype._applyExtensions = function (actionAsync) {
  91818. for (var _i = 0, _a = GLTFLoader._Names; _i < _a.length; _i++) {
  91819. var name_2 = _a[_i];
  91820. var extension = this._extensions[name_2];
  91821. if (extension.enabled) {
  91822. var promise = actionAsync(extension);
  91823. if (promise) {
  91824. return promise;
  91825. }
  91826. }
  91827. }
  91828. return null;
  91829. };
  91830. GLTFLoader._Names = new Array();
  91831. GLTFLoader._Factories = {};
  91832. return GLTFLoader;
  91833. }());
  91834. GLTF2.GLTFLoader = GLTFLoader;
  91835. BABYLON.GLTFFileLoader.CreateGLTFLoaderV2 = function () { return new GLTFLoader(); };
  91836. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  91837. })(BABYLON || (BABYLON = {}));
  91838. //# sourceMappingURL=babylon.glTFLoader.js.map
  91839. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  91840. var BABYLON;
  91841. (function (BABYLON) {
  91842. var GLTF2;
  91843. (function (GLTF2) {
  91844. var GLTFLoaderExtension = /** @class */ (function () {
  91845. function GLTFLoaderExtension(loader) {
  91846. this.enabled = true;
  91847. this._loader = loader;
  91848. }
  91849. // #region Overridable Methods
  91850. /** Override this method to modify the default behavior for loading scenes. */
  91851. GLTFLoaderExtension.prototype._loadSceneAsync = function (context, node) { return null; };
  91852. /** Override this method to modify the default behavior for loading nodes. */
  91853. GLTFLoaderExtension.prototype._loadNodeAsync = function (context, node) { return null; };
  91854. /** Override this method to modify the default behavior for loading materials. */
  91855. GLTFLoaderExtension.prototype._loadMaterialAsync = function (context, material, babylonMesh) { return null; };
  91856. /** Override this method to modify the default behavior for loading uris. */
  91857. GLTFLoaderExtension.prototype._loadUriAsync = function (context, uri) { return null; };
  91858. // #endregion
  91859. /** Helper method called by a loader extension to load an glTF extension. */
  91860. GLTFLoaderExtension.prototype._loadExtensionAsync = function (context, property, actionAsync) {
  91861. var _this = this;
  91862. if (!property.extensions) {
  91863. return null;
  91864. }
  91865. var extensions = property.extensions;
  91866. var extension = extensions[this.name];
  91867. if (!extension) {
  91868. return null;
  91869. }
  91870. // Clear out the extension before executing the action to avoid recursing into the same property.
  91871. delete extensions[this.name];
  91872. return actionAsync(context + "/extensions/" + this.name, extension).then(function () {
  91873. // Restore the extension after completing the action.
  91874. extensions[_this.name] = extension;
  91875. });
  91876. };
  91877. /** Helper method called by the loader to allow extensions to override loading scenes. */
  91878. GLTFLoaderExtension._LoadSceneAsync = function (loader, context, scene) {
  91879. return loader._applyExtensions(function (extension) { return extension._loadSceneAsync(context, scene); });
  91880. };
  91881. /** Helper method called by the loader to allow extensions to override loading nodes. */
  91882. GLTFLoaderExtension._LoadNodeAsync = function (loader, context, node) {
  91883. return loader._applyExtensions(function (extension) { return extension._loadNodeAsync(context, node); });
  91884. };
  91885. /** Helper method called by the loader to allow extensions to override loading materials. */
  91886. GLTFLoaderExtension._LoadMaterialAsync = function (loader, context, material, babylonMesh) {
  91887. return loader._applyExtensions(function (extension) { return extension._loadMaterialAsync(context, material, babylonMesh); });
  91888. };
  91889. /** Helper method called by the loader to allow extensions to override loading uris. */
  91890. GLTFLoaderExtension._LoadUriAsync = function (loader, context, uri) {
  91891. return loader._applyExtensions(function (extension) { return extension._loadUriAsync(context, uri); });
  91892. };
  91893. return GLTFLoaderExtension;
  91894. }());
  91895. GLTF2.GLTFLoaderExtension = GLTFLoaderExtension;
  91896. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  91897. })(BABYLON || (BABYLON = {}));
  91898. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  91899. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  91900. var BABYLON;
  91901. (function (BABYLON) {
  91902. var GLTF2;
  91903. (function (GLTF2) {
  91904. var Extensions;
  91905. (function (Extensions) {
  91906. // https://github.com/sbtron/glTF/tree/MSFT_lod/extensions/Vendor/MSFT_lod
  91907. var NAME = "MSFT_lod";
  91908. var MSFT_lod = /** @class */ (function (_super) {
  91909. __extends(MSFT_lod, _super);
  91910. function MSFT_lod() {
  91911. var _this = _super !== null && _super.apply(this, arguments) || this;
  91912. _this.name = NAME;
  91913. /**
  91914. * Maximum number of LODs to load, starting from the lowest LOD.
  91915. */
  91916. _this.maxLODsToLoad = Number.MAX_VALUE;
  91917. _this._loadingNodeLOD = null;
  91918. _this._loadNodeSignals = {};
  91919. _this._loadingMaterialLOD = null;
  91920. _this._loadMaterialSignals = {};
  91921. return _this;
  91922. }
  91923. MSFT_lod.prototype._loadNodeAsync = function (context, node) {
  91924. var _this = this;
  91925. return this._loadExtensionAsync(context, node, function (context, extension) {
  91926. var firstPromise;
  91927. var nodeLODs = _this._getLODs(context, node, _this._loader._gltf.nodes, extension.ids);
  91928. var _loop_1 = function (indexLOD) {
  91929. var nodeLOD = nodeLODs[indexLOD];
  91930. if (indexLOD !== 0) {
  91931. _this._loadingNodeLOD = nodeLOD;
  91932. _this._loadNodeSignals[nodeLOD._index] = new BABYLON.Deferred();
  91933. }
  91934. var promise = _this._loader._loadNodeAsync("#/nodes/" + nodeLOD._index, nodeLOD).then(function () {
  91935. if (indexLOD !== 0) {
  91936. var previousNodeLOD = nodeLODs[indexLOD - 1];
  91937. previousNodeLOD._babylonMesh.setEnabled(false);
  91938. }
  91939. if (indexLOD !== nodeLODs.length - 1) {
  91940. var nodeIndex = nodeLODs[indexLOD + 1]._index;
  91941. _this._loadNodeSignals[nodeIndex].resolve();
  91942. delete _this._loadNodeSignals[nodeIndex];
  91943. }
  91944. });
  91945. if (indexLOD === 0) {
  91946. firstPromise = promise;
  91947. }
  91948. else {
  91949. _this._loader._completePromises.push(promise);
  91950. _this._loadingNodeLOD = null;
  91951. }
  91952. };
  91953. for (var indexLOD = 0; indexLOD < nodeLODs.length; indexLOD++) {
  91954. _loop_1(indexLOD);
  91955. }
  91956. return firstPromise;
  91957. });
  91958. };
  91959. MSFT_lod.prototype._loadMaterialAsync = function (context, material, babylonMesh) {
  91960. var _this = this;
  91961. // Don't load material LODs if already loading a node LOD.
  91962. if (this._loadingNodeLOD) {
  91963. return null;
  91964. }
  91965. return this._loadExtensionAsync(context, material, function (context, extension) {
  91966. var firstPromise;
  91967. var materialLODs = _this._getLODs(context, material, _this._loader._gltf.materials, extension.ids);
  91968. var _loop_2 = function (indexLOD) {
  91969. var materialLOD = materialLODs[indexLOD];
  91970. if (indexLOD !== 0) {
  91971. _this._loadingMaterialLOD = materialLOD;
  91972. _this._loadMaterialSignals[materialLOD._index] = new BABYLON.Deferred();
  91973. }
  91974. var promise = _this._loader._loadMaterialAsync("#/materials/" + materialLOD._index, materialLOD, babylonMesh).then(function () {
  91975. if (indexLOD !== materialLODs.length - 1) {
  91976. var materialIndex = materialLODs[indexLOD + 1]._index;
  91977. _this._loadMaterialSignals[materialIndex].resolve();
  91978. delete _this._loadMaterialSignals[materialIndex];
  91979. }
  91980. });
  91981. if (indexLOD === 0) {
  91982. firstPromise = promise;
  91983. }
  91984. else {
  91985. _this._loader._completePromises.push(promise);
  91986. _this._loadingMaterialLOD = null;
  91987. }
  91988. };
  91989. for (var indexLOD = 0; indexLOD < materialLODs.length; indexLOD++) {
  91990. _loop_2(indexLOD);
  91991. }
  91992. return firstPromise;
  91993. });
  91994. };
  91995. MSFT_lod.prototype._loadUriAsync = function (context, uri) {
  91996. var _this = this;
  91997. // Defer the loading of uris if loading a material or node LOD.
  91998. if (this._loadingMaterialLOD) {
  91999. var index = this._loadingMaterialLOD._index;
  92000. return this._loadMaterialSignals[index].promise.then(function () {
  92001. return _this._loader._loadUriAsync(context, uri);
  92002. });
  92003. }
  92004. else if (this._loadingNodeLOD) {
  92005. var index = this._loadingNodeLOD._index;
  92006. return this._loadNodeSignals[index].promise.then(function () {
  92007. return _this._loader._loadUriAsync(context, uri);
  92008. });
  92009. }
  92010. return null;
  92011. };
  92012. /**
  92013. * Gets an array of LOD properties from lowest to highest.
  92014. */
  92015. MSFT_lod.prototype._getLODs = function (context, property, array, ids) {
  92016. if (this.maxLODsToLoad <= 0) {
  92017. throw new Error("maxLODsToLoad must be greater than zero");
  92018. }
  92019. var properties = new Array();
  92020. for (var i = ids.length - 1; i >= 0; i--) {
  92021. properties.push(GLTF2.GLTFLoader._GetProperty(context + "/ids/" + ids[i], array, ids[i]));
  92022. if (properties.length === this.maxLODsToLoad) {
  92023. return properties;
  92024. }
  92025. }
  92026. properties.push(property);
  92027. return properties;
  92028. };
  92029. return MSFT_lod;
  92030. }(GLTF2.GLTFLoaderExtension));
  92031. Extensions.MSFT_lod = MSFT_lod;
  92032. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new MSFT_lod(loader); });
  92033. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  92034. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  92035. })(BABYLON || (BABYLON = {}));
  92036. //# sourceMappingURL=MSFT_lod.js.map
  92037. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  92038. var BABYLON;
  92039. (function (BABYLON) {
  92040. var GLTF2;
  92041. (function (GLTF2) {
  92042. var Extensions;
  92043. (function (Extensions) {
  92044. // https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness
  92045. var NAME = "KHR_materials_pbrSpecularGlossiness";
  92046. var KHR_materials_pbrSpecularGlossiness = /** @class */ (function (_super) {
  92047. __extends(KHR_materials_pbrSpecularGlossiness, _super);
  92048. function KHR_materials_pbrSpecularGlossiness() {
  92049. var _this = _super !== null && _super.apply(this, arguments) || this;
  92050. _this.name = NAME;
  92051. return _this;
  92052. }
  92053. KHR_materials_pbrSpecularGlossiness.prototype._loadMaterialAsync = function (context, material, babylonMesh) {
  92054. var _this = this;
  92055. return this._loadExtensionAsync(context, material, function (context, extension) {
  92056. material._babylonMeshes = material._babylonMeshes || [];
  92057. material._babylonMeshes.push(babylonMesh);
  92058. if (material._loaded) {
  92059. babylonMesh.material = material._babylonMaterial;
  92060. return material._loaded;
  92061. }
  92062. var promises = new Array();
  92063. var babylonMaterial = _this._loader._createMaterial(material);
  92064. material._babylonMaterial = babylonMaterial;
  92065. promises.push(_this._loader._loadMaterialBasePropertiesAsync(context, material));
  92066. promises.push(_this._loadSpecularGlossinessPropertiesAsync(_this._loader, context, material, extension));
  92067. _this._loader.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  92068. babylonMesh.material = babylonMaterial;
  92069. return (material._loaded = Promise.all(promises).then(function () { }));
  92070. });
  92071. };
  92072. KHR_materials_pbrSpecularGlossiness.prototype._loadSpecularGlossinessPropertiesAsync = function (loader, context, material, properties) {
  92073. var promises = new Array();
  92074. var babylonMaterial = material._babylonMaterial;
  92075. if (properties.diffuseFactor) {
  92076. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.diffuseFactor);
  92077. babylonMaterial.alpha = properties.diffuseFactor[3];
  92078. }
  92079. else {
  92080. babylonMaterial.albedoColor = BABYLON.Color3.White();
  92081. }
  92082. babylonMaterial.reflectivityColor = properties.specularFactor ? BABYLON.Color3.FromArray(properties.specularFactor) : BABYLON.Color3.White();
  92083. babylonMaterial.microSurface = properties.glossinessFactor == undefined ? 1 : properties.glossinessFactor;
  92084. if (properties.diffuseTexture) {
  92085. promises.push(loader._loadTextureAsync(context + "/diffuseTexture", properties.diffuseTexture, function (texture) {
  92086. babylonMaterial.albedoTexture = texture;
  92087. }));
  92088. }
  92089. if (properties.specularGlossinessTexture) {
  92090. promises.push(loader._loadTextureAsync(context + "/specularGlossinessTexture", properties.specularGlossinessTexture, function (texture) {
  92091. babylonMaterial.reflectivityTexture = texture;
  92092. }));
  92093. babylonMaterial.reflectivityTexture.hasAlpha = true;
  92094. babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;
  92095. }
  92096. loader._loadMaterialAlphaProperties(context, material);
  92097. return Promise.all(promises).then(function () { });
  92098. };
  92099. return KHR_materials_pbrSpecularGlossiness;
  92100. }(GLTF2.GLTFLoaderExtension));
  92101. Extensions.KHR_materials_pbrSpecularGlossiness = KHR_materials_pbrSpecularGlossiness;
  92102. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_materials_pbrSpecularGlossiness(loader); });
  92103. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  92104. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  92105. })(BABYLON || (BABYLON = {}));
  92106. //# sourceMappingURL=KHR_materials_pbrSpecularGlossiness.js.map
  92107. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  92108. var BABYLON;
  92109. (function (BABYLON) {
  92110. var GLTF2;
  92111. (function (GLTF2) {
  92112. var Extensions;
  92113. (function (Extensions) {
  92114. // https://github.com/MiiBond/glTF/tree/khr_lights_v1/extensions/Khronos/KHR_lights
  92115. var NAME = "KHR_lights";
  92116. var LightType;
  92117. (function (LightType) {
  92118. LightType["AMBIENT"] = "ambient";
  92119. LightType["DIRECTIONAL"] = "directional";
  92120. LightType["POINT"] = "point";
  92121. LightType["SPOT"] = "spot";
  92122. })(LightType || (LightType = {}));
  92123. var KHR_lights = /** @class */ (function (_super) {
  92124. __extends(KHR_lights, _super);
  92125. function KHR_lights() {
  92126. var _this = _super !== null && _super.apply(this, arguments) || this;
  92127. _this.name = NAME;
  92128. return _this;
  92129. }
  92130. KHR_lights.prototype._loadSceneAsync = function (context, scene) {
  92131. var _this = this;
  92132. return this._loadExtensionAsync(context, scene, function (context, extension) {
  92133. var promise = _this._loader._loadSceneAsync(context, scene);
  92134. var light = GLTF2.GLTFLoader._GetProperty(context, _this._lights, extension.light);
  92135. if (light.type !== LightType.AMBIENT) {
  92136. throw new Error(context + ": Only ambient lights are allowed on a scene");
  92137. }
  92138. _this._loader._babylonScene.ambientColor = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.Black();
  92139. return promise;
  92140. });
  92141. };
  92142. KHR_lights.prototype._loadNodeAsync = function (context, node) {
  92143. var _this = this;
  92144. return this._loadExtensionAsync(context, node, function (context, extension) {
  92145. var promise = _this._loader._loadNodeAsync(context, node);
  92146. var babylonLight;
  92147. var light = GLTF2.GLTFLoader._GetProperty(context, _this._lights, extension.light);
  92148. var name = node._babylonMesh.name;
  92149. switch (light.type) {
  92150. case LightType.AMBIENT: {
  92151. throw new Error(context + ": Ambient lights are not allowed on a node");
  92152. }
  92153. case LightType.DIRECTIONAL: {
  92154. babylonLight = new BABYLON.DirectionalLight(name, BABYLON.Vector3.Forward(), _this._loader._babylonScene);
  92155. break;
  92156. }
  92157. case LightType.POINT: {
  92158. babylonLight = new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), _this._loader._babylonScene);
  92159. break;
  92160. }
  92161. case LightType.SPOT: {
  92162. var spotLight = light;
  92163. // TODO: support inner and outer cone angles
  92164. //const innerConeAngle = spotLight.innerConeAngle || 0;
  92165. var outerConeAngle = spotLight.outerConeAngle || Math.PI / 4;
  92166. babylonLight = new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward(), outerConeAngle, 2, _this._loader._babylonScene);
  92167. break;
  92168. }
  92169. default: {
  92170. throw new Error(context + ": Invalid light type " + light.type);
  92171. }
  92172. }
  92173. babylonLight.diffuse = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.White();
  92174. babylonLight.intensity = light.intensity == undefined ? 1 : light.intensity;
  92175. babylonLight.parent = node._babylonMesh;
  92176. return promise;
  92177. });
  92178. };
  92179. Object.defineProperty(KHR_lights.prototype, "_lights", {
  92180. get: function () {
  92181. var extensions = this._loader._gltf.extensions;
  92182. if (!extensions || !extensions[this.name]) {
  92183. throw new Error("#/extensions: " + this.name + " not found");
  92184. }
  92185. var extension = extensions[this.name];
  92186. return extension.lights;
  92187. },
  92188. enumerable: true,
  92189. configurable: true
  92190. });
  92191. return KHR_lights;
  92192. }(GLTF2.GLTFLoaderExtension));
  92193. Extensions.KHR_lights = KHR_lights;
  92194. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_lights(loader); });
  92195. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  92196. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  92197. })(BABYLON || (BABYLON = {}));
  92198. //# sourceMappingURL=KHR_lights.js.map
  92199. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  92200. globalObject["BABYLON"] = BABYLON;
  92201. var EffectFallbacks = BABYLON.EffectFallbacks;var EffectCreationOptions = BABYLON.EffectCreationOptions;var Effect = BABYLON.Effect;var KeyboardEventTypes = BABYLON.KeyboardEventTypes;var KeyboardInfo = BABYLON.KeyboardInfo;var KeyboardInfoPre = BABYLON.KeyboardInfoPre;var PointerEventTypes = BABYLON.PointerEventTypes;var PointerInfoBase = BABYLON.PointerInfoBase;var PointerInfoPre = BABYLON.PointerInfoPre;var PointerInfo = BABYLON.PointerInfo;var Color3 = BABYLON.Color3;var Color4 = BABYLON.Color4;var Vector2 = BABYLON.Vector2;var Vector3 = BABYLON.Vector3;var Vector4 = BABYLON.Vector4;var Size = BABYLON.Size;var Quaternion = BABYLON.Quaternion;var Matrix = BABYLON.Matrix;var Plane = BABYLON.Plane;var Viewport = BABYLON.Viewport;var Frustum = BABYLON.Frustum;var Axis = BABYLON.Axis;var BezierCurve = BABYLON.BezierCurve;var Angle = BABYLON.Angle;var Arc2 = BABYLON.Arc2;var Path2 = BABYLON.Path2;var Path3D = BABYLON.Path3D;var Curve3 = BABYLON.Curve3;var PositionNormalVertex = BABYLON.PositionNormalVertex;var PositionNormalTextureVertex = BABYLON.PositionNormalTextureVertex;var Tmp = BABYLON.Tmp;var Scalar = BABYLON.Scalar;var expandToProperty = BABYLON.expandToProperty;var serialize = BABYLON.serialize;var serializeAsTexture = BABYLON.serializeAsTexture;var serializeAsColor3 = BABYLON.serializeAsColor3;var serializeAsFresnelParameters = BABYLON.serializeAsFresnelParameters;var serializeAsVector2 = BABYLON.serializeAsVector2;var serializeAsVector3 = BABYLON.serializeAsVector3;var serializeAsMeshReference = BABYLON.serializeAsMeshReference;var serializeAsColorCurves = BABYLON.serializeAsColorCurves;var serializeAsColor4 = BABYLON.serializeAsColor4;var serializeAsImageProcessingConfiguration = BABYLON.serializeAsImageProcessingConfiguration;var serializeAsQuaternion = BABYLON.serializeAsQuaternion;var SerializationHelper = BABYLON.SerializationHelper;var Deferred = BABYLON.Deferred;var EventState = BABYLON.EventState;var Observer = BABYLON.Observer;var MultiObserver = BABYLON.MultiObserver;var Observable = BABYLON.Observable;var SmartArray = BABYLON.SmartArray;var SmartArrayNoDuplicate = BABYLON.SmartArrayNoDuplicate;var LoadFileError = BABYLON.LoadFileError;var RetryStrategy = BABYLON.RetryStrategy;var Tools = BABYLON.Tools;var PerfCounter = BABYLON.PerfCounter;var className = BABYLON.className;var AsyncLoop = BABYLON.AsyncLoop;var PromisePolyfill = BABYLON.PromisePolyfill;var _AlphaState = BABYLON._AlphaState;var _DepthCullingState = BABYLON._DepthCullingState;var _StencilState = BABYLON._StencilState;var InstancingAttributeInfo = BABYLON.InstancingAttributeInfo;var RenderTargetCreationOptions = BABYLON.RenderTargetCreationOptions;var EngineCapabilities = BABYLON.EngineCapabilities;var Engine = BABYLON.Engine;var Node = BABYLON.Node;var BoundingSphere = BABYLON.BoundingSphere;var BoundingBox = BABYLON.BoundingBox;var BoundingInfo = BABYLON.BoundingInfo;var TransformNode = BABYLON.TransformNode;var AbstractMesh = BABYLON.AbstractMesh;var Light = BABYLON.Light;var Camera = BABYLON.Camera;var RenderingManager = BABYLON.RenderingManager;var RenderingGroup = BABYLON.RenderingGroup;var RenderingGroupInfo = BABYLON.RenderingGroupInfo;var Scene = BABYLON.Scene;var KeepAssets = BABYLON.KeepAssets;var AssetContainer = BABYLON.AssetContainer;var Buffer = BABYLON.Buffer;var VertexBuffer = BABYLON.VertexBuffer;var DummyInternalTextureTracker = BABYLON.DummyInternalTextureTracker;var InternalTexture = BABYLON.InternalTexture;var BaseTexture = BABYLON.BaseTexture;var Texture = BABYLON.Texture;var _InstancesBatch = BABYLON._InstancesBatch;var Mesh = BABYLON.Mesh;var BaseSubMesh = BABYLON.BaseSubMesh;var SubMesh = BABYLON.SubMesh;var MaterialDefines = BABYLON.MaterialDefines;var Material = BABYLON.Material;var UniformBuffer = BABYLON.UniformBuffer;var VertexData = BABYLON.VertexData;var Geometry = BABYLON.Geometry;var _PrimitiveGeometry = BABYLON._PrimitiveGeometry;var RibbonGeometry = BABYLON.RibbonGeometry;var BoxGeometry = BABYLON.BoxGeometry;var SphereGeometry = BABYLON.SphereGeometry;var DiscGeometry = BABYLON.DiscGeometry;var CylinderGeometry = BABYLON.CylinderGeometry;var TorusGeometry = BABYLON.TorusGeometry;var GroundGeometry = BABYLON.GroundGeometry;var TiledGroundGeometry = BABYLON.TiledGroundGeometry;var PlaneGeometry = BABYLON.PlaneGeometry;var TorusKnotGeometry = BABYLON.TorusKnotGeometry;var PostProcessManager = BABYLON.PostProcessManager;var PerformanceMonitor = BABYLON.PerformanceMonitor;var RollingAverage = BABYLON.RollingAverage;var ImageProcessingConfiguration = BABYLON.ImageProcessingConfiguration;var ColorGradingTexture = BABYLON.ColorGradingTexture;var ColorCurves = BABYLON.ColorCurves;var MaterialHelper = BABYLON.MaterialHelper;var PushMaterial = BABYLON.PushMaterial;var StandardMaterialDefines = BABYLON.StandardMaterialDefines;var StandardMaterial = BABYLON.StandardMaterial;var PBRBaseMaterial = BABYLON.PBRBaseMaterial;var PBRBaseSimpleMaterial = BABYLON.PBRBaseSimpleMaterial;var PBRMaterial = BABYLON.PBRMaterial;var PBRMetallicRoughnessMaterial = BABYLON.PBRMetallicRoughnessMaterial;var PBRSpecularGlossinessMaterial = BABYLON.PBRSpecularGlossinessMaterial;var CameraInputsManager = BABYLON.CameraInputsManager;var TargetCamera = BABYLON.TargetCamera;var FreeCameraMouseInput = BABYLON.FreeCameraMouseInput;var FreeCameraKeyboardMoveInput = BABYLON.FreeCameraKeyboardMoveInput;var FreeCameraInputsManager = BABYLON.FreeCameraInputsManager;var FreeCamera = BABYLON.FreeCamera;var ArcRotateCameraKeyboardMoveInput = BABYLON.ArcRotateCameraKeyboardMoveInput;var ArcRotateCameraMouseWheelInput = BABYLON.ArcRotateCameraMouseWheelInput;var ArcRotateCameraPointersInput = BABYLON.ArcRotateCameraPointersInput;var ArcRotateCameraInputsManager = BABYLON.ArcRotateCameraInputsManager;var ArcRotateCamera = BABYLON.ArcRotateCamera;var HemisphericLight = BABYLON.HemisphericLight;var ShadowLight = BABYLON.ShadowLight;var PointLight = BABYLON.PointLight;var DirectionalLight = BABYLON.DirectionalLight;var SpotLight = BABYLON.SpotLight;var AnimationRange = BABYLON.AnimationRange;var AnimationEvent = BABYLON.AnimationEvent;var PathCursor = BABYLON.PathCursor;var Animation = BABYLON.Animation;var TargetedAnimation = BABYLON.TargetedAnimation;var AnimationGroup = BABYLON.AnimationGroup;var RuntimeAnimation = BABYLON.RuntimeAnimation;var Animatable = BABYLON.Animatable;var EasingFunction = BABYLON.EasingFunction;var CircleEase = BABYLON.CircleEase;var BackEase = BABYLON.BackEase;var BounceEase = BABYLON.BounceEase;var CubicEase = BABYLON.CubicEase;var ElasticEase = BABYLON.ElasticEase;var ExponentialEase = BABYLON.ExponentialEase;var PowerEase = BABYLON.PowerEase;var QuadraticEase = BABYLON.QuadraticEase;var QuarticEase = BABYLON.QuarticEase;var QuinticEase = BABYLON.QuinticEase;var SineEase = BABYLON.SineEase;var BezierCurveEase = BABYLON.BezierCurveEase;var Condition = BABYLON.Condition;var ValueCondition = BABYLON.ValueCondition;var PredicateCondition = BABYLON.PredicateCondition;var StateCondition = BABYLON.StateCondition;var Action = BABYLON.Action;var ActionEvent = BABYLON.ActionEvent;var ActionManager = BABYLON.ActionManager;var InterpolateValueAction = BABYLON.InterpolateValueAction;var SwitchBooleanAction = BABYLON.SwitchBooleanAction;var SetStateAction = BABYLON.SetStateAction;var SetValueAction = BABYLON.SetValueAction;var IncrementValueAction = BABYLON.IncrementValueAction;var PlayAnimationAction = BABYLON.PlayAnimationAction;var StopAnimationAction = BABYLON.StopAnimationAction;var DoNothingAction = BABYLON.DoNothingAction;var CombineAction = BABYLON.CombineAction;var ExecuteCodeAction = BABYLON.ExecuteCodeAction;var SetParentAction = BABYLON.SetParentAction;var PlaySoundAction = BABYLON.PlaySoundAction;var StopSoundAction = BABYLON.StopSoundAction;var SpriteManager = BABYLON.SpriteManager;var Sprite = BABYLON.Sprite;var IntersectionInfo = BABYLON.IntersectionInfo;var PickingInfo = BABYLON.PickingInfo;var Ray = BABYLON.Ray;var Collider = BABYLON.Collider;var CollisionCoordinatorWorker = BABYLON.CollisionCoordinatorWorker;var CollisionCoordinatorLegacy = BABYLON.CollisionCoordinatorLegacy;var Particle = BABYLON.Particle;var ParticleSystem = BABYLON.ParticleSystem;var BoxParticleEmitter = BABYLON.BoxParticleEmitter;var ConeParticleEmitter = BABYLON.ConeParticleEmitter;var SphereParticleEmitter = BABYLON.SphereParticleEmitter;var SphereDirectedParticleEmitter = BABYLON.SphereDirectedParticleEmitter;var SolidParticle = BABYLON.SolidParticle;var ModelShape = BABYLON.ModelShape;var DepthSortedParticle = BABYLON.DepthSortedParticle;var SolidParticleSystem = BABYLON.SolidParticleSystem;var ShaderMaterial = BABYLON.ShaderMaterial;var GroundMesh = BABYLON.GroundMesh;var InstancedMesh = BABYLON.InstancedMesh;var LinesMesh = BABYLON.LinesMesh;var MeshBuilder = BABYLON.MeshBuilder;var AudioEngine = BABYLON.AudioEngine;var Sound = BABYLON.Sound;var SoundTrack = BABYLON.SoundTrack;var Analyser = BABYLON.Analyser;var CubeTexture = BABYLON.CubeTexture;var RenderTargetTexture = BABYLON.RenderTargetTexture;var MultiRenderTarget = BABYLON.MultiRenderTarget;var MirrorTexture = BABYLON.MirrorTexture;var RefractionTexture = BABYLON.RefractionTexture;var DynamicTexture = BABYLON.DynamicTexture;var VideoTexture = BABYLON.VideoTexture;var RawTexture = BABYLON.RawTexture;var PostProcess = BABYLON.PostProcess;var PassPostProcess = BABYLON.PassPostProcess;var ShadowGenerator = BABYLON.ShadowGenerator;var DefaultLoadingScreen = BABYLON.DefaultLoadingScreen;var SceneLoaderProgressEvent = BABYLON.SceneLoaderProgressEvent;var SceneLoader = BABYLON.SceneLoader;var FilesInput = BABYLON.FilesInput;var StringDictionary = BABYLON.StringDictionary;var Tags = BABYLON.Tags;var AndOrNotEvaluator = BABYLON.AndOrNotEvaluator;var Database = BABYLON.Database;var FresnelParameters = BABYLON.FresnelParameters;var MultiMaterial = BABYLON.MultiMaterial;var FreeCameraTouchInput = BABYLON.FreeCameraTouchInput;var TouchCamera = BABYLON.TouchCamera;var ProceduralTexture = BABYLON.ProceduralTexture;var CustomProceduralTexture = BABYLON.CustomProceduralTexture;var FreeCameraGamepadInput = BABYLON.FreeCameraGamepadInput;var ArcRotateCameraGamepadInput = BABYLON.ArcRotateCameraGamepadInput;var GamepadManager = BABYLON.GamepadManager;var StickValues = BABYLON.StickValues;var Gamepad = BABYLON.Gamepad;var GenericPad = BABYLON.GenericPad;var Xbox360Pad = BABYLON.Xbox360Pad;var PoseEnabledControllerHelper = BABYLON.PoseEnabledControllerHelper;var PoseEnabledController = BABYLON.PoseEnabledController;var WebVRController = BABYLON.WebVRController;var OculusTouchController = BABYLON.OculusTouchController;var ViveController = BABYLON.ViveController;var GenericController = BABYLON.GenericController;var WindowsMotionController = BABYLON.WindowsMotionController;var GearVRController = BABYLON.GearVRController;var FollowCamera = BABYLON.FollowCamera;var ArcFollowCamera = BABYLON.ArcFollowCamera;var UniversalCamera = BABYLON.UniversalCamera;var GamepadCamera = BABYLON.GamepadCamera;var PostProcessRenderPipelineManager = BABYLON.PostProcessRenderPipelineManager;var PostProcessRenderEffect = BABYLON.PostProcessRenderEffect;var PostProcessRenderPipeline = BABYLON.PostProcessRenderPipeline;var DepthRenderer = BABYLON.DepthRenderer;var SSAORenderingPipeline = BABYLON.SSAORenderingPipeline;var SSAO2RenderingPipeline = BABYLON.SSAO2RenderingPipeline;var LensRenderingPipeline = BABYLON.LensRenderingPipeline;var StandardRenderingPipeline = BABYLON.StandardRenderingPipeline;var FxaaPostProcess = BABYLON.FxaaPostProcess;var CircleOfConfusionPostProcess = BABYLON.CircleOfConfusionPostProcess;var DepthOfFieldMergePostProcess = BABYLON.DepthOfFieldMergePostProcess;var DepthOfFieldEffect = BABYLON.DepthOfFieldEffect;var DefaultRenderingPipeline = BABYLON.DefaultRenderingPipeline;var GeometryBufferRenderer = BABYLON.GeometryBufferRenderer;var RefractionPostProcess = BABYLON.RefractionPostProcess;var BlackAndWhitePostProcess = BABYLON.BlackAndWhitePostProcess;var ConvolutionPostProcess = BABYLON.ConvolutionPostProcess;var FilterPostProcess = BABYLON.FilterPostProcess;var VolumetricLightScatteringPostProcess = BABYLON.VolumetricLightScatteringPostProcess;var ColorCorrectionPostProcess = BABYLON.ColorCorrectionPostProcess;var TonemapPostProcess = BABYLON.TonemapPostProcess;var DisplayPassPostProcess = BABYLON.DisplayPassPostProcess;var HighlightsPostProcess = BABYLON.HighlightsPostProcess;var ImageProcessingPostProcess = BABYLON.ImageProcessingPostProcess;var BlurPostProcess = BABYLON.BlurPostProcess;var Bone = BABYLON.Bone;var BoneIKController = BABYLON.BoneIKController;var BoneLookController = BABYLON.BoneLookController;var Skeleton = BABYLON.Skeleton;var SphericalPolynomial = BABYLON.SphericalPolynomial;var SphericalHarmonics = BABYLON.SphericalHarmonics;var CubeMapToSphericalPolynomialTools = BABYLON.CubeMapToSphericalPolynomialTools;var PanoramaToCubeMapTools = BABYLON.PanoramaToCubeMapTools;var HDRTools = BABYLON.HDRTools;var HDRCubeTexture = BABYLON.HDRCubeTexture;var Polygon = BABYLON.Polygon;var PolygonMeshBuilder = BABYLON.PolygonMeshBuilder;var CSG = BABYLON.CSG;var LensFlare = BABYLON.LensFlare;var LensFlareSystem = BABYLON.LensFlareSystem;var PhysicsJoint = BABYLON.PhysicsJoint;var DistanceJoint = BABYLON.DistanceJoint;var MotorEnabledJoint = BABYLON.MotorEnabledJoint;var HingeJoint = BABYLON.HingeJoint;var Hinge2Joint = BABYLON.Hinge2Joint;var PhysicsImpostor = BABYLON.PhysicsImpostor;var PhysicsEngine = BABYLON.PhysicsEngine;var PhysicsHelper = BABYLON.PhysicsHelper;var PhysicsRadialExplosionEvent = BABYLON.PhysicsRadialExplosionEvent;var PhysicsGravitationalFieldEvent = BABYLON.PhysicsGravitationalFieldEvent;var PhysicsUpdraftEvent = BABYLON.PhysicsUpdraftEvent;var PhysicsVortexEvent = BABYLON.PhysicsVortexEvent;var CannonJSPlugin = BABYLON.CannonJSPlugin;var OimoJSPlugin = BABYLON.OimoJSPlugin;var TGATools = BABYLON.TGATools;var DDSTools = BABYLON.DDSTools;var KhronosTextureContainer = BABYLON.KhronosTextureContainer;var Debug = BABYLON.Debug;var RayHelper = BABYLON.RayHelper;var DebugLayer = BABYLON.DebugLayer;var BoundingBoxRenderer = BABYLON.BoundingBoxRenderer;var MorphTarget = BABYLON.MorphTarget;var MorphTargetManager = BABYLON.MorphTargetManager;var Octree = BABYLON.Octree;var OctreeBlock = BABYLON.OctreeBlock;var VRDistortionCorrectionPostProcess = BABYLON.VRDistortionCorrectionPostProcess;var AnaglyphPostProcess = BABYLON.AnaglyphPostProcess;var StereoscopicInterlacePostProcess = BABYLON.StereoscopicInterlacePostProcess;var FreeCameraDeviceOrientationInput = BABYLON.FreeCameraDeviceOrientationInput;var ArcRotateCameraVRDeviceOrientationInput = BABYLON.ArcRotateCameraVRDeviceOrientationInput;var VRCameraMetrics = BABYLON.VRCameraMetrics;var WebVRFreeCamera = BABYLON.WebVRFreeCamera;var DeviceOrientationCamera = BABYLON.DeviceOrientationCamera;var VRDeviceOrientationFreeCamera = BABYLON.VRDeviceOrientationFreeCamera;var VRDeviceOrientationGamepadCamera = BABYLON.VRDeviceOrientationGamepadCamera;var VRDeviceOrientationArcRotateCamera = BABYLON.VRDeviceOrientationArcRotateCamera;var AnaglyphFreeCamera = BABYLON.AnaglyphFreeCamera;var AnaglyphArcRotateCamera = BABYLON.AnaglyphArcRotateCamera;var AnaglyphGamepadCamera = BABYLON.AnaglyphGamepadCamera;var AnaglyphUniversalCamera = BABYLON.AnaglyphUniversalCamera;var StereoscopicFreeCamera = BABYLON.StereoscopicFreeCamera;var StereoscopicArcRotateCamera = BABYLON.StereoscopicArcRotateCamera;var StereoscopicGamepadCamera = BABYLON.StereoscopicGamepadCamera;var StereoscopicUniversalCamera = BABYLON.StereoscopicUniversalCamera;var VRExperienceHelper = BABYLON.VRExperienceHelper;var VirtualJoystick = BABYLON.VirtualJoystick;var VirtualJoysticksCamera = BABYLON.VirtualJoysticksCamera;var FreeCameraVirtualJoystickInput = BABYLON.FreeCameraVirtualJoystickInput;var SimplificationSettings = BABYLON.SimplificationSettings;var SimplificationQueue = BABYLON.SimplificationQueue;var DecimationTriangle = BABYLON.DecimationTriangle;var DecimationVertex = BABYLON.DecimationVertex;var QuadraticMatrix = BABYLON.QuadraticMatrix;var Reference = BABYLON.Reference;var QuadraticErrorSimplification = BABYLON.QuadraticErrorSimplification;var MeshLODLevel = BABYLON.MeshLODLevel;var SceneOptimization = BABYLON.SceneOptimization;var TextureOptimization = BABYLON.TextureOptimization;var HardwareScalingOptimization = BABYLON.HardwareScalingOptimization;var ShadowsOptimization = BABYLON.ShadowsOptimization;var PostProcessesOptimization = BABYLON.PostProcessesOptimization;var LensFlaresOptimization = BABYLON.LensFlaresOptimization;var CustomOptimization = BABYLON.CustomOptimization;var ParticlesOptimization = BABYLON.ParticlesOptimization;var RenderTargetsOptimization = BABYLON.RenderTargetsOptimization;var MergeMeshesOptimization = BABYLON.MergeMeshesOptimization;var SceneOptimizerOptions = BABYLON.SceneOptimizerOptions;var SceneOptimizer = BABYLON.SceneOptimizer;var OutlineRenderer = BABYLON.OutlineRenderer;var EdgesRenderer = BABYLON.EdgesRenderer;var EffectLayer = BABYLON.EffectLayer;var HighlightLayer = BABYLON.HighlightLayer;var GlowLayer = BABYLON.GlowLayer;var AbstractAssetTask = BABYLON.AbstractAssetTask;var AssetsProgressEvent = BABYLON.AssetsProgressEvent;var MeshAssetTask = BABYLON.MeshAssetTask;var TextFileAssetTask = BABYLON.TextFileAssetTask;var BinaryFileAssetTask = BABYLON.BinaryFileAssetTask;var ImageAssetTask = BABYLON.ImageAssetTask;var TextureAssetTask = BABYLON.TextureAssetTask;var CubeTextureAssetTask = BABYLON.CubeTextureAssetTask;var HDRCubeTextureAssetTask = BABYLON.HDRCubeTextureAssetTask;var AssetsManager = BABYLON.AssetsManager;var SceneSerializer = BABYLON.SceneSerializer;var ReflectionProbe = BABYLON.ReflectionProbe;var Layer = BABYLON.Layer;var TextureTools = BABYLON.TextureTools;var FramingBehavior = BABYLON.FramingBehavior;var BouncingBehavior = BABYLON.BouncingBehavior;var AutoRotationBehavior = BABYLON.AutoRotationBehavior;var EngineInstrumentation = BABYLON.EngineInstrumentation;var SceneInstrumentation = BABYLON.SceneInstrumentation;var _TimeToken = BABYLON._TimeToken;var BackgroundMaterial = BABYLON.BackgroundMaterial;var EnvironmentHelper = BABYLON.EnvironmentHelper;var GridMaterial = BABYLON.GridMaterial;var GLTFFileLoader = BABYLON.GLTFFileLoader;
  92202. export { EffectFallbacks,EffectCreationOptions,Effect,KeyboardEventTypes,KeyboardInfo,KeyboardInfoPre,PointerEventTypes,PointerInfoBase,PointerInfoPre,PointerInfo,Color3,Color4,Vector2,Vector3,Vector4,Size,Quaternion,Matrix,Plane,Viewport,Frustum,Axis,BezierCurve,Angle,Arc2,Path2,Path3D,Curve3,PositionNormalVertex,PositionNormalTextureVertex,Tmp,Scalar,expandToProperty,serialize,serializeAsTexture,serializeAsColor3,serializeAsFresnelParameters,serializeAsVector2,serializeAsVector3,serializeAsMeshReference,serializeAsColorCurves,serializeAsColor4,serializeAsImageProcessingConfiguration,serializeAsQuaternion,SerializationHelper,Deferred,EventState,Observer,MultiObserver,Observable,SmartArray,SmartArrayNoDuplicate,LoadFileError,RetryStrategy,Tools,PerfCounter,className,AsyncLoop,PromisePolyfill,_AlphaState,_DepthCullingState,_StencilState,InstancingAttributeInfo,RenderTargetCreationOptions,EngineCapabilities,Engine,Node,BoundingSphere,BoundingBox,BoundingInfo,TransformNode,AbstractMesh,Light,Camera,RenderingManager,RenderingGroup,RenderingGroupInfo,Scene,KeepAssets,AssetContainer,Buffer,VertexBuffer,DummyInternalTextureTracker,InternalTexture,BaseTexture,Texture,_InstancesBatch,Mesh,BaseSubMesh,SubMesh,MaterialDefines,Material,UniformBuffer,VertexData,Geometry,_PrimitiveGeometry,RibbonGeometry,BoxGeometry,SphereGeometry,DiscGeometry,CylinderGeometry,TorusGeometry,GroundGeometry,TiledGroundGeometry,PlaneGeometry,TorusKnotGeometry,PostProcessManager,PerformanceMonitor,RollingAverage,ImageProcessingConfiguration,ColorGradingTexture,ColorCurves,MaterialHelper,PushMaterial,StandardMaterialDefines,StandardMaterial,PBRBaseMaterial,PBRBaseSimpleMaterial,PBRMaterial,PBRMetallicRoughnessMaterial,PBRSpecularGlossinessMaterial,CameraInputsManager,TargetCamera,FreeCameraMouseInput,FreeCameraKeyboardMoveInput,FreeCameraInputsManager,FreeCamera,ArcRotateCameraKeyboardMoveInput,ArcRotateCameraMouseWheelInput,ArcRotateCameraPointersInput,ArcRotateCameraInputsManager,ArcRotateCamera,HemisphericLight,ShadowLight,PointLight,DirectionalLight,SpotLight,AnimationRange,AnimationEvent,PathCursor,Animation,TargetedAnimation,AnimationGroup,RuntimeAnimation,Animatable,EasingFunction,CircleEase,BackEase,BounceEase,CubicEase,ElasticEase,ExponentialEase,PowerEase,QuadraticEase,QuarticEase,QuinticEase,SineEase,BezierCurveEase,Condition,ValueCondition,PredicateCondition,StateCondition,Action,ActionEvent,ActionManager,InterpolateValueAction,SwitchBooleanAction,SetStateAction,SetValueAction,IncrementValueAction,PlayAnimationAction,StopAnimationAction,DoNothingAction,CombineAction,ExecuteCodeAction,SetParentAction,PlaySoundAction,StopSoundAction,SpriteManager,Sprite,IntersectionInfo,PickingInfo,Ray,Collider,CollisionCoordinatorWorker,CollisionCoordinatorLegacy,Particle,ParticleSystem,BoxParticleEmitter,ConeParticleEmitter,SphereParticleEmitter,SphereDirectedParticleEmitter,SolidParticle,ModelShape,DepthSortedParticle,SolidParticleSystem,ShaderMaterial,GroundMesh,InstancedMesh,LinesMesh,MeshBuilder,AudioEngine,Sound,SoundTrack,Analyser,CubeTexture,RenderTargetTexture,MultiRenderTarget,MirrorTexture,RefractionTexture,DynamicTexture,VideoTexture,RawTexture,PostProcess,PassPostProcess,ShadowGenerator,DefaultLoadingScreen,SceneLoaderProgressEvent,SceneLoader,FilesInput,StringDictionary,Tags,AndOrNotEvaluator,Database,FresnelParameters,MultiMaterial,FreeCameraTouchInput,TouchCamera,ProceduralTexture,CustomProceduralTexture,FreeCameraGamepadInput,ArcRotateCameraGamepadInput,GamepadManager,StickValues,Gamepad,GenericPad,Xbox360Pad,PoseEnabledControllerHelper,PoseEnabledController,WebVRController,OculusTouchController,ViveController,GenericController,WindowsMotionController,GearVRController,FollowCamera,ArcFollowCamera,UniversalCamera,GamepadCamera,PostProcessRenderPipelineManager,PostProcessRenderEffect,PostProcessRenderPipeline,DepthRenderer,SSAORenderingPipeline,SSAO2RenderingPipeline,LensRenderingPipeline,StandardRenderingPipeline,FxaaPostProcess,CircleOfConfusionPostProcess,DepthOfFieldMergePostProcess,DepthOfFieldEffect,DefaultRenderingPipeline,GeometryBufferRenderer,RefractionPostProcess,BlackAndWhitePostProcess,ConvolutionPostProcess,FilterPostProcess,VolumetricLightScatteringPostProcess,ColorCorrectionPostProcess,TonemapPostProcess,DisplayPassPostProcess,HighlightsPostProcess,ImageProcessingPostProcess,BlurPostProcess,Bone,BoneIKController,BoneLookController,Skeleton,SphericalPolynomial,SphericalHarmonics,CubeMapToSphericalPolynomialTools,PanoramaToCubeMapTools,HDRTools,HDRCubeTexture,Polygon,PolygonMeshBuilder,CSG,LensFlare,LensFlareSystem,PhysicsJoint,DistanceJoint,MotorEnabledJoint,HingeJoint,Hinge2Joint,PhysicsImpostor,PhysicsEngine,PhysicsHelper,PhysicsRadialExplosionEvent,PhysicsGravitationalFieldEvent,PhysicsUpdraftEvent,PhysicsVortexEvent,CannonJSPlugin,OimoJSPlugin,TGATools,DDSTools,KhronosTextureContainer,Debug,RayHelper,DebugLayer,BoundingBoxRenderer,MorphTarget,MorphTargetManager,Octree,OctreeBlock,VRDistortionCorrectionPostProcess,AnaglyphPostProcess,StereoscopicInterlacePostProcess,FreeCameraDeviceOrientationInput,ArcRotateCameraVRDeviceOrientationInput,VRCameraMetrics,WebVRFreeCamera,DeviceOrientationCamera,VRDeviceOrientationFreeCamera,VRDeviceOrientationGamepadCamera,VRDeviceOrientationArcRotateCamera,AnaglyphFreeCamera,AnaglyphArcRotateCamera,AnaglyphGamepadCamera,AnaglyphUniversalCamera,StereoscopicFreeCamera,StereoscopicArcRotateCamera,StereoscopicGamepadCamera,StereoscopicUniversalCamera,VRExperienceHelper,VirtualJoystick,VirtualJoysticksCamera,FreeCameraVirtualJoystickInput,SimplificationSettings,SimplificationQueue,DecimationTriangle,DecimationVertex,QuadraticMatrix,Reference,QuadraticErrorSimplification,MeshLODLevel,SceneOptimization,TextureOptimization,HardwareScalingOptimization,ShadowsOptimization,PostProcessesOptimization,LensFlaresOptimization,CustomOptimization,ParticlesOptimization,RenderTargetsOptimization,MergeMeshesOptimization,SceneOptimizerOptions,SceneOptimizer,OutlineRenderer,EdgesRenderer,EffectLayer,HighlightLayer,GlowLayer,AbstractAssetTask,AssetsProgressEvent,MeshAssetTask,TextFileAssetTask,BinaryFileAssetTask,ImageAssetTask,TextureAssetTask,CubeTextureAssetTask,HDRCubeTextureAssetTask,AssetsManager,SceneSerializer,ReflectionProbe,Layer,TextureTools,FramingBehavior,BouncingBehavior,AutoRotationBehavior,EngineInstrumentation,SceneInstrumentation,_TimeToken,BackgroundMaterial,EnvironmentHelper,GridMaterial,GLTFFileLoader };